# Kimi K3 API 接口文档

> 官方文档：https://platform.kimi.com/docs/api/chat（Kimi API 开放平台）
> 为聊天消息创建补全结果。支持标准聊天、流式输出、Tool Use（函数调用）、Partial Mode、多模态输入。

---

## 1. 基本信息

| 项目         | 说明                                                         |
| ------------ | ------------------------------------------------------------ |
| 接口地址     | `POST https://$Burncloud_API_BaseUrl/v1/chat/completions`    |
| 认证方式     | `Authorization: Bearer $Burncloud_API_KEY`（服务端密钥，在 API 密钥页面生成） |
| Content-Type | `application/json`                                           |
| 兼容性       | OpenAI Chat Completions 兼容格式（可用 OpenAI SDK，`base_url` 指向 `https://$Burncloud_API_BaseUrl/v1`） |

**模型特性：**

- Kimi K3 **始终启用思考（Always Thinking）**，且**始终开启 Preserved Thinking**
- 通过顶层 `reasoning_effort` 控制推理强度：`"low"` / `"high"` / `"max"`，默认 `"max"`
- 上下文与输出上限：`max_completion_tokens` 默认 **131072**，最大可设 **1048576**
- 注意：K3 使用 `reasoning_effort`，不支持 K2.x 的 `thinking` 对象参数

---

## 2. 请求参数（Kimi-K3 Chat Request）

### 2.1 K3 专属参数

| 参数               | 类型   | 必填 | 说明                                                         |
| ------------------ | ------ | ---- | ------------------------------------------------------------ |
| `model`            | string | 是   | 固定为 `"kimi-k3"`                                           |
| `messages`         | array  | 是   | Kimi K3 对话消息列表（见 §3）。除标准消息外，还可在任意对话位置插入 `{"role": "system", "tools": [...]}` 动态工具消息 |
| `reasoning_effort` | string | 否   | 推理强度：`"low"` \| `"high"` \| `"max"`，默认 `"max"`       |

### 2.2 通用参数（Chat Request Common）

| 参数                    | 类型               | 必填 | 说明                                                         |
| ----------------------- | ------------------ | ---- | ------------------------------------------------------------ |
| `max_completion_tokens` | integer            | 否   | 生成的最大 Token 数。K3 默认 131072，最大 1048576。达到上限未结束则 `finish_reason="length"`。此值为期望输出长度，非输入+输出总量；若输入+此值超出上下文窗口，返回 `invalid_request_error` |
| `max_tokens`            | integer            | 否   | ⚠️ 已弃用，请使用 `max_completion_tokens`                     |
| `stream`                | boolean            | 否   | 是否流式返回，默认 `false`                                   |
| `stream_options`        | object             | 否   | `{"include_usage": true}` 可在 `data: [DONE]` 前额外收到一个含 `usage` 的 chunk（choices 为空数组） |
| `tools`                 | array              | 否   | 模型可调用的工具列表，见 §5                                  |
| `tool_choice`           | string \| object   | 否   | `auto`（默认）：模型自行决定；`none`：不调用；`required`：强制调用；或传 `{"type": "function", "function": {"name": "xxx"}}` 强制调用指定工具 |
| `response_format`       | object             | 否   | 输出格式约束，见 §6                                          |
| `stop`                  | string \| string[] | 否   | 停用词，完全匹配时停止输出（匹配词本身不输出）。最多 5 个，每个 ≤32 字节 |
| `prompt_cache_key`      | string             | 否   | 提升缓存命中率的会话标识（如 session id / task id），恢复会话时保持不变。Kimi Code Plan 场景必填，Coding Agent 强烈建议使用 |
| `safety_identifier`     | string             | 否   | 标识最终用户的稳定字符串，建议对用户名/邮箱做哈希            |
| `logprobs`              | boolean            | 否   | 是否返回输出 Token 的对数概率，默认 `false`                  |
| `top_logprobs`          | integer            | 否   | 每个 Token 位置返回概率最高的候选 Token 数（0–20），需同时 `logprobs: true` |
| `prediction`            | object             | 否   | Predicted Output 配置。响应大部分内容可预知时（如重新生成仅少量修改的文件）可显著降低延迟。`{"type": "content", "content": "<string 或 array>"}` |

> 注：`temperature`、`top_p`、`n`、`presence_penalty`、`frequency_penalty` 仅适用于 moonshot-v1 系列，不属于 kimi-k3 的请求参数。

---

## 3. 消息类型（Kimi-K3 Message）

K3 的 `messages` 中每个元素为以下两种之一：

### 3.1 标准消息

```json
{
  "role": "user",
  "content": "你好",
  "name": null,
  "partial": false
}
```

| 字段      | 类型            | 必填 | 说明                                                         |
| --------- | --------------- | ---- | ------------------------------------------------------------ |
| `role`    | string          | 是   | `system` \| `user` \| `assistant` \| `tool`                  |
| `content` | string \| array | 是   | 纯文本字符串，或对象数组（多模态输入）                       |
| `name`    | string          | 否   | 消息发送者名称                                               |
| `partial` | boolean         | 否   | 在最后一条 assistant 消息设为 `true` 启用 Partial Mode（Prefill），默认 `false` |

**多模态 content 数组**（每个元素按 `type` 区分）：

```json
{
  "content": [
    { "type": "text", "text": "描述这张图片" },
    { "type": "image_url", "image_url": { "url": "data:image/png;base64,..." } },
    { "type": "video_url", "video_url": { "url": "data:video/mp4;base64,..." } }
  ]
}
```

| type        | 必填字段    | 说明                                                |
| ----------- | ----------- | --------------------------------------------------- |
| `text`      | `text`      | 文本内容                                            |
| `image_url` | `image_url` | 图片，支持对象 `{"url": "..."}` 或直接传 URL 字符串 |
| `video_url` | `video_url` | 视频，同上                                          |

`url` 支持两种格式：

- base64 编码：`data:image/png;base64,...` / `data:video/mp4;base64,...`
- 文件引用：`ms://<file_id>`

### 3.2 动态工具消息（K3 特有）

可在**任意对话位置**插入，动态加载工具；**不含 `content` 字段**，只影响其后的对话：

```json
{
  "role": "system",
  "tools": [ { "type": "function", "function": { ... } } ]
}
```

| 字段    | 类型   | 必填 | 说明                                   |
| ------- | ------ | ---- | -------------------------------------- |
| `role`  | string | 是   | 固定为 `"system"`                      |
| `tools` | array  | 是   | 从该消息位置开始可供模型调用的工具列表 |

---

## 4. 响应格式

### 4.1 非流式响应

```json
{
  "id": "cmpl-04ea926191a14749b7f2c7a48a68abc6",
  "object": "chat.completion",
  "created": 1698999496,
  "model": "kimi-k3",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "你好，李雷！1+1等于2。",
        "tool_calls": [
          {
            "id": "call_xxx",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\": \"北京\"}"
            }
          }
        ],
        "reasoning_content": "用户问的是基础数学问题，直接相加即可。"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 19,
    "completion_tokens": 21,
    "total_tokens": 40,
    "cached_tokens": 10
  }
}
```

| 字段                                  | 说明                                                         |
| ------------------------------------- | ------------------------------------------------------------ |
| `choices[].message.content`           | 最终答案                                                     |
| `choices[].message.reasoning_content` | 推理过程（K3 始终思考，始终返回）                            |
| `choices[].message.tool_calls`        | 模型发起的工具调用                                           |
| `choices[].finish_reason`             | `stop`（正常结束）\| `length`（达到 max_completion_tokens）\| `tool_calls`（需执行工具） |
| `usage.cached_tokens`                 | 命中缓存的 Token 数                                          |

### 4.2 流式响应（`stream: true`）

SSE 格式，每行以 `data:` 开头，`finish_reason` 非 null 时表示结束，最后以 `data: [DONE]` 结尾：

```text
data: {"id":"cmpl-xxx","object":"chat.completion.chunk","created":1698999575,"model":"kimi-k3","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"cmpl-xxx","object":"chat.completion.chunk","created":1698999575,"model":"kimi-k3","choices":[{"index":0,"delta":{"content":"你好"},"finish_reason":null}]}

data: {"id":"cmpl-xxx","object":"chat.completion.chunk","created":1698999575,"model":"kimi-k3","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":19,"completion_tokens":13,"total_tokens":32,"cached_tokens":12}}

data: [DONE]
```

- 增量内容在 `choices[].delta.content` 中累加；`delta.tool_calls` 为工具调用片段
- 搭配 `stream_options: {"include_usage": true}` 可获取 Token 用量统计
- 流中断时可能收不到含总用量的最终 chunk

---

## 5. 工具调用（Tool Use）

### 5.1 工具定义（Tool Definition）

```json
{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "获取指定城市的天气",
    "parameters": {
      "type": "object",
      "properties": {
        "city": { "type": "string", "description": "城市名称" }
      },
      "required": ["city"]
    },
    "strict": true
  }
}
```

| 字段                   | 说明                                                         |
| ---------------------- | ------------------------------------------------------------ |
| `function.name`        | 必填。须匹配正则 `^[a-zA-Z_][a-zA-Z0-9-_]{2,63}$`            |
| `function.description` | 功能描述                                                     |
| `function.parameters`  | 必填。JSON Schema 格式，需符合 MFJS（Moonshot Flavored JSON Schema）规范 |
| `function.strict`      | 是否严格按 schema 约束参数输出，默认 `true`                  |

### 5.2 调用流程

1. **请求**时通过顶层 `tools` 或动态工具消息传入工具定义
2. **响应**中 `finish_reason = "tool_calls"`，读取 `message.tool_calls`（含 `id`、`function.name`、`function.arguments`——后者为 JSON 字符串）
3. 本地执行工具后，将结果以 `role="tool"` 消息追加到 `messages`（`tool_call_id` 必须与 `id` 对应）：

```json
{ "role": "tool", "tool_call_id": "call_xxx", "content": "晴，25°C" }
```

---

## 6. 输出格式控制（response_format）

| 取值                                            | 说明                                                         |
| ----------------------------------------------- | ------------------------------------------------------------ |
| `{"type": "text"}`                              | 默认，纯文本输出                                             |
| `{"type": "json_object"}`                       | 强制输出合法 JSON Object。**必须在 system/user prompt 中明确描述期望的 JSON 字段和类型**；勿与 Partial Mode 混用 |
| `{"type": "json_schema", "json_schema": {...}}` | Structured Output（推荐），按 JSON Schema 约束输出           |

`json_schema` 字段：

| 字段     | 必填 | 说明                                                         |
| -------- | ---- | ------------------------------------------------------------ |
| `name`   | 是   | Schema 名称                                                  |
| `schema` | 是   | JSON Schema 对象，需符合 MFJS 规范（可用 walle CLI 自检：`go install github.com/moonshotai/walle/cmd/walle@latest && walle -schema '你的schema' -level strict`） |
| `strict` | 否   | 默认 `true` 严格约束；`false` 时仅保证为合法 JSON            |

---

## 7. 错误响应

| HTTP 状态码 | 说明                        |
| ----------- | --------------------------- |
| 400         | 请求错误 — 参数无效         |
| 401         | 未授权 — API 密钥无效或缺失 |
| 500         | 服务器错误                  |

错误体格式：

```json
{
  "error": {
    "message": "描述错误原因的错误消息",
    "type": "错误类型",
    "code": "错误码"
  }
}
```

---

## 8. 调用示例

### curl（基础请求）

```bash
curl --request POST \
  --url https://$Burncloud_API_BaseUrl/v1/chat/completions \
  --header 'Authorization: Bearer $Burncloud_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "kimi-k3",
    "messages": [
      { "role": "user", "content": "你好" }
    ]
  }'
```

### Python（OpenAI SDK，含推理强度与流式输出）

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("Burncloud_API_KEY"),
    base_url="https://$Burncloud_API_BaseUrl/v1",
)

completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[{"role": "user", "content": "请解释什么是递归。"}],
    reasoning_effort="high",        # low / high / max，默认 max
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
```

### Python（多轮对话）

```python
messages = [
    {"role": "system", "content": "你是 Kimi。"},
    {"role": "user", "content": "你好，我叫李雷。"},
]

completion = client.chat.completions.create(model="kimi-k3", messages=messages)
reply = completion.choices[0].message

# API 无状态：将 assistant 回复（含 reasoning_content）原样追加回 messages
messages.append({"role": "assistant", "content": reply.content,
                 "reasoning_content": reply.reasoning_content})
messages.append({"role": "user", "content": "1+1 等于多少？"})
```

### Python（Partial Mode / Prefill）

```python
completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {"role": "user", "content": "用 Python 实现快速排序。"},
        {"role": "assistant", "content": "```python\n", "partial": True},
    ],
)
# 模型从 ```python\n 之后继续生成代码
```

常见用途：强制特定格式开头（JSON 的 `{`、代码块前缀）；角色扮演保持名称前缀（配合 `name`）；`finish_reason="length"` 时用相同前缀续写截断内容。⚠️ 勿与 `response_format={"type": "json_object"}` 混用。

### Python（动态工具消息，K3 特有）

```python
completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {"role": "user", "content": "北京今天天气怎么样？"},
        {"role": "system", "tools": [            # 在此处动态加载工具，只影响后续对话
            {"type": "function", "function": {
                "name": "get_weather",
                "description": "获取指定城市的天气",
                "parameters": {
                    "type": "object",
                    "properties": {"city": {"type": "string"}},
                    "required": ["city"],
                },
            }}
        ]},
    ],
)
```

---

## 9. 注意事项与最佳实践

1. **无状态 API**：多轮对话需自行把历史（assistant 回复、工具结果）追加到 `messages`；历史过长时只保留最近若干条或做压缩。
2. **Preserved Thinking**：K3 始终保留历史轮次的 `reasoning_content`，请将每一轮 assistant 消息的 `reasoning_content` 原样保留在 `messages` 中，否则可能丢失推理上下文。
3. **缓存优化**：使用 `prompt_cache_key`（会话级稳定标识）提高缓存命中率，降低成本与延迟；`usage.cached_tokens` 可查看命中量。
4. **采样参数**：K3 不支持 `temperature`/`top_p` 等（仅 moonshot-v1 系列）。