---
url: https://limapi.com/docs/guide/chat-completions.md
---
# 协议一：OpenAI Chat Completions

```
POST /api/v1/chat/completions
```

兼容 OpenAI 的 Create a Chat Completion 接口，用于对话型大语言模型推理调用。

下面列出了所有模型可能支持的参数，不同模型的支持参数有所不同。

## Request headers

### Authorization `string` \*

Bearer Token 鉴权，使用你的 API Key：

```
Authorization: Bearer sk-xxx
```

### Content-Type `string` \*

请求内容类型，固定为 `application/json`

## Request

### messages `array` \*

以对话的消息列表形式输入给大模型的提示词。根据模型的能力不同，支持的消息类型也会有所不同，比如文本、图片、音频、视频。

messages 里的每个元素表示一条对话消息，每条消息由 `role` 和 `content` 组成，详情如下：

**Developer message** `object`

开发者提供的指令，无论用户发送什么消息，模型都应遵循。在 o1 及更新模型中，developer 消息取代了之前的 system 消息。

| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| role | string | \* | 固定为 `developer` |
| content | string or array | \* | Developer message 的内容。支持纯文本字符串，或 `[{type: "text", text: "..."}]` 格式的内容片段数组 |
| name | string | 可选 | 可选参与者名称 |

**System message** `object`

开发者提供的指令。在 o1 及更新模型中，应使用 developer 消息。

| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| role | string | \* | 固定为 `system` |
| content | string or array | \* | System message 的内容 |
| name | string | 可选 | 可选参与者名称 |

**User message** `object`

终端用户发送给模型的消息，大多数对话场景中你只需要使用此角色。

| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| role | string | \* | 固定为 `user` |
| content | string or array | \* | 支持纯文本或多模态内容片段数组（文本、图片、音频等） |
| name | string | 可选 | 可选参与者名称 |

多模态内容片段（content 为 array 时）：

| 类型 | type | 字段 | 说明 |
|------|------|------|------|
| 文本 | `text` | `text` string \* | 文本内容 |
| 图片 | `image_url` | `image_url.url` string \*, `image_url.detail` string | 图片 URL 或 base64 Data URL；detail 可选值：`low` / `high` / `auto` |
| 音频 | `input_audio` | `input_audio.data` string \*, `input_audio.format` string \* | 音频文件 base64 内容；format 如 `wav`、`mp3` |

**Assistant message** `object`

模型在对话中发送给用户的回复消息。可以在新的请求中把这些历史助手消息一并传回，以便模型继续基于完整上下文进行推理。

| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| role | string | \* | 固定为 `assistant` |
| content | string or array | 可选 | 助手消息的内容。当未设置 `tool_calls` 时为必填 |
| refusal | string or null | 可选 | 模型拒绝回答时的拒答信息 |
| tool\_calls | array | 可选 | 工具调用列表 |
| reasoning | string | 可选 | 推理过程的文本内容（扩展字段） |
| reasoning\_details | array | 可选 | 推理过程详细信息，多轮工具调用场景必须完整传回 |

**Tool message** `object`

用于把外部工具（函数）调用的执行结果传回给模型。

| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| role | string | \* | 固定为 `tool` |
| content | string or array | \* | 工具执行结果内容 |
| tool\_call\_id | string | \* | 对应 assistant 消息中的 `tool_calls[i].id` |

***

### model `string` \*

此次推理调用的模型 ID，如 `qwen3.8-max`、`claude-sonnet-4-6` 等。可通过 `GET /api/v1/models` 获取可用模型列表。

### max\_completion\_tokens `integer or null` 可选

限制模型生成内容的长度（包括思考过程）。如果不传，使用模型默认限制。

> 思考型模型（如 `kimi-k3`、`doubao-seed-evolving`）请用它来控成本：`max_tokens` 在这类模型上只闸最终正文、闸不住思考过程。给得太小会出现「思考吃满预算、正文为空」，建议按目标输出量的 2~3 倍留预算。`doubao-seed-evolving` 上游不接受 `max_tokens` 与 `max_completion_tokens` 同发，同发时网关保留 `max_completion_tokens`。

### temperature `number` 可选

* 默认：1
* 建议取值范围：\[0, 2]

采样温度，控制随机性。值越高越随机，值越低越稳定。一般与 `top_p` 二选一调节。

### top\_p `number` 可选

* 默认：1

Nucleus sampling 参数：只从累积概率质量前 top\_p 的 token 中采样。

### n `integer or null` 可选

返回候选回答数量，当前仅支持 `n=1`。

### frequency\_penalty `number or null` 可选

* 默认：0
* 取值范围：-2.0 ~ 2.0

对已出现频率较高的 token 施加惩罚，减少机械复读。

### presence\_penalty `number or null` 可选

* 默认：0
* 取值范围：-2.0 ~ 2.0

对是否已出现过的 token 施加惩罚，减少重复讨论相同内容。

### stop `string | array | null` 可选

* 默认：null
* 最多可提供 4 个 stop 序列

当生成内容命中任一 stop 序列时，模型停止生成。

### logit\_bias `object` 可选

* 默认：null

对指定 token 的采样概率进行微调。键为 token ID（整数），值为 -100 ~ 100 之间的偏置。

### logprobs `boolean or null` 可选

* 默认：false

是否在返回结果中包含输出 token 的对数概率信息。

### top\_logprobs `integer` 可选

指定每个位置返回的最高概率 token 个数（0~20），需配合 `logprobs: true` 使用。

### tools `array` 可选

声明本次对话中模型可使用的工具列表。每个工具包含 `type` 和 `function` 定义。

```json
{
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取城市天气信息",
        "parameters": {
          "type": "object",
          "properties": {
            "location": { "type": "string" }
          },
          "required": ["location"]
        }
      }
    }
  ]
}
```

### tool\_choice `string or object` 可选

控制模型对工具的使用策略：

* `"none"` — 不调用任何工具
* `"auto"` — 由模型自行决定是否调用工具
* `"required"` — 本轮必须调用至少一个工具
* `{"type": "function", "function": {"name": "my_function"}}` — 指定调用某个工具

### parallel\_tool\_calls `boolean` 可选

* 默认：true

是否允许模型在一次回复中并行调用多个工具。

### response\_format `object` 可选

指定模型输出格式：

* `{ "type": "text" }` — 默认文本输出
* `{ "type": "json_object" }` — 强制输出有效 JSON
* `{ "type": "json_schema", "json_schema": { "name": "...", "schema": {...} } }` — 结构化输出

### reasoning\_effort `string` 可选

控制推理模型的思考投入程度：`low`、`medium`、`high`、`xhigh`、`max`。

> 注：`none`、`minimal` 等 OpenAI 风格值会被网关自动映射为最接近的合法值（如 `minimal` → `low`），建议直接使用上述标准值。
>
> `doubao-seed-evolving` 例外：它原生认 `minimal`/`low`/`medium`/`high`/`max` 五档，网关原样透传不折叠（实测 `minimal` 直接零思考，折成 `low` 会凭空多出思考量）。该模型另支持 `thinking: {"type": "disabled"}` 关掉思考，但与 `reasoning_effort` 同发会被上游 400，二选一。

### verbosity `string` 可选

* 默认：`"medium"`

约束模型输出的详略程度：`low`（简洁）、`medium`（适中）、`high`（更详细）。

### prompt\_cache\_options `object` 可选

上下文缓存写入档位（Kimi 系模型，如 `kimi-k3`）。**不传即默认开启写入、走 5min 档。**

| 字段 | 类型 | 说明 |
|------|------|------|
| mode | string | 写入模式，目前仅支持 `"implicit"`：自动把请求前缀写入缓存 |
| ttl | string | 写入有效期，`"5m"`（默认）或 `"1h"`；两档缓存相互独立，不复用 |

写入 token 按 TTL 分档计价，命中部分只收命中价、不再收写入价，命中还会按原 TTL 刷新有效期；缓存按组织隔离，组织之间不共享。计价规则见 [缓存计费](/guide/#缓存计费)。

### stream `boolean or null` 可选

* 默认：false

是否启用流式输出（Server-Sent Events）。为 true 时，结果以事件流形式分片返回。

### stream\_options `object` 可选

仅当 `stream: true` 时有效。

| 字段 | 类型 | 说明 |
|------|------|------|
| include\_usage | boolean | 是否在流结束时附带 usage 信息 |

### provider `object` 可选（扩展）

配置本次请求在多个模型提供商之间的路由与故障转移策略。

| 字段 | 类型 | 说明 |
|------|------|------|
| routing.type | string | 路由类型：`priority`（优先级）、`round_robin`（轮询）、`least_latency`（最低延迟） |
| routing.primary\_factor | string | 主要考量因素：`cost` / `speed` / `quality` |
| routing.providers | array | 提供商列表，如 `["openai", "anthropic"]` |
| fallback | string | 故障转移策略：`"true"` / `"false"` / 指定提供商名 |

### reasoning `object` 可选（扩展）

配置推理过程（chain-of-thought）相关行为。

| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| enabled | boolean | \* | 是否启用显式推理过程 |
| effort | string | 可选 | 推理投入程度：`low` / `medium` / `high` |
| max\_tokens | number | 可选 | 推理过程的最大 token 数上限 |
| exclude | boolean | 可选 | 是否从返回内容中排除推理过程 |

### metadata `object` 可选

附带最多 16 个键值对，作为结构化业务元信息。

***

## Response（非流式）

当 `stream: false` 或未传时，返回完整的 `chat.completion` 对象。

```json
{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1700000000,
  "model": "qwen3.8-max",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "你好！有什么我可以帮助你的吗？",
        "refusal": null,
        "annotations": [],
        "tool_calls": null
      },
      "logprobs": null
    }
  ],
  "usage": {
    "prompt_tokens": 14,
    "completion_tokens": 20,
    "total_tokens": 34,
    "completion_tokens_details": {
      "reasoning_tokens": 0
    },
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  },
  "system_fingerprint": "fp_xxx",
  "service_tier": "default"
}
```

### 响应字段说明

**顶层字段：**

| 字段 | 类型 | 说明 |
|------|------|------|
| id | string | 本次补全的唯一标识符 |
| object | string | 固定为 `chat.completion` |
| created | integer | Unix 时间戳（秒） |
| model | string | 实际使用的模型 ID |
| choices | array | 补全选项列表，通常只有一个元素 |
| usage | object | Token 用量统计 |
| system\_fingerprint | string | 后端配置指纹 |
| service\_tier | string | 服务等级 |

**choices\[i]：**

| 字段 | 类型 | 说明 |
|------|------|------|
| index | integer | 选项索引，从 0 开始 |
| finish\_reason | string | 停止原因：`stop` / `length` / `content_filter` / `tool_calls` |
| message | object | 模型生成的完整消息 |
| logprobs | object | 对数概率信息（需请求时开启） |

**message：**

| 字段 | 类型 | 说明 |
|------|------|------|
| role | string | 固定为 `assistant` |
| content | string | 模型回复正文 |
| refusal | string or null | 拒答信息 |
| tool\_calls | array | 工具调用列表 |
| reasoning | string | 推理过程文本（扩展字段） |
| reasoning\_details | array | 推理详细信息（扩展字段） |
| annotations | array | 注释列表（如 URL 引用） |

**usage：**

| 字段 | 类型 | 说明 |
|------|------|------|
| prompt\_tokens | integer | 输入提示 token 数 |
| completion\_tokens | integer | 生成补全 token 数 |
| total\_tokens | integer | 总 token 数 |
| completion\_tokens\_details.reasoning\_tokens | integer | 推理过程 token 数 |
| prompt\_tokens\_details.cached\_tokens | integer | 缓存命中 token 数 |
| prompt\_tokens\_details.cache\_creation\_input\_tokens | integer | 缓存写入 token 数，按缓存写入价计费（部分模型以 `cache_write_tokens` 字段名回传，含义相同） |

***

## Response（流式）

当 `stream: true` 时，以 SSE 形式返回多个 `chat.completion.chunk` 对象。

```
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.8-max","choices":[{"index":0,"delta":{"role":"assistant","content":"你"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.8-max","choices":[{"index":0,"delta":{"content":"好"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.8-max","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1700000000,"model":"qwen3.8-max","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":11,"total_tokens":25}}

data: [DONE]
```

**chunk 字段说明：**

| 字段 | 类型 | 说明 |
|------|------|------|
| id | string | 补全 ID（同一流中共享） |
| object | string | 固定为 `chat.completion.chunk` |
| created | integer | Unix 时间戳 |
| model | string | 模型 ID |
| choices | array | 增量选项列表 |

**choices\[i].delta：**

| 字段 | 类型 | 说明 |
|------|------|------|
| role | string | 角色，通常在首块为 `assistant` |
| content | string | 增量正文内容，需逐块拼接 |
| tool\_calls | array | 工具调用增量信息 |
| reasoning | string | 推理过程增量文本（扩展字段） |
| reasoning\_content | string | 推理内容增量（扩展字段） |
| refusal | string | 拒答信息增量 |

**choices\[i].finish\_reason：**

`string or null` — 停止原因，`null` 表示尚未结束。取值同非流式 `finish_reason`。

***

## 代码示例

### 文本输入（JavaScript / OpenAI SDK）

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://limapi.com/api/v1",
  apiKey: "sk-xxx",
});

const completion = await client.chat.completions.create({
  model: "qwen3.8-max",
  messages: [{ role: "user", content: "你好，介绍一下自己" }],
});

console.log(completion.choices[0].message.content);
```

### 文本输入（Python / OpenAI SDK）

```python
from openai import OpenAI

client = OpenAI(
    base_url="https://limapi.com/api/v1",
    api_key="sk-xxx",
)

completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[{"role": "user", "content": "你好，介绍一下自己"}],
)

print(completion.choices[0].message.content)
```

### 文本输入（cURL）

```bash
curl https://limapi.com/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxx" \
  -d '{
    "model": "qwen3.8-max",
    "messages": [
      {"role": "user", "content": "你好，介绍一下自己"}
    ]
  }'
```

### 图片输入（多模态）

```javascript
const completion = await client.chat.completions.create({
  model: "qwen3.8-max",
  messages: [
    {
      role: "user",
      content: [
        { type: "text", text: "描述这张图片" },
        {
          type: "image_url",
          image_url: { url: "https://example.com/photo.jpg" },
        },
      ],
    },
  ],
});
```

### 流式输出

```javascript
const stream = await client.chat.completions.create({
  model: "qwen3.8-max",
  stream: true,
  messages: [{ role: "user", content: "写一首短诗" }],
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
```

### Function Calling（工具调用）

```javascript
const completion = await client.chat.completions.create({
  model: "qwen3.8-max",
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "获取城市天气信息",
        parameters: {
          type: "object",
          properties: { location: { type: "string" } },
          required: ["location"],
        },
      },
    },
  ],
  messages: [{ role: "user", content: "上海今天天气怎么样？" }],
});

console.log(completion.choices[0].message.tool_calls);
```

### 推理模型

```javascript
const completion = await client.chat.completions.create({
  model: "qwen3.8-max",
  reasoning_effort: "medium",
  messages: [
    { role: "user", content: "比较两种数据库索引策略的优劣" },
  ],
});

console.log(completion.choices[0].message.content);
```
