# ChatCompletions 格式
> 与 OpenAI Chat Completions 完全兼容，是最通用的对话入口
> 流式与非流式是同一个接口，区别只在请求体的 `stream` 字段
> 默认流式返回，收到 `data: [DONE]` 结束；传 `stream: false` 则一次返回完整结果
`POST /v1/chat/completions`
## 认证
- `Authorization` (string / 必填) — 所有接口均使用 Bearer Token 进行认证。 获取 API Key：[访问控制台](https://api.oairoute.com/keys) 创建。 请求时在请求头中添加： ```http Authorization: Bearer YOUR_OAIRoute_KEY ```
## 请求参数
- `model` (string / 必填) — 模型 ID。可先调用模型列表接口获取当前可用清单。
- `messages` (array / 必填) — 对话消息数组，按时间顺序排列。每个元素的结构见下列字段。
- `messages[].role` (string / 必填) — 消息角色。取值 `system` 系统提示、`user` 用户输入、`assistant` 模型回复、`tool` 工具返回。
- `messages[].content` (string / 必填) — 消息正文。多模态时可传内容块数组，元素含 `type` 与对应字段。
- `messages[].name` (string / 可选) — 参与者名称，用于区分同一角色下的多个说话人。
- `messages[].tool_call_id` (string / 可选) — `role` 为 `tool` 时必填，指向对应的工具调用 ID。
- `stream` (boolean / 可选) — 是否流式返回。默认 `true`，以 SSE 事件流逐块返回；传 `false` 则一次返回完整响应。两种模式共用同一套参数，只有响应形态不同。
- `stream_options.include_usage` (boolean / 可选) — 是否在流的最后追加一条 `usage` 统计。
- `temperature` (number / 可选) — 采样温度，取值 0 到 2。数值越低输出越确定。
- `top_p` (number / 可选) — 核采样阈值，取值 0 到 1。建议不要与 `temperature` 同时调整。
- `max_tokens` (integer / 可选) — 生成的最大 token 数。不同模型的上限不同，超出会被截断。
- `stop` (string | array / 可选) — 停止标记。命中其一即结束生成，且标记本身不计入输出。
- `presence_penalty` (number / 可选) — 存在惩罚，取值 -2 到 2。正值鼓励引入新话题。
- `frequency_penalty` (number / 可选) — 频率惩罚，取值 -2 到 2。正值抑制重复用词。
- `seed` (integer / 可选) — 随机种子。相同种子与相同参数结果相近，但不保证完全一致。
- `tools` (array / 可选) — 可用工具清单，结构与 OpenAI 一致。
- `tools[].type` (string / 必填) — 固定为 `function`。
- `tools[].function.name` (string / 必填) — 函数名，模型会以此为标识发起调用。
- `tools[].function.description` (string / 可选) — 函数用途说明。写得越清楚，模型选错的概率越低。
- `tools[].function.parameters` (object / 必填) — 参数的 JSON Schema。
- `tool_choice` (string | object / 可选) — 工具选择策略。`auto` 由模型决定，`none` 禁止调用，也可指定某个函数。
- `response_format.type` (string / 可选) — 输出格式约束。`text` 为普通文本，`json_object` 要求返回合法 JSON。
- `n` (integer / 可选) — 生成几条候选回复，默认 1。流式下固定为 1。
- `user` (string / 可选) — 终端用户标识，用于按用户维度的统计与风控。
## 响应
`stream: false` 时返回单个完整对象，`choices[].message` 一次给全；`stream: true` 时返回 SSE 事件流，每个事件是一个 `chat.completion.chunk`，`choices[].delta` 只带增量。
- `id` (string / 可选) — 本次请求的唯一标识。
- `object` (string / 可选) — 流式为 `chat.completion.chunk`，非流式为 `chat.completion`，可按它判断该按哪种结构解析。
- `created` (integer / 可选) — 生成时间戳，Unix 秒。
- `model` (string / 可选) — 实际使用的模型。
- `choices` (array / 可选) — 候选回复数组。
- `choices[].index` (integer / 可选) — 候选序号，从 0 开始。
- `choices[].delta` (object / 可选) — 流式增量对象，每个事件只带变化的部分，正文在 `delta.content`。非流式下不出现。
- `choices[].message` (object / 可选) — 非流式完整回复，含 `role` 与 `content`，替代流式里的 `delta`。
- `choices[].finish_reason` (string / 可选) — 结束原因。`stop` 正常结束，`length` 触达长度上限，`tool_calls` 发起工具调用，`content_filter` 被内容策略拦截。流式下在最后一个事件出现。
- `usage.prompt_tokens` (integer / 可选) — 输入 token 数。
- `usage.completion_tokens` (integer / 可选) — 输出 token 数。
- `usage.total_tokens` (integer / 可选) — 两者之和。
## 流式返回示例
不传 `stream` 或传 `stream: true` 时，服务端以 SSE 逐块推送。每块是一个 `chat.completion.chunk`，正文在 `delta.content` 里，按顺序拼起来就是完整回复。
```
data: {"id":"chatcmpl-01KA","object":"chat.completion.chunk","created":1763088289,"model":"YOUR_MODEL_ID","choices":[{"index":0,"delta":{"role":"assistant","content":"你"},"finish_reason":null}]}
data: {"id":"chatcmpl-01KA","object":"chat.completion.chunk","created":1763088289,"model":"YOUR_MODEL_ID","choices":[{"index":0,"delta":{"content":"好"},"finish_reason":null}]}
data: {"id":"chatcmpl-01KA","object":"chat.completion.chunk","created":1763088289,"model":"YOUR_MODEL_ID","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
```
> **Note:**
> 每条 `data:` 后是一个完整 JSON，行与行之间以空行分隔。收到 `data: [DONE]` 表示流已结束，此时不要再等待更多数据。
## 非流式返回示例
传 `stream: false` 时一次返回完整对象，正文在 `choices[0].message.content`，`object` 为 `chat.completion`。适合后台任务、批处理与结构化抽取，不必处理分块拼装。
```
{
  "id": "chatcmpl-01KA040M0HP1GJWBJYZMKX1XS1",
  "object": "chat.completion",
  "created": 1763088289,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "你好！有什么可以帮你的？"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}
```
> **Note:**
> 非流式需要等模型输出完才返回，长文本时客户端等待更久。对首字延迟敏感的聊天界面建议用流式，其余场景用非流式更省事。
## 支持的模型列表
以下模型均可通过本接口调用。清单由模型目录自动生成，实际可用范围以你的账号分组为准：
:::models
> **Note:** 想按上下文长度、价格或能力标签挑选模型，可查阅 [模型列表元数据接口](../models.html)，或直接读取 `GET /api/pricing`。
## 流式与非流式怎么选
两种模式的数据一样，区别在传输节奏与等待方式。按场景选即可，不需要为它换接口或换 SDK。
| 场景 | 推荐 | 关键构造 |
| 聊天界面、需要首字尽快出现 | 流式 | 不传 `stream`，逐块渲染 `delta.content` |
| 后台任务、批量处理 | 非流式 | 传 `"stream": false`，直接读 `message.content` |
| 结构化抽取、要解析 JSON | 非流式 | `stream: false` + `response_format` 为 `json_object` |
| 边收边展示、最后再落库 | 流式 | 拼接 `delta` 得到全文后写入 |
## 使用示例
以下几种最常见的用法都基于同一个接口，差别只在 `messages` 的构造方式和 `stream` 参数。完整可复制的请求体见右侧代码栏，切换上方的场景页签即可对应查看。
| 场景 | 关键构造 | 对应右栏页签 |
| 基础对话 | 只放一条 `role: user` 的消息 | 基础对话 |
| 系统提示词 | 在 `messages` 最前面加一条 `role: system` | 系统提示词 |
| 多轮对话 | 把历史消息按时间顺序整体放进 `messages` | 多轮对话 |
| 流式输出 | 不传或传 `"stream": true`，响应变为 SSE 事件流 | 流式输出 |
| 非流式输出 | 传 `"stream": false`，直接读 `choices[0].message.content` | 非流式输出 |
| 工具调用 | 传 `tools` 声明函数，模型返回 `tool_calls` | 函数调用 |
| 结构化输出 | 设置 `response_format` 为 `json_object` | 结构化输出 |
| 图片输入 | `content` 传内容块数组，含 `image_url` | 图片输入 |
> **Note:** 接口本身不保存会话状态，每一轮都要把完整历史重新提交。历史越长，每轮消耗的输入 token 越多，长期会话建议在客户端做摘要，只保留最近若干轮加一份摘要。
## 错误
| HTTP | type | 说明 |
|---|---|---|
| 400 | invalid_request_error | 参数格式错误，或模型不支持某个字段 |
| 401 | authentication_error | Key 缺失或无效 |
| 402 | payment_required | 余额不足 |
| 429 | rate_limit_error | 触发限流，降低并发或稍后重试 |
**文本输入{Text input}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [{ "role": "user", "content": "你好" }],
  "stream": false
}'
```
**文本输入{Text input}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "你好" }],
    "stream": false
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**文本输入{Text input}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "你好" }],
    "stream": false
  }),
});
console.log(await res.json());
```
**流式输出{Streaming output}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [{ "role": "user", "content": "你好" }],
  "stream": true
}'
```
**流式输出{Streaming output}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "你好" }],
    "stream": true
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**流式输出{Streaming output}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "你好" }],
    "stream": true
  }),
});
console.log(await res.json());
```
**非流式输出{Non-streaming output}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [{ "role": "user", "content": "用一段话总结团队周会的要点。" }],
  "stream": false
}'
```
**非流式输出{Non-streaming output}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "用一段话总结团队周会的要点。" }],
    "stream": false
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**非流式输出{Non-streaming output}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "用一段话总结团队周会的要点。" }],
    "stream": false
  }),
});
console.log(await res.json());
```
**系统提示词{System prompt}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [
    { "role": "system", "content": "你是客服助手，回答不超过三句话，不承诺文档之外的功能。" },
    { "role": "user", "content": "你们能开发票吗" }
  ],
  "stream": false
}'
```
**系统提示词{System prompt}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [
      { "role": "system", "content": "你是客服助手，回答不超过三句话，不承诺文档之外的功能。" },
      { "role": "user", "content": "你们能开发票吗" }
    ],
    "stream": false
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**系统提示词{System prompt}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [
      { "role": "system", "content": "你是客服助手，回答不超过三句话，不承诺文档之外的功能。" },
      { "role": "user", "content": "你们能开发票吗" }
    ],
    "stream": false
  }),
});
console.log(await res.json());
```
**多轮对话{Multi-turn chat}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [
    { "role": "user", "content": "用一句话介绍杭州" },
    { "role": "assistant", "content": "杭州是浙江省会，以西湖和数字经济闻名。" },
    { "role": "user", "content": "那它的气候呢" },
  ]
}'
```
**多轮对话{Multi-turn chat}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [
      { "role": "user", "content": "用一句话介绍杭州" },
      { "role": "assistant", "content": "杭州是浙江省会，以西湖和数字经济闻名。" },
      { "role": "user", "content": "那它的气候呢" },
    ]
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**多轮对话{Multi-turn chat}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [
      { "role": "user", "content": "用一句话介绍杭州" },
      { "role": "assistant", "content": "杭州是浙江省会，以西湖和数字经济闻名。" },
      { "role": "user", "content": "那它的气候呢" },
    ]
  }),
});
console.log(await res.json());
```
**函数调用{Function calling}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [{ "role": "user", "content": "北京现在天气如何" }]
  "tools": [{
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "查询指定城市的实时天气",
      "parameters": {
        "type": "object",
        "properties": { "city": { "type": "string" } },
        "required": ["city"]
      }
    }
  }]
  "tool_choice": "auto",
  "stream": false
}'
```
**函数调用{Function calling}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "北京现在天气如何" }]
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "查询指定城市的实时天气",
        "parameters": {
          "type": "object",
          "properties": { "city": { "type": "string" } },
          "required": ["city"]
        }
      }
    }]
    "tool_choice": "auto",
    "stream": false
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**函数调用{Function calling}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [{ "role": "user", "content": "北京现在天气如何" }]
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "查询指定城市的实时天气",
        "parameters": {
          "type": "object",
          "properties": { "city": { "type": "string" } },
          "required": ["city"]
        }
      }
    }]
    "tool_choice": "auto",
    "stream": false
  }),
});
console.log(await res.json());
```
**结构化输出{Structured output}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [
    { "role": "system", "content": "从用户文本中抽取字段，返回 JSON，键为 name 与 city。" },
    { "role": "user", "content": "我叫李明，住在杭州。" }
  ]
  "response_format": { "type": "json_object" },
  "stream": false
}'
```
**结构化输出{Structured output}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [
      { "role": "system", "content": "从用户文本中抽取字段，返回 JSON，键为 name 与 city。" },
      { "role": "user", "content": "我叫李明，住在杭州。" }
    ]
    "response_format": { "type": "json_object" },
    "stream": false
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**结构化输出{Structured output}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [
      { "role": "system", "content": "从用户文本中抽取字段，返回 JSON，键为 name 与 city。" },
      { "role": "user", "content": "我叫李明，住在杭州。" }
    ]
    "response_format": { "type": "json_object" },
    "stream": false
  }),
});
console.log(await res.json());
```
**图片输入{Image input}::cURL**
```
curl --request POST https://api.oairoute.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OAIRoute_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_ID",
  "messages": [{
    "role": "user",
    "content": [
      { "type": "text", "text": "这张图里是什么" },
      { "type": "image_url", "image_url": { "url": "https://example.com/a.jpg" } }
    ],
  }]
}'
```
**图片输入{Image input}::Python**
```
import requests
url = "https://api.oairoute.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_OAIRoute_KEY"}
payload = {
    "model": "YOUR_MODEL_ID",
    "messages": [{
      "role": "user",
      "content": [
        { "type": "text", "text": "这张图里是什么" },
        { "type": "image_url", "image_url": { "url": "https://example.com/a.jpg" } }
      ],
    }]
  }
res = requests.post(url, headers=headers, json=payload)
print(res.json())
```
**图片输入{Image input}::JavaScript**
```
const res = await fetch("https://api.oairoute.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_OAIRoute_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "model": "YOUR_MODEL_ID",
    "messages": [{
      "role": "user",
      "content": [
        { "type": "text", "text": "这张图里是什么" },
        { "type": "image_url", "image_url": { "url": "https://example.com/a.jpg" } }
      ],
    }]
  }),
});
console.log(await res.json());
```