API 接入OpenAI Compatible
Chat Completions
OpenAI 兼容对话接口
接口
POST
https://www.yunqiai.chat/v1/chat/completions所有请求使用 HTTPS,并通过请求头携带访问密钥。
请求参数
| 参数 | 类型 | 说明 |
|---|---|---|
model必填 | string | 要调用的模型 ID |
messages必填 | array | system / user / assistant / tool 消息数组 |
max_completion_tokens | integer | 最大生成 Token;上限随模型变化 |
stream | boolean | 是否以 SSE 流式返回,默认 false |
temperature | number | 0–2;推理模型建议省略并使用模型默认值 |
top_p | number | 0–1;与 temperature 通常只设置一个 |
n | integer | 返回候选数量;通常使用 1 控制费用 |
stop | string | string[] | 可选停止序列;使用模型默认行为时省略 |
tools | array | OpenAI Function Calling 工具定义 |
tool_choice | string | object | auto / none / required 或指定工具 |
response_format | object | 文本或 JSON Schema 结构化输出 |
请求示例
curl --request POST \
--url https://www.yunqiai.chat/v1/chat/completions \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "gpt-5.6-sol",
"messages": [
{
"role": "user",
"content": "你好,请介绍一下你自己"
}
],
"stream": false
}'工具调用闭环
先随请求发送工具定义;模型返回调用参数后,由客户端校验参数并执行本地函数,再用同一个调用 ID 回传结果,模型才会生成最终回答。
{
"model": "gpt-5.6-sol",
"messages": [
{
"role": "user",
"content": "上海现在几点?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_time",
"description": "返回指定时区的当前时间",
"parameters": {
"type": "object",
"properties": {
"timezone": {
"type": "string",
"description": "IANA 时区,例如 Asia/Shanghai"
}
},
"required": [
"timezone"
],
"additionalProperties": false
}
}
}
]
}{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_01JY7X",
"type": "function",
"function": {
"name": "get_time",
"arguments": "{\"timezone\":\"Asia/Shanghai\"}"
}
}
]
}| 协议 | 模型返回 | 客户端回传 |
|---|---|---|
| Chat Completions | message.tool_calls[] · id · function.arguments | role: tool · tool_call_id |
{
"model": "gpt-5.6-sol",
"messages": [
{
"role": "user",
"content": "上海现在几点?"
},
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_01JY7X",
"type": "function",
"function": {
"name": "get_time",
"arguments": "{\"timezone\":\"Asia/Shanghai\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_01JY7X",
"content": "{\"time\":\"14:30\"}"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_time",
"description": "返回指定时区的当前时间",
"parameters": {
"type": "object",
"properties": {
"timezone": {
"type": "string"
}
},
"required": [
"timezone"
]
}
}
}
]
}Base64 图片输入
OpenAI 兼容消息使用 image_url 内容块,url 可填写完整 Data URL。
{
"model": "gpt-5.6-sol",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "描述这张图片"
},
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,BASE64_IMAGE_DATA",
"detail": "low"
}
}
]
}
]
}流式输出
客户端以 SSE 逐行读取 data: 事件。不要按网络数据块直接解码 JSON;同一事件可能被拆成多个传输片段。
| 阶段 | 事件 | 读取内容 |
|---|---|---|
| 数据块 | data: {JSON} | 逐条解析 SSE data 行 |
| 文本增量 | choices[].delta.content | 按候选顺序拼接文本 |
| 工具参数 | choices[].delta.tool_calls[] | 按 choice.index + 工具 index 分组并拼接 function.arguments |
| 候选结束 | choices[].finish_reason | 非 null 表示该候选结束 |
| 流结束 | data: [DONE] | 关闭本次流读取 |
import json
import os
import requests
payload = {
"model": "gpt-5.6-sol",
"messages": [{"role": "user", "content": "用三句话解释量子计算"}],
"stream": True,
}
with requests.post(
"https://www.yunqiai.chat/v1/chat/completions",
headers={
"Authorization": f"Bearer {os.environ['YUNQI_API_KEY']}",
"Content-Type": "application/json",
},
json=payload,
stream=True,
timeout=(10, 180),
) as response:
response.raise_for_status()
done = False
tool_calls = {}
for line in response.iter_lines(decode_unicode=True):
if not line or not line.startswith("data: "):
continue
data = line[6:]
if data == "[DONE]":
done = True
break
chunk = json.loads(data)
if chunk.get("error"):
raise RuntimeError(chunk["error"].get("message", "stream error"))
for choice in chunk.get("choices", []):
choice_index = choice.get("index", 0)
delta = choice.get("delta", {})
text = delta.get("content")
if text:
print(text, end="", flush=True)
for call in delta.get("tool_calls", []):
tool_index = call.get("index", 0)
key = (choice_index, tool_index)
current = tool_calls.setdefault(key, {"choice_index": choice_index, "id": "", "name": "", "arguments": ""})
if call.get("id"):
current["id"] = call["id"]
function = call.get("function") or {}
if function.get("name"):
current["name"] = function["name"]
current["arguments"] += function.get("arguments", "")
if not done:
raise RuntimeError("stream ended before [DONE]")
print()
for call in tool_calls.values():
call["arguments"] = json.loads(call["arguments"])
print("tool", call)错误、重试与超时
| 情况 | 客户端处理 |
|---|---|
| 连接超时 | 单独设置连接超时,例如 10 秒;确认网络与 Base URL |
| 读取超时 | 文本请求可从 180 秒起设置;图像等耗时任务可设为 300 秒 |
| 408、429、5xx | 读取 Retry-After,并使用带随机抖动的指数退避;限制重试次数 |
| 400、401、403、404 | 不要自动重试;先检查错误正文、鉴权头、接口路径、模型与参数 |
{
"error": {
"message": "请求参数无效",
"type": "invalid_request_error",
"param": "model",
"code": "invalid_model"
}
}| 协议 | 错误正文中的请求 ID | 响应头中的请求 ID |
|---|---|---|
| Chat Completions | 无固定顶层字段 | x-request-id |
import os
import random
import time
import requests
url = "https://www.yunqiai.chat/v1/chat/completions"
headers = {"Authorization": f"Bearer {os.environ['YUNQI_API_KEY']}"}
payload = {"model": "gpt-5.6-sol", "messages": [{"role": "user", "content": "你好"}]}
for attempt in range(4):
delay = min(2 ** attempt, 8) + random.random()
try:
response = requests.post(url, headers=headers, json=payload, timeout=(10, 180))
except requests.Timeout:
if attempt == 3:
raise
else:
if response.ok:
print(response.json())
break
if response.status_code not in {408, 429, 500, 502, 503, 504}:
response.raise_for_status()
if attempt == 3:
response.raise_for_status()
retry_after = response.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
pass
time.sleep(delay)响应
{
"id": "chatcmpl_01JY7X",
"object": "chat.completion",
"model": "gpt-5.6-sol",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "你好!我是一个 AI 助手。"
},
"finish_reason": "stop"
}
]
}协议参考
本页示例按 YunQi AI 的模型 ID、接口路径和参数格式编写;以下链接提供对应协议的字段说明。