# 创建对话补全

> BigModel.io 的 POST /v1/chat/completions 接口：用 OpenAI Chat Completions 协议调用 GLM、DeepSeek、Kimi、MiniMax 等模型，支持流式、工具调用和 OpenRouter 风格的备用模型。

网页版: https://bigmodel.io/zh-cn/docs/api-chat-completions · 更新于 2026-10-18

`POST https://bigmodel.io/v1/chat/completions`

OpenAI Chat Completions 接口。所有提供文本模型的分组都能调用，包括仅对话补全分组（DeepSeek、GLM 平台）。在仅对话补全分组上请求体原样交给服务商；在其他分组上请求会被转换，部分字段会被丢弃（见下方说明）。

## 请求

```http
POST https://bigmodel.io/v1/chat/completions
```

### 认证

| 请求头 | 值 |
|---|---|
| `Authorization` | `Bearer $BIGMODEL_API_KEY` |
| `x-api-key` | `$BIGMODEL_API_KEY` |

任选其一。

### 请求体

标准 OpenAI Chat Completions 请求体。GLM、DeepSeek、Qwen 分组会把请求体原样交给服务商（只改写 `model`），各字段是否生效取决于模型。其他分组会转换请求，转换时 `response_format`、`n`、`seed`、`user`、`logprobs` 会被丢弃。

| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `model` | string | 是 | 模型目录中的模型 ID，例如 `glm-5.3`。也可用 OpenRouter 风格的名称，如 `z-ai/glm-5.3`。 |
| `models` | array<string> |  | 在 `model` 之后依次尝试的备用模型（总共最多 5 次尝试）。转发前会被移除。 |
| `messages` | array<ChatMessage> | 是 | 对话内容。 |
| `messages[].role` | string | 是 | 消息的角色。 可选值：`system`, `developer`, `user`, `assistant`, `tool` |
| `messages[].content` | string \| array<object> | 是 | 文本，或内容片段数组（`text`、`image_url`，用于支持图片输入的模型）。 |
| `messages[].tool_calls` | array<object> |  | 之前轮次中助手发起的工具调用。 |
| `messages[].tool_call_id` | string |  | `tool` 消息：对应的工具调用 ID。 |
| `stream` | boolean |  | 以 SSE 流式返回。 默认 `false` |
| `stream_options` | object |  | 流式选项。网关总会向上游请求用量。 |
| `stream_options.include_usage` | boolean |  |  |
| `max_tokens` | integer |  | 最多生成的 token 数。 |
| `max_completion_tokens` | integer |  | `max_tokens` 的新名称。 |
| `temperature` | number |  | 采样温度。 |
| `top_p` | number |  | 核采样。 |
| `stop` | string \| array<string> |  | 停止序列。 |
| `tools` | array<object> |  | 模型可调用的函数工具。 |
| `tool_choice` | string \| object |  | `auto`、`none`、`required` 或指定函数。 |
| `response_format` | object |  | JSON 模式或 JSON Schema（取决于模型是否支持）。GLM、DeepSeek、Qwen 分组原样透传；会转换请求的分组会丢弃该字段。 |
| `reasoning_effort` | string |  | 推理强度（仅支持的模型）。 |

## 响应

| 状态码 | 含义 |
|---|---|
| `200` | 对话补全结果；`stream` 为 true 时为 SSE 流。 |
| `400` | `api_key_in_query_deprecated`（Key 放在了查询参数里），或 `invalid_request_error`：请求体为空或不是合法 JSON、缺少 `model`、`stream` 不是布尔值等。 |
| `401` | `API_KEY_REQUIRED`、`INVALID_API_KEY`、`API_KEY_DISABLED`、`USER_NOT_FOUND`、`USER_INACTIVE`。 |
| `403` | `INSUFFICIENT_BALANCE`、`API_KEY_EXPIRED`、`ACCESS_DENIED`（IP 规则）、`SUBSCRIPTION_NOT_FOUND`、`SUBSCRIPTION_INVALID`，或 `permission_error`（Key 未分配分组、分组不允许该接口）。 |
| `413` | 请求体过大。 |
| `429` | `API_KEY_QUOTA_EXHAUSTED`、`USAGE_LIMIT_EXCEEDED`（套餐额度），或 `rate_limit_exceeded` / `rate_limit_error`（Key 的 5 小时/1 天/7 天限额、每分钟请求数、并发、上游限流）。每分钟限流会带 `Retry-After`。 |
| `502` | `upstream_error`：模型服务商出错。 |
| `503` | `api_error` 等：分组暂时没有该模型的可用容量，或分组不提供该模型（`No available accounts`）。 |

### 响应字段

| 字段 | 类型 | 说明 |
|---|---|---|
| `id` | string |  |
| `object` | any |  |
| `created` | integer |  |
| `model` | string | 实际回答的模型。 |
| `choices` | array<object> |  |
| `choices[].index` | integer |  |
| `choices[].message` | ChatMessage |  |
| `choices[].finish_reason` | string | `stop`, `length`, `tool_calls`, … |
| `usage` | object |  |
| `usage.prompt_tokens` | integer |  |
| `usage.completion_tokens` | integer |  |
| `usage.total_tokens` | integer |  |

`stream: true` 时返回 SSE 流，每个事件是一个 `chat.completion.chunk`，以 `data: [DONE]` 结束。网关会要求上游在最后返回用量。


## 示例

```bash [cURL]
curl https://bigmodel.io/v1/chat/completions \
  -H "Authorization: Bearer $BIGMODEL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "glm-5.3",
    "messages": [
      {"role": "system", "content": "你是一个简洁的助手。"},
      {"role": "user", "content": "用一句话解释 HTTP 429。"}
    ],
    "max_tokens": 128
  }'
```

```python [Python]
import os
from openai import OpenAI

client = OpenAI(base_url="https://bigmodel.io/v1", api_key=os.environ["BIGMODEL_API_KEY"])

resp = client.chat.completions.create(
    model="glm-5.3",
    messages=[
        {"role": "system", "content": "你是一个简洁的助手。"},
        {"role": "user", "content": "用一句话解释 HTTP 429。"},
    ],
    max_tokens=128,
)
print(resp.choices[0].message.content)
```

```js [Node.js]
import OpenAI from 'openai'

const client = new OpenAI({baseURL: 'https://bigmodel.io/v1', apiKey: process.env.BIGMODEL_API_KEY})

const resp = await client.chat.completions.create({
  model: 'glm-5.3',
  messages: [
    {role: 'system', content: '你是一个简洁的助手。'},
    {role: 'user', content: '用一句话解释 HTTP 429。'},
  ],
  max_tokens: 128,
})
console.log(resp.choices[0].message.content)
```

响应示例（`id`、时间戳、文本和 token 数仅作示意；`reasoning_content` 等额外字段由模型服务商返回）：

```json
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "created": 1792310400,
  "model": "glm-5.3",
  "choices": [
    {
      "index": 0,
      "message": {"role": "assistant", "content": "HTTP 429 表示你在一段时间内请求过多，需要稍后重试。"},
      "finish_reason": "stop"
    }
  ],
  "usage": {"prompt_tokens": 24, "completion_tokens": 19, "total_tokens": 43}
}
```

### 流式输出

```bash [cURL]
curl -N https://bigmodel.io/v1/chat/completions \
  -H "Authorization: Bearer $BIGMODEL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"glm-5.3","stream":true,"messages":[{"role":"user","content":"从 1 数到 3。"}]}'
```

```python [Python]
stream = client.chat.completions.create(
    model="glm-5.3",
    messages=[{"role": "user", "content": "从 1 数到 3。"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

```js [Node.js]
const stream = await client.chat.completions.create({
  model: 'glm-5.3',
  messages: [{role: 'user', content: '从 1 数到 3。'}],
  stream: true,
})
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? '')
```

流以 `data: [DONE]` 结束。最后一个数据块通常带 `usage`，`choices` 为空数组，所以要像上面那样跳过没有 choices 的块。

### 备用模型

```json
{
  "model": "glm-5.3",
  "models": ["kimi-k3", "deepseek-v4-pro"],
  "messages": [{"role": "user", "content": "你好"}]
}
```

网关先尝试 `glm-5.3`，再依次尝试 `models` 中的模型。详见 [OpenRouter 兼容](https://bigmodel.io/zh-cn/docs/openrouter-compat)。

## 说明

- **可用字段取决于分组。** 在仅对话补全分组（DeepSeek、GLM 平台）上只改写 `model`，`tools`、`tool_choice`、`response_format`、`thinking`、`reasoning_effort` 和图片输入都会透传，是否生效取决于模型。在其他 OpenAI 分组和 Anthropic 分组上请求会被转换，只保留 `model`、`messages`、`instructions`、`max_tokens`、`max_completion_tokens`、`temperature`、`top_p`、`stream`、`stream_options.include_usage`、`tools`、`tool_choice`、`reasoning_effort`、`service_tier`、`stop`、`functions` 和 `function_call`。**`response_format`、`n`、`seed`、`user`、`logprobs` 在这些路径上会被丢弃**，JSON 模式不会生效。详见[结构化输出](https://bigmodel.io/zh-cn/docs/structured-output)。
- **模型不存在返回 `503`，不是 `404`。** 分组不提供的模型或拼错的 ID 返回 `503` `api_error`："No available accounts: no available accounts supporting model: …"。请从 [/models](https://bigmodel.io/zh-cn/models) 或 [`GET /v1/models`](https://bigmodel.io/zh-cn/docs/api-models) 复制模型 ID。
- **OpenRouter 风格请求。** `z-ai/glm-5.3` 以及 `:nitro` 这类后缀会尽量解析到已提供的模型；`:free` 不会被去掉。`models` 加起来最多尝试 5 次；只在返回任何字节之前遇到 `404`、`408`、`429`、`5xx` 时切换，`400`/`401`/`402`/`403`/`413` 不切换。只按成功的那次计费。`provider`、`transforms`、`route` 会被忽略。
- **流式用量。** 网关总会向上游请求用量，即使你没设置 `stream_options`，最后一块也会带 token 数。流开始后的错误以 SSE `error` 事件返回。
- **JSON 格式错误、请求体为空或缺少 `model`** 返回 `400` `invalid_request_error`。
- 完整错误列表见[错误码](https://bigmodel.io/zh-cn/docs/errors)。

## 相关文档

- [流式输出](https://bigmodel.io/zh-cn/docs/streaming)
- [工具调用](https://bigmodel.io/zh-cn/docs/tool-calling)
- [图片输入](https://bigmodel.io/zh-cn/docs/vision)
- [OpenAI SDK](https://bigmodel.io/zh-cn/docs/openai-sdk-langchain)
