控制台 ↗
API 接入OpenAI Compatible

Chat Completions

OpenAI 兼容对话接口

接口

POSThttps://www.yunqiai.chat/v1/chat/completions

所有请求使用 HTTPS,并通过请求头携带访问密钥。

请求参数

参数类型说明
model必填string要调用的模型 ID
messages必填arraysystem / user / assistant / tool 消息数组
max_completion_tokensinteger最大生成 Token;上限随模型变化
streamboolean是否以 SSE 流式返回,默认 false
temperaturenumber0–2;推理模型建议省略并使用模型默认值
top_pnumber0–1;与 temperature 通常只设置一个
ninteger返回候选数量;通常使用 1 控制费用
stopstring | string[]可选停止序列;使用模型默认行为时省略
toolsarrayOpenAI Function Calling 工具定义
tool_choicestring | objectauto / none / required 或指定工具
response_formatobject文本或 JSON Schema 结构化输出

请求示例

cURL
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 回传结果,模型才会生成最终回答。

JSON · define tools
{
  "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
        }
      }
    }
  ]
}
JSON · message.tool_calls[]
{
  "role": "assistant",
  "content": null,
  "tool_calls": [
    {
      "id": "call_01JY7X",
      "type": "function",
      "function": {
        "name": "get_time",
        "arguments": "{\"timezone\":\"Asia/Shanghai\"}"
      }
    }
  ]
}
协议模型返回客户端回传
Chat Completionsmessage.tool_calls[] · id · function.argumentsrole: tool · tool_call_id
JSON · return tool result
{
  "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。

JSON · Base64
{
  "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]关闭本次流读取
Python · Chat Completions SSE
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不要自动重试;先检查错误正文、鉴权头、接口路径、模型与参数
JSON · error response body
{
  "error": {
    "message": "请求参数无效",
    "type": "invalid_request_error",
    "param": "model",
    "code": "invalid_model"
  }
}
协议错误正文中的请求 ID响应头中的请求 ID
Chat Completions无固定顶层字段x-request-id
Python · timeout and retry
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)

响应

JSON
{
  "id": "chatcmpl_01JY7X",
  "object": "chat.completion",
  "model": "gpt-5.6-sol",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "你好!我是一个 AI 助手。"
      },
      "finish_reason": "stop"
    }
  ]
}
YunQi AI 开放平台文档 · 客户接入与参数参考模型目录更新于 2026-08-06