# Chat Completions

OpenAI Chat Completions 兼容接口，适用于绝大多数聊天、Agent、RAG 与多模态场景。

**提示：还要接 Claude 或 Gemini？**

本页只讲 OpenAI Chat 协议。Claude 的 `/v1/messages`、Gemini 的 `/v1beta/models/{model}:generateContent` 的请求头、SDK 配置、字段差异和参数映射，见[聊天协议总览](https://docs.myaigf.cfd/api/chat-protocols)。

**接口地址**：`POST https://YOUR_API_BASE_URL/v1/chat/completions`

- 鉴权：Bearer Token
- Content-Type：application/json

messages 为必填对话列表；stream 为 true 时返回 SSE 流。

## 请求头

| 请求头 | 必填 | 值 |
| --- | --- | --- |
| `Authorization` | 是 | `Bearer sk-xxxxxxxx` |
| `Content-Type` | 是 | `application/json` |

## 请求体参数

### 核心参数

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `model` | string | 是 | 模型 ID，来自 `GET /v1/models` |
| `messages` | array | 是 | 对话消息列表，按时间顺序排列 |
| `stream` | boolean | 否 | `true` 时以 SSE 返回，默认 `false` |
| `stream_options` | object | 否 | 流式选项，如 `{"include_usage": true}` |
| `max_tokens` | integer | 否 | 最大生成 token 数；不要与 `max_completion_tokens` 同时使用 |
| `max_completion_tokens` | integer | 否 | 生成 token 上限，部分模型包含推理 token |
| `n` | integer | 否 | 生成候选数量，默认 `1` |
| `stop` | string \| string[] | 否 | 遇到指定字符串时停止，最多 4 个 |
| `temperature` | number | 否 | 采样温度，通常 `0`–`2`，默认值由模型决定 |
| `top_p` | number | 否 | 核采样，通常 `0`–`1` |
| `presence_penalty` | number | 否 | 话题新鲜度惩罚，`-2`–`2` |
| `frequency_penalty` | number | 否 | 频率惩罚，`-2`–`2` |
| `logit_bias` | object | 否 | token 级偏置，键为 token ID |
| `logprobs` | boolean | 否 | 是否返回对数概率 |
| `top_logprobs` | integer | 否 | 返回概率最高的 token 数，`0`–`20` |
| `user` | string | 否 | 终端用户标识，用于风控与统计 |
| `seed` | integer | 否 | 随机种子；不保证所有模型可复现 |

### 输出格式

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `response_format` | object | 指定输出格式 |
| `response_format.type` | string | `text`、`json_object` 或 `json_schema` |
| `response_format.json_schema` | object | `type=json_schema` 时的结构定义 |
| `response_format.json_schema.name` | string | 结构名称 |
| `response_format.json_schema.schema` | object | JSON Schema |
| `response_format.json_schema.strict` | boolean | 是否严格遵循 Schema |

**提示**

使用 `json_object` 时，提示词中仍需明确要求输出 JSON。使用 `json_schema` 可配合 `strict: true` 获得更稳定的结构，但需要模型支持。

### 工具调用

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `tools` | array | 可用工具列表 |
| `tools[].type` | string | 目前常用 `function` |
| `tools[].function.name` | string | 函数名 |
| `tools[].function.description` | string | 函数说明，影响模型选择 |
| `tools[].function.parameters` | object | JSON Schema 参数定义 |
| `tools[].function.strict` | boolean | 是否严格遵循参数结构 |
| `tool_choice` | string \| object | `none`、`auto`、`required` 或指定函数 |
| `parallel_tool_calls` | boolean | 是否允许并行调用多个工具 |

指定函数：

```json
{
  "tool_choice": {
    "type": "function",
    "function": { "name": "get_weather" }
  }
}
```

### 其他参数（模型相关）

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `reasoning_effort` | string | 推理强度，常见 `low` / `medium` / `high` |
| `modalities` | string[] | 输出模态，例如 `["text"]`、`["text","audio"]` |
| `audio` | object | 音频输出配置，如 `{"voice":"alloy","format":"mp3"}` |
| `service_tier` | string | 服务等级，如 `auto` / `default` / `flex` / `priority` |
| `store` | boolean | 是否允许服务端存储请求，部分模型不接受 `true` |
| `metadata` | object | 自定义元数据，键值对 |
| `prediction` | object | 预测输出以降低延迟（模型相关） |

**注意**

上表部分参数只有特定模型支持。传入不支持的参数时，网关或模型可能返回 `400 unsupported_parameter`，也可能忽略。生产环境请做好兼容。

## messages 结构

每条消息的基本结构：

```json
{
  "role": "user",
  "content": "你好"
}
```

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `role` | string | `system`、`developer`、`user`、`assistant`、`tool` |
| `content` | string \| array \| null | 文本，或多模态内容块数组 |
| `name` | string | 可选的参与者名称 |
| `tool_calls` | array | 助手消息中的工具调用 |
| `tool_call_id` | string | `tool` 消息对应的调用 ID |

### 内容块

`content` 为数组时，支持以下块（是否支持由模型决定）：

| type | 结构 | 说明 |
| --- | --- | --- |
| `text` | `{"type":"text","text":"..."}` | 文本 |
| `image_url` | `{"type":"image_url","image_url":{"url":"...","detail":"auto"}}` | 图片 URL 或 Data URI |
| `input_audio` | `{"type":"input_audio","input_audio":{"data":"<base64>","format":"wav"}}` | 音频输入 |
| `file` | `{"type":"file","file":{"file_id":"file_xxx"}}` | 文件引用，字段随模型而定 |

图片示例：

```json
{
  "role": "user",
  "content": [
    { "type": "text", "text": "请描述这张图片。" },
    {
      "type": "image_url",
      "image_url": {
        "url": "https://media.example.com/reference.jpg",
        "detail": "auto"
      }
    }
  ]
}
```

图片 URL 必须是公网可访问的 `http` / `https` 地址，或合法的 Data URI。私有地址、需要登录的页面通常无法被服务读取。

## 基础调用

**cURL**

```bash
curl "https://YOUR_API_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL",
    "messages": [
      {"role": "system", "content": "你是一个简洁的助手。"},
      {"role": "user", "content": "用一句话解释什么是向量数据库。"}
    ],
    "temperature": 0.7,
    "stream": false
  }'
```

**Python**

```python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url=os.environ["API_BASE"] + "/v1",
)

resp = client.chat.completions.create(
    model="YOUR_MODEL",
    messages=[
        {"role": "system", "content": "你是一个简洁的助手。"},
        {"role": "user", "content": "用一句话解释什么是向量数据库。"},
    ],
    temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage)
```

**Node.js**

```javascript
import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: process.env.API_BASE + '/v1'
})

const resp = await client.chat.completions.create({
  model: 'YOUR_MODEL',
  messages: [
    { role: 'system', content: '你是一个简洁的助手。' },
    { role: 'user', content: '用一句话解释什么是向量数据库。' }
  ],
  temperature: 0.7
})
console.log(resp.choices[0].message.content)
```

## 成功响应

HTTP `200`：

```json
{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "created": 1788566400,
  "model": "YOUR_MODEL",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "向量数据库是一种专门存储和检索向量表示的数据库。"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 24,
    "total_tokens": 52
  },
  "system_fingerprint": null
}
```

| 字段 | 说明 |
| --- | --- |
| `id` | 响应 ID |
| `object` | 固定为 `chat.completion` |
| `created` | Unix 秒时间戳 |
| `model` | 实际使用的模型名，可能是实际模型名 |
| `choices[].index` | 候选序号 |
| `choices[].message.content` | 生成的文本 |
| `choices[].message.tool_calls` | 工具调用列表，可能不存在 |
| `choices[].finish_reason` | `stop`、`length`、`tool_calls`、`content_filter` 等 |
| `usage.prompt_tokens` | 输入 token |
| `usage.completion_tokens` | 输出 token |
| `usage.total_tokens` | 总 token |

部分推理模型会在消息中额外返回 `reasoning_content` 字段，属于模型相关行为。

## 流式调用

```bash
curl -N "https://YOUR_API_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL",
    "messages": [{"role": "user", "content": "写两句关于秋天的诗。"}],
    "stream": true,
    "stream_options": {"include_usage": true}
  }'
```

返回：

```text
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{"content":"秋风"},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{"content":"起"},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[],"usage":{"prompt_tokens":20,"completion_tokens":12,"total_tokens":32}}

data: [DONE]
```

| 字段 | 说明 |
| --- | --- |
| `choices[].delta.content` | 本次增量文本 |
| `choices[].delta.tool_calls` | 增量工具调用，需按 `index` 拼接 |
| `choices[].finish_reason` | 最后一个内容块给出结束原因 |
| `usage` | 仅在 `include_usage: true` 时，最后一个数据块返回 |
| `[DONE]` | 流结束标记，不是 JSON |

Python SDK：

```python
stream = client.chat.completions.create(
    model="YOUR_MODEL",
    messages=[{"role": "user", "content": "写两句关于秋天的诗。"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

## 工具调用

第一次请求让模型决定调用哪个函数：

```json
{
  "model": "YOUR_MODEL",
  "messages": [
    {"role": "user", "content": "北京今天天气怎么样？"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "查询指定城市的天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "城市名称"}
          },
          "required": ["city"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}
```

模型返回工具调用：

```json
{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_example",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"北京\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}
```

执行函数后，把结果作为 `tool` 消息追加，再次请求：

```json
{
  "model": "YOUR_MODEL",
  "messages": [
    {"role": "user", "content": "北京今天天气怎么样？"},
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_example",
          "type": "function",
          "function": {"name": "get_weather", "arguments": "{\"city\":\"北京\"}"}
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "call_example",
      "content": "{\"temperature\":26,\"weather\":\"晴\"}"
    }
  ],
  "tools": [ ... ]
}
```

## 结构化输出

```json
{
  "model": "YOUR_MODEL",
  "messages": [
    {"role": "system", "content": "从文本中抽取人物信息。"},
    {"role": "user", "content": "张三，32 岁，住在杭州。"}
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "age": {"type": "integer"},
          "city": {"type": "string"}
        },
        "required": ["name", "age", "city"],
        "additionalProperties": false
      }
    }
  }
}
```

## 错误

| 状态码 | 常见原因 |
| --- | --- |
| `400` | JSON 错误、缺少 `messages`、参数不支持、图片格式错误 |
| `401` | Key 无效或过期 |
| `403` | 模型不在分组 / 白名单，或额度不足 |
| `404` | 模型不存在 |
| `429` | 频率或额度超限 |
| `500` / `502` / `503` | 服务异常，可退避重试 |

完整错误结构见[错误与重试](https://docs.myaigf.cfd/guide/errors)。

## 相关阅读

- [通用约定](https://docs.myaigf.cfd/guide/conventions)：流式解析、超时与重试。
- [Responses](https://docs.myaigf.cfd/api/responses)：OpenAI 新版响应式协议。
- [Claude Messages](https://docs.myaigf.cfd/api/messages)：Anthropic 协议。
- [模型与分组](https://docs.myaigf.cfd/guide/models)：如何确认模型能力。
