# Claude 原生接口（Anthropic Messages）

> 官方文档：[Create a Message](https://platform.claude.com/docs/en/api/messages/create) ｜ [Streaming](https://platform.claude.com/docs/en/build-with-claude/streaming) ｜ [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) ｜ [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) ｜ [Errors](https://platform.claude.com/docs/en/api/errors)

## 📝 简介

Messages API 是 Anthropic 官方的对话接口：传入一组结构化的输入消息（文本、图片、PDF、工具结果等），模型生成对话中的下一条消息。接口本身无状态，多轮对话需要每次带上完整历史。BeeRoute 按 Anthropic 原生格式转发该接口，官方 SDK 和 Claude Code 等工具只需把 base URL 换成本站即可使用。

本页覆盖最常用的字段和用法，完整字段以 [官方参考](https://platform.claude.com/docs/en/api/messages/create) 为准。

### 接入要点

| 项目 | 说明 |
| --- | --- |
| 端点 | `POST https://beeroute.ai/v1/messages` |
| Base URL | `https://beeroute.ai`（SDK、Claude Code 等工具里填的 Anthropic base URL，不要带 `/v1`） |
| 鉴权 | `x-api-key: $API_KEY` 或 `Authorization: Bearer $API_KEY`，二选一 |
| 版本头 | `anthropic-version: 2023-06-01`（必填，见下方版本说明） |
| 内容类型 | `content-type: application/json` |
| 获取密钥 | [https://beeroute.ai/keys](https://beeroute.ai/keys) |
| 模型与价格 | [https://beeroute.ai/modellist/](https://beeroute.ai/modellist/?lang=zh) |

下文 curl 示例统一使用环境变量 `$API_KEY`，请先执行：

```bash
export API_KEY=sk-xxx
```

?> 直接调用 API 请使用 `default` 分组的令牌；`ClaudeCode` 分组的令牌仅供 Claude Code 客户端使用。

!> 本站不提供 Token 计数接口（`POST /v1/messages/count_tokens` 返回 404），也不提供 Files API 和 Message Batches API。

**关于 API 版本：** Anthropic 官方最新的 API 版本是 `2026-10-21`，此前的 `2023-06-01` 仍被广泛使用。本站原样转发您发送的 `anthropic-version`，本页示例统一使用兼容性最好的 `2023-06-01`（Claude Code 发送的也是这个值）。`2026-10-21` 能否使用取决于上游渠道，若报错请改回 `2023-06-01`。`2026-10-21` 相对 `2023-06-01` 的破坏性变更（[迁移指南](https://platform.claude.com/docs/en/api/migration-2026-10-21)）：

- 移除 `temperature`、`top_p`、`top_k`：请求中带上其中任何一个，在所有模型上都返回 400，即使是默认值；
- `assistant` 消息中直接放置 `document` 块返回 400；
- `user` 消息中带非空 `citations` 的 `text` 块（包括 `search_result` 内的）返回 400。

另外，官方 SDK 的新主版本（Python `anthropic` 2.0.0 起、TypeScript `@anthropic-ai/sdk` 1.0.0 起）默认发送 `2026-10-21`，并改用 `Authorization: Bearer` 发送密钥，详见下文「Python SDK」一节。

### 可用模型

本站当前提供的 Claude 模型：

`claude-opus-5-5`、`claude-sonnet-5-5`、`claude-haiku-5-5`、`claude-fable-5-2`、`claude-opus-5`、`claude-sonnet-5`

旧版本（`claude-fable-5-1`、`claude-fable-5`、`claude-opus-4-8`、`claude-opus-4-7`、`claude-opus-4-6`、`claude-sonnet-4-6`、`claude-haiku-4-5-20251001`）仍可调用，用于兼容已有项目；新项目请使用上面的模型。

本页示例默认使用 `claude-sonnet-5-5`。不同模型对思考、采样参数、prefill、强制工具调用等的支持不同，下文会逐项注明。

## 💡 请求示例

### 基础文本对话 ✅

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "你好，请用一句话介绍你自己。"}
    ]
  }'
```

**响应示例：**

```json
{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-5-5",
  "content": [
    {
      "type": "text",
      "text": "你好！我是 Claude，由 Anthropic 开发的 AI 助手，可以帮你写作、编程、分析和回答各种问题。"
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 21,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0},
    "output_tokens": 38,
    "service_tier": "standard"
  }
}
```

?> 使用 `Authorization: Bearer $API_KEY` 代替 `x-api-key: $API_KEY` 效果相同，本页其余示例不再重复说明。响应中的字段可能随上游版本增加，请按字段名读取，不要依赖字段顺序。

### 系统提示词 ✅

系统提示词放在顶层 `system` 字段，可以是字符串，也可以是 `text` 块数组（需要给系统提示词加 `cache_control` 时必须用数组形式）。

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "system": "你是一名资深中文技术编辑，回答简洁准确。",
    "messages": [
      {"role": "user", "content": "解释一下什么是幂等性。"}
    ]
  }'
```

### 多轮对话 ✅

接口无状态，每次请求都要带上完整历史，`user` 与 `assistant` 交替出现，最后一条应为 `user`。

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "你好。"},
      {"role": "assistant", "content": "你好！有什么可以帮你的吗？"},
      {"role": "user", "content": "请用通俗的话解释什么是大语言模型。"}
    ]
  }'
```

!> 以 `assistant` 消息结尾（即 prefill，预填充回复开头）在 Claude 4.6 及之后的模型上返回 400。本站模型中只有 `claude-haiku-4-5-20251001` 支持 prefill；其他模型请改用系统提示词或结构化输出（见下文「结构化输出」）约束格式。

### 图像理解 ✅

图片以 `image` 内容块传入，支持 `base64` 和 `url` 两种来源，格式支持 `image/jpeg`、`image/png`、`image/gif`、`image/webp`。官方建议图片放在文字之前。

**base64 图片：**

```bash
IMG_B64=$(base64 < image.jpg | tr -d '\n')

cat > request.json <<EOF
{
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "image",
          "source": {"type": "base64", "media_type": "image/jpeg", "data": "$IMG_B64"}
        },
        {"type": "text", "text": "这张图片里有什么？"}
      ]
    }
  ]
}
EOF

curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  --data @request.json
```

**URL 图片：**

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "image",
            "source": {"type": "url", "url": "https://platform.claude.com/docs/images/vision-example.jpg"}
          },
          {"type": "text", "text": "请描述这张图片。"}
        ]
      }
    ]
  }'
```

?> base64 数据中不能有换行，也不要带 `data:image/jpeg;base64,` 前缀。官方限制：单张图片最大 8000x8000 像素、base64 后不超过 10 MB；一次请求超过 20 张图片时单张尺寸限制更严格。URL 来源要求图片可公网访问，部分上游渠道只支持 base64，遇到不支持时请改用 base64。

### PDF 文档 ✅

PDF 以 `document` 内容块传入，来源可以是 `url` 或 `base64`（`media_type` 为 `application/pdf`）。官方限制：单次请求最多 600 页（上下文窗口小于 1M 的模型为 100 页）；Anthropic 官方 API 的请求体上限为 128 MB，其他平台和上游渠道可能更低。

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 2048,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "document",
            "source": {
              "type": "url",
              "url": "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
            }
          },
          {"type": "text", "text": "请用三点总结这份文档的主要内容。"}
        ]
      }
    ]
  }'
```

base64 来源的写法（用法同上面的图片 heredoc 示例）：

```json
{
  "type": "document",
  "source": {
    "type": "base64",
    "media_type": "application/pdf",
    "data": "JVBERi0xLjQK..."
  },
  "title": "季度报告",
  "citations": {"enabled": true}
}
```

`title`、`context`、`citations` 均为可选；开启 `citations` 后，回答会拆成多个 `text` 块并附带引用位置。`citations` 不能与 `output_config.format` 同时使用。

### 工具调用 ✅

**第 1 步：发送带工具定义的请求**

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "tools": [
      {
        "name": "get_weather",
        "description": "获取指定城市的当前天气",
        "input_schema": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "城市名称，如：北京"}
          },
          "required": ["location"]
        }
      }
    ],
    "messages": [
      {"role": "user", "content": "今天北京天气怎么样？"}
    ]
  }'
```

**响应示例：** 模型决定调用工具时，`stop_reason` 为 `tool_use`。`claude-sonnet-5-5` 默认开启自适应思考，响应中可能带有 `thinking` 块（默认不显示思考内容，`thinking` 字段为空字符串，但带 `signature`）。

```json
{
  "id": "msg_01Aq9w938a90dw8q",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-5-5",
  "content": [
    {"type": "thinking", "thinking": "", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."},
    {"type": "tool_use", "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "name": "get_weather", "input": {"location": "北京"}}
  ],
  "stop_reason": "tool_use",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 612,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "output_tokens": 86
  }
}
```

**第 2 步：执行工具，把结果作为 `tool_result` 发回**

把上一步 assistant 的 `content` **原样**（包括 `thinking` 块）追加到历史中，再追加一条 `user` 消息，其中放 `tool_result`，`tool_use_id` 对应上一步的 `tool_use.id`：

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "tools": [
      {"name": "get_weather", "description": "获取指定城市的当前天气", "input_schema": {"type": "object", "properties": {"location": {"type": "string", "description": "城市名称，如：北京"}}, "required": ["location"]}}
    ],
    "messages": [
      {"role": "user", "content": "今天北京天气怎么样？"},
      {
        "role": "assistant",
        "content": [
          {"type": "thinking", "thinking": "", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."},
          {"type": "tool_use", "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "name": "get_weather", "input": {"location": "北京"}}
        ]
      },
      {
        "role": "user",
        "content": [
          {"type": "tool_result", "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "content": "北京：晴，25°C，东南风 2 级"}
        ]
      }
    ]
  }'
```

模型随后返回最终回答（`stop_reason` 为 `end_turn`），例如 `"今天北京晴，气温约 25°C，东南风 2 级，适合出行。"`。

!> 示例中的 `signature` 是占位值，实际请求必须原样回传上一步响应里的 `thinking` / `redacted_thinking` 块，修改或调换顺序会返回 400。

?> 工具调用规则：`tool_result` 所在的 `user` 消息必须紧跟在对应的 `tool_use` 之后；`tool_result` 块要放在 `content` 数组最前面，其他文字放在其后；模型一次返回多个 `tool_use` 时，请把所有 `tool_result` 放在同一条 `user` 消息里；工具执行失败时返回 `"is_error": true` 并在 `content` 中写明原因。

### 流式响应 ✅

设置 `"stream": true` 后，接口以 SSE（Server-Sent Events）增量返回。

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "stream": true,
    "messages": [
      {"role": "user", "content": "你好"}
    ]
  }'
```

**响应示例：**

```text
event: message_start
data: {"type": "message_start", "message": {"id": "msg_01DsBEzYqFX4Xk3jvP4aSVGm", "type": "message", "role": "assistant", "content": [], "model": "claude-sonnet-5-5", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 12, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 1}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: ping
data: {"type": "ping"}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "你好！"}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "有什么可以帮你的吗？"}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}, "usage": {"output_tokens": 15}}

event: message_stop
data: {"type": "message_stop"}
```

事件顺序和各类 delta 详见下文「流式事件」。`message_delta` 中的 `usage` 是**累计值**，不是增量。

### 思考（Adaptive Thinking） ✅

Claude 5 系列模型默认开启自适应思考：模型自行决定是否思考、思考多深，用 `output_config.effort` 控制整体投入。这些模型默认不返回思考内容（`display` 默认为 `"omitted"`），如需看到思考摘要请设置 `"display": "summarized"`。

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 16000,
    "thinking": {"type": "adaptive", "display": "summarized"},
    "output_config": {"effort": "high"},
    "messages": [
      {"role": "user", "content": "1071 和 462 的最大公约数是多少？"}
    ]
  }'
```

**响应示例：**

```json
{
  "id": "msg_01QmTqXkV8sJZ3nF4b2yR9cH",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-5-5",
  "content": [
    {
      "type": "thinking",
      "thinking": "用辗转相除法：1071 = 2 × 462 + 147；462 = 3 × 147 + 21；147 = 7 × 21。最大公约数为 21。",
      "signature": "WaUjzkypQ2mUEVM36O2Txu..."
    },
    {
      "type": "text",
      "text": "1071 和 462 的最大公约数是 **21**。"
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 30,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "output_tokens": 412,
    "output_tokens_details": {"thinking_tokens": 356}
  }
}
```

- 思考 token 按输出 token 计费，并计入 `max_tokens`，即使思考内容未返回也照样计费；
- 返回的思考内容是摘要，不是原始推理过程；
- 各模型对 `thinking` 取值的支持见下文「请求」部分的 `thinking` 参数表。较老的 `claude-haiku-4-5-20251001` 不支持 `adaptive`，需使用 `{"type": "enabled", "budget_tokens": 2048}`（`budget_tokens` 最小 1024 且小于 `max_tokens`）；在 Claude 4.7 及之后的模型上 `enabled` 会返回 400。

### 提示缓存 ✅

在请求中给某个内容块加 `cache_control`，该块及之前的前缀（按 `tools` → `system` → `messages` 的顺序）会被缓存，后续请求命中缓存时按更低的缓存读取价格计费，价格见 [价格页](https://beeroute.ai/modellist/?lang=zh)。

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "system": [
      {"type": "text", "text": "你是一名法律文书分析助手。"},
      {
        "type": "text",
        "text": "（此处放置需要反复使用的长文本，例如完整的合同全文……）",
        "cache_control": {"type": "ephemeral"}
      }
    ],
    "messages": [
      {"role": "user", "content": "这份合同的违约条款有哪些？"}
    ]
  }'
```

第一次请求写入缓存，`usage.cache_creation_input_tokens` 大于 0；5 分钟内再次发送相同前缀的请求，`usage.cache_read_input_tokens` 大于 0：

```json
{
  "usage": {
    "input_tokens": 18,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 3842,
    "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0},
    "output_tokens": 296
  }
}
```

**自动缓存：** 也可以只在请求顶层加一个 `cache_control`，系统会自动把缓存断点放在最后一个可缓存的块上，适合多轮对话：

```json
{
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "cache_control": {"type": "ephemeral", "ttl": "1h"},
  "system": "你是一名乐于助人的助手。",
  "messages": [
    {"role": "user", "content": "继续上次的话题。"}
  ]
}
```

- `ttl` 可选 `"5m"`（默认）或 `"1h"`，1 小时缓存的写入价格更高；
- 每个请求最多 4 个缓存断点（顶层自动缓存占用其中 1 个）；
- 低于最小长度的前缀不会被缓存，也不报错：`claude-opus-5-5`、`claude-opus-5`、`claude-sonnet-5-5`、`claude-haiku-5-5`、Fable 系列为 512 token；`claude-opus-4-8`、`claude-sonnet-5`、`claude-sonnet-4-6` 为 1024；`claude-opus-4-7` 为 2048；`claude-opus-4-6`、`claude-haiku-4-5-20251001` 为 4096；
- 前缀中任何字节变化（包括工具列表、思考配置、effort 的变化）都会让其后的缓存失效。

### 结构化输出 ✅

通过 `output_config.format` 传入 JSON Schema，模型返回的 `text` 块内容保证是符合该 Schema 的 JSON。官方支持列表覆盖本站全部 Claude 模型。

```bash
curl https://beeroute.ai/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "从这段话中提取信息：张伟（zhangwei@example.com）想了解企业版，并希望下周二下午两点预约演示。"}
    ],
    "output_config": {
      "format": {
        "type": "json_schema",
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "email": {"type": "string"},
            "plan_interest": {"type": "string"},
            "demo_requested": {"type": "boolean"}
          },
          "required": ["name", "email", "plan_interest", "demo_requested"],
          "additionalProperties": false
        }
      }
    }
  }'
```

**响应中的 `content`：**

```json
[
  {
    "type": "text",
    "text": "{\"name\": \"张伟\", \"email\": \"zhangwei@example.com\", \"plan_interest\": \"企业版\", \"demo_requested\": true}"
  }
]
```

?> Schema 中对象必须设置 `"additionalProperties": false`；不支持递归、`oneOf`、数值和字符串长度约束等。遇到 `stop_reason` 为 `refusal` 或 `max_tokens` 时输出可能不符合 Schema。完整限制见 [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)。旧的顶层 `output_format` 参数已废弃。

### Python SDK ✅

```bash
pip install anthropic
```

```python
import anthropic

client = anthropic.Anthropic(
    api_key="sk-xxx",                 # 本站令牌
    base_url="https://beeroute.ai",   # 不要带 /v1
)

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "你好，Claude"}],
)
for block in message.content:  # 开启思考时 content 中可能先出现 thinking 块
    if block.type == "text":
        print(block.text)

# 流式输出
with client.messages.stream(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "写一首关于秋天的短诗"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
```

- 也可以不在代码里写参数，改为设置环境变量 `ANTHROPIC_API_KEY` 和 `ANTHROPIC_BASE_URL=https://beeroute.ai`；
- `anthropic` 2.0.0 及以上版本默认发送 `anthropic-version: 2026-10-21`，且不再提供 `temperature` / `top_p` / `top_k` 参数。如果上游渠道不接受 `2026-10-21`，可以在构造客户端时加上 `default_headers={"anthropic-version": "2023-06-01"}`；
- SDK 在 `max_tokens` 较大（超过约 21,333）时要求使用流式接口，这是客户端校验，用 `client.messages.stream(...)` 配合 `stream.get_final_message()` 即可拿到完整消息。

## 📮 请求

### 端点

```text
POST https://beeroute.ai/v1/messages
```

### 请求头

| 请求头 | 必需 | 说明 |
| --- | --- | --- |
| `x-api-key` | 二选一 | 本站令牌。Anthropic 官方现将其列为 `Authorization` 的旧式备选，仍然有效 |
| `Authorization` | 二选一 | `Bearer $API_KEY`，Anthropic 官方当前首选的写法 |
| `anthropic-version` | 是 | API 版本，推荐 `2023-06-01`；最新版本 `2026-10-21` 是否可用取决于上游渠道 |
| `content-type` | 是 | `application/json` |
| `anthropic-beta` | 否 | 启用 beta 功能。多个 beta 请写在**同一个**请求头内，用英文逗号分隔，例如 `anthropic-beta: beta1,beta2`，不要重复发送多个该请求头。beta 功能能否生效取决于上游渠道 |

### 请求体参数

| 参数 | 类型 | 必需 | 说明 |
| --- | --- | --- | --- |
| `model` | string | 是 | 模型名称，见上文「可用模型」 |
| `max_tokens` | integer | 是 | 最多生成的 token 数，最小 0，上限因模型而异 |
| `messages` | array | 是 | 输入消息列表，单次最多 100,000 条 |
| `system` | string 或 array | 否 | 系统提示词 |
| `thinking` | object | 否 | 思考配置 |
| `output_config` | object | 否 | 输出配置：`effort`、`format` |
| `tools` | array | 否 | 工具定义 |
| `tool_choice` | object | 否 | 工具选择策略 |
| `cache_control` | object | 否 | 顶层自动缓存 |
| `stop_sequences` | array of string | 否 | 自定义停止序列 |
| `stream` | boolean | 否 | 是否以 SSE 流式返回 |
| `metadata` | object | 否 | 请求元数据 |
| `temperature` / `top_p` / `top_k` | number / number / integer | 否 | 采样参数，新模型上有严格限制，见下文 |

#### `model`

模型 ID，例如 `claude-sonnet-5-5`。传入本站不提供的模型名会返回错误。

#### `max_tokens`

生成的最大 token 数，模型可能在达到上限前自然停止。官方最小值为 0：`max_tokens: 0` 用于只写入提示缓存、不生成内容（缓存预热）。

上限因模型而异：`claude-haiku-4-5-20251001` 为 64K，本站其余模型为 128K。开启思考时，思考 token 也计入 `max_tokens`。

!> 本站会把缺省或为 0 的 `max_tokens` 按模型替换为默认值，因此 `max_tokens: 0` 缓存预热在本站不保证生效；请始终显式填写大于 0 的 `max_tokens`。

#### `messages`

输入消息数组，每条消息包含 `role` 和 `content`。

**`role`** 可选值：

- `user`：用户消息，也用于回传 `tool_result`；
- `assistant`：模型之前的回复。连续的同角色消息会被合并为一轮；以 `assistant` 结尾即 prefill，仅 `claude-haiku-4-5-20251001` 支持，其他模型返回 400；
- `system`：对话中途追加的系统指令（不会使上方已缓存的前缀失效）。仅部分模型支持：`claude-opus-5-5`、`claude-sonnet-5-5`、`claude-haiku-5-5`、Fable 系列、`claude-opus-5`、`claude-opus-4-8`；`claude-sonnet-5` 等其他模型请使用顶层 `system`。限制：不能是第一条消息；必须紧跟在 `user` 消息（或以服务端工具结果结尾的 `assistant` 消息）之后，并位于 `assistant` 消息之前或作为最后一条；不能插在 `tool_use` 与其 `tool_result` 之间。不要把工具输出、网页内容等不可信文本放进 `system` 消息。

**`content`** 可以是字符串，也可以是内容块数组。字符串等价于一个 `text` 块，下面两种写法相同：

```json
{"role": "user", "content": "Hello, Claude"}
```

```json
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}
```

可用的内容块见下文「内容块类型」。

#### `system`

系统提示词，为 Claude 设定角色、背景和规则。可以是字符串，或 `text` 块数组：

```json
{
  "system": [
    {
      "type": "text",
      "text": "你是一名客服助手。",
      "cache_control": {"type": "ephemeral"}
    }
  ]
}
```

#### `thinking`

控制模型的思考行为，可选类型：

| 写法 | 说明 |
| --- | --- |
| `{"type": "adaptive"}` | 自适应思考，模型自行决定何时思考、思考多少，推荐写法。可选 `display`：`"summarized"`（返回思考摘要）或 `"omitted"`（`thinking` 字段为空字符串，只保留 `signature`） |
| `{"type": "enabled", "budget_tokens": 2048}` | 手动扩展思考，`budget_tokens` 最小 1024 且小于 `max_tokens`，同样可设 `display`。Claude 4.7 及之后的模型返回 400 |
| `{"type": "disabled"}` | 关闭思考，部分模型不接受 |
| `{"type": "between_tools"}` | 仅 `claude-sonnet-5-5`：关闭预先思考，只在工具调用之间输出进度更新；只能在 effort 为 `high` 及以下使用，且不能带其他字段 |

本站各模型的支持情况（来自官方 [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking) 文档；“≤high”指 effort 为 `low`/`medium`/`high` 时可用，`xhigh`/`max` 时返回 400）：

| 模型 | 不传 `thinking` | `adaptive` | `enabled` | `disabled` |
| --- | --- | --- | --- | --- |
| `claude-opus-5-5`、Fable 系列 | 自适应思考 | 支持 | 400 | 400 |
| `claude-sonnet-5-5` | 自适应思考 | 支持 | 400 | 400（改用 `between_tools`，≤high） |
| `claude-haiku-5-5`、`claude-opus-5` | 自适应思考 | 支持 | 400 | 关闭思考（≤high） |
| `claude-sonnet-5` | 自适应思考 | 支持 | 400 | 关闭思考 |
| `claude-opus-4-8`、`claude-opus-4-7` | 不思考 | 支持 | 400 | 关闭思考 |
| `claude-opus-4-6`、`claude-sonnet-4-6` | 不思考 | 支持 | 支持（已废弃） | 关闭思考 |
| `claude-haiku-4-5-20251001` | 不思考 | 400 | 支持 | 关闭思考 |

`display` 默认值：`claude-opus-4-6`、`claude-sonnet-4-6`、`claude-haiku-4-5-20251001` 为 `"summarized"`，其余模型为 `"omitted"`。`display` 只影响是否返回思考文本，不影响计费。

多轮对话和工具调用中，请把响应里的 `thinking` / `redacted_thinking` 块**原样**回传（含 `signature`），不要修改、删减或调换顺序。另外：

- 切换模型时也照常回传，目标模型无法读取的思考块会被自动忽略且不计费；
- `claude-opus-5-5`、`claude-sonnet-5-5`、`claude-haiku-5-5`、`claude-fable-5-2`、`claude-fable-5-1` 会校验思考块之前的对话前缀：如果改动了 `system`、`tools` 或更早的消息，其后的思考块可能导致 400，请以只追加的方式维护对话历史；
- `claude-fable-5-2`、`claude-sonnet-5-5`、`claude-haiku-5-5` 的思考块只在生成它的上游账号内有效。同一对话的后续请求如果由其他上游账号处理，这些思考块会被静默忽略（不报错，但模型看不到之前的推理）。

#### `output_config`

| 字段 | 说明 |
| --- | --- |
| `effort` | 投入程度：`low`、`medium`、`high`、`xhigh`、`max`。作用于全部输出 token（文字、工具调用和思考）。默认 `high`；`claude-opus-5-5`、`claude-haiku-5-5` 默认 `medium`。`xhigh` 不支持 `claude-opus-4-6`、`claude-sonnet-4-6`；`claude-haiku-4-5-20251001` 不支持 `effort` |
| `format` | 结构化输出：`{"type": "json_schema", "schema": {...}}`，见上文「结构化输出」示例 |

#### `tools`

工具定义数组。自定义工具字段：

| 字段 | 必需 | 说明 |
| --- | --- | --- |
| `name` | 是 | 工具名，1 至 128 个字符，需匹配 `^[a-zA-Z0-9_-]{1,128}$` |
| `description` | 否 | 工具说明，强烈建议写清楚用途和参数含义 |
| `input_schema` | 是 | 工具输入的 JSON Schema，`type` 为 `object` |
| `strict` | 否 | 设为 `true` 时保证模型生成的工具名和参数严格符合 Schema |
| `cache_control` | 否 | 在该工具处设置缓存断点 |
| `type` | 否 | 自定义工具可写 `"custom"` 或省略 |

?> Anthropic 内置工具（如 web search、web fetch、code execution、computer use、bash、text editor 等）版本更新较快，能否使用取决于上游渠道，本页不逐一列出，请参考官方 [Tool use 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)。

#### `tool_choice`

| 写法 | 说明 |
| --- | --- |
| `{"type": "auto"}` | 默认值，模型自行决定是否调用工具 |
| `{"type": "any"}` | 必须调用某个工具 |
| `{"type": "tool", "name": "get_weather"}` | 必须调用指定工具 |
| `{"type": "none"}` | 禁止调用工具 |

`auto`、`any`、`tool` 可附加 `"disable_parallel_tool_use": true`：`auto` 时最多调用一个工具，`any` / `tool` 时恰好调用一个工具。

!> `claude-opus-5-5`、`claude-sonnet-5-5`、`claude-fable-5-2`、`claude-fable-5-1` 不支持强制工具调用，`any` 和 `tool` 返回 400，请用 `auto` 配合提示词、`strict: true` 或结构化输出。使用手动扩展思考（`thinking.type` 为 `enabled`）时，也只能用 `auto` 或 `none`。

#### `cache_control`

缓存断点，可以写在请求顶层（自动缓存），也可以写在 `tools`、`system`、`messages` 中的具体内容块上：

```json
{"type": "ephemeral", "ttl": "5m"}
```

`type` 只能是 `ephemeral`；`ttl` 可选 `"5m"`（默认）或 `"1h"`。用法和限制见上文「提示缓存」示例。思考块不能直接设置 `cache_control`。

#### `stop_sequences`

自定义停止序列（字符串数组）。模型生成其中任一序列时停止，响应的 `stop_reason` 为 `stop_sequence`，`stop_sequence` 字段为命中的序列。

#### `stream`

为 `true` 时以 SSE 流式返回，见下文「流式事件」。生成时间较长（大 `max_tokens`、开启思考）的请求建议使用流式，避免超时。

#### `metadata`

| 字段 | 说明 |
| --- | --- |
| `user_id` | 终端用户的外部标识，最长 512 字符。请使用 UUID、哈希等不透明标识，不要包含姓名、邮箱、电话等个人信息 |

#### `temperature` / `top_p` / `top_k`

采样参数。`temperature` 默认 1.0，范围 0.0 至 1.0，越低越确定，越高越发散；`top_p` 为核采样阈值；`top_k` 只从概率最高的 K 个 token 中采样。

!> 在 `claude-opus-5-5`、`claude-sonnet-5-5`、`claude-haiku-5-5`、Fable 系列、`claude-opus-5`、`claude-sonnet-5`、`claude-opus-4-8`、`claude-opus-4-7` 上，任何非默认值都会返回 400；同时传 `temperature` 和 `top_p` 也返回 400（即使都是默认值）；这些模型的 `top_p` 默认值为 0.99，所以 `top_p: 1` 也会报错。建议在这些模型上完全不传这三个参数。

`claude-opus-4-6`、`claude-sonnet-4-6`、`claude-haiku-4-5-20251001` 在 `2023-06-01` 版本下仍可调整采样参数，但开启思考时不能使用 `temperature` 和 `top_k`，`top_p` 只能在 0.95 至 1 之间。使用 `anthropic-version: 2026-10-21` 时，任何模型带上这三个参数都返回 400。

#### 其他参数

官方还支持 `container`、`diagnostics`、`service_tier`、`speed`、`inference_geo` 等参数，以及需要 `anthropic-beta` 请求头的功能。其中 `service_tier`、`speed`、`inference_geo` 本站默认不转发；其余参数能否生效取决于上游渠道，请勿依赖。

### 内容块类型

`messages[].content` 中可用的主要内容块：

| `type` | 用途 | 主要字段 |
| --- | --- | --- |
| `text` | 文本 | `text`（至少 1 个字符）、`cache_control`、`citations` |
| `image` | 图片 | `source`：`{"type": "base64", "media_type": "image/jpeg", "data": "..."}` 或 `{"type": "url", "url": "..."}`；`cache_control` |
| `document` | 文档 | `source`：PDF 的 `base64`（`media_type` 为 `application/pdf`）或 `url`、纯文本 `{"type": "text", "media_type": "text/plain", "data": "..."}`、自定义内容 `{"type": "content", "content": [...]}`；可选 `title`、`context`、`citations`、`cache_control` |
| `search_result` | 搜索结果（便于引用） | `source`、`title`、`content`（`text` 块数组）、`citations` |
| `tool_use` | 回传历史中模型发起的工具调用 | `id`、`name`、`input` |
| `tool_result` | 工具执行结果，放在 `user` 消息中 | `tool_use_id`（必需）、`content`（可选，字符串或 `text` / `image` / `search_result` / `document` 块数组）、`is_error` |
| `thinking` | 回传历史中的思考块 | `thinking`、`signature`，必须原样回传 |
| `redacted_thinking` | 回传历史中的加密思考块 | `data`，必须原样回传 |

?> `image` 和 `document` 还支持 `{"type": "file", "file_id": "..."}` 来源，但需要配合 Files API，本站不提供。

## 📥 响应

### 消息对象

非流式请求成功时返回一个 `message` 对象：

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `id` | string | 消息唯一 ID，格式可能变化 |
| `type` | string | 固定为 `message` |
| `role` | string | 固定为 `assistant` |
| `model` | string | 处理请求的模型 |
| `content` | array | 模型生成的内容块 |
| `stop_reason` | string 或 null | 停止原因，见下文 |
| `stop_sequence` | string 或 null | 命中的自定义停止序列，否则为 null |
| `stop_details` | object 或 null | 仅 `stop_reason` 为 `refusal` 时有值：`type`（`refusal`）、`category`（如 `cyber`、`bio`、`frontier_llm`、`reasoning_extraction`、`general_harms`，或 null）、`explanation` |
| `usage` | object | token 用量，见下文 |

`content` 中常见的块类型：

- `text`：文本，`text` 字段为内容；开启引用时带 `citations` 数组；
- `thinking`：思考块，`thinking` 为摘要（`display` 为 `omitted` 时为空字符串），`signature` 用于回传校验；
- `redacted_thinking`：被安全系统加密的思考块，`data` 字段不可读，回传时原样带上；
- `tool_use`：工具调用，包含 `id`、`name`、`input`（对象）；请用 JSON 解析器读取 `input`，不要做字符串匹配；
- `server_tool_use`、`web_search_tool_result` 等：使用 Anthropic 服务端工具时出现。

### `stop_reason`

| 值 | 含义 |
| --- | --- |
| `end_turn` | 模型自然结束 |
| `max_tokens` | 达到 `max_tokens` 或模型上限，输出可能被截断 |
| `stop_sequence` | 生成了 `stop_sequences` 中的某个序列 |
| `tool_use` | 模型调用了一个或多个工具，需要执行工具并回传 `tool_result` |
| `pause_turn` | 长时间运行的回合被暂停（常见于服务端工具），可把响应原样作为 assistant 消息再次发送，让模型继续 |
| `refusal` | 安全分类器拒绝了请求（HTTP 状态码仍为 200），详情见 `stop_details`，此时 `content` 可能不完整 |
| `model_context_window_exceeded` | 超出模型上下文窗口 |

非流式响应中 `stop_reason` 一定非空；流式响应中，`message_start` 里为 null，最终值在 `message_delta` 中给出。

### `usage`

| 字段 | 说明 |
| --- | --- |
| `input_tokens` | 未命中、也未写入缓存的输入 token（即最后一个缓存断点之后的部分） |
| `cache_creation_input_tokens` | 本次写入缓存的输入 token |
| `cache_read_input_tokens` | 本次从缓存读取的输入 token |
| `cache_creation.ephemeral_5m_input_tokens` | 写入 5 分钟缓存的 token |
| `cache_creation.ephemeral_1h_input_tokens` | 写入 1 小时缓存的 token |
| `output_tokens` | 输出 token，包含思考 token（官方按此计费） |
| `output_tokens_details.thinking_tokens` | 其中用于思考的 token（仅供观察） |
| `server_tool_use` | 服务端工具调用次数，如 `web_search_requests`、`web_fetch_requests` |
| `service_tier` | 实际使用的服务等级：`standard`、`priority` 或 `batch` |

总输入 token = `input_tokens` + `cache_creation_input_tokens` + `cache_read_input_tokens`。由于 API 内部会对请求做格式转换，token 数与可见内容不会一一对应，例如即使返回空字符串，`output_tokens` 也不为 0。

### 流式事件

开启 `stream` 后，每个 SSE 事件都有事件名（`event: ...`）和对应的 JSON 数据（`data: {...}`，其中的 `type` 与事件名相同）。事件顺序：

1. `message_start`：包含一个 `content` 为空数组、`stop_reason` 为 null 的 `message` 对象，以及初始 `usage`；
2. 每个内容块依次发送：`content_block_start` → 若干 `content_block_delta` → `content_block_stop`，`index` 对应最终 `content` 数组中的位置；
3. 一个或多个 `message_delta`：`delta` 中给出 `stop_reason`、`stop_sequence`，与 `delta` 同级的 `usage` 为**累计** token 数；
4. `message_stop`：流结束。

流中可能随时穿插 `ping` 事件；以后也可能新增事件类型，客户端应忽略不认识的事件。

`content_block_delta` 的 `delta` 类型：

| `delta.type` | 所属块 | 字段 | 说明 |
| --- | --- | --- | --- |
| `text_delta` | `text` | `text` | 文本增量 |
| `input_json_delta` | `tool_use` | `partial_json` | 工具参数的部分 JSON 字符串，拼接后在 `content_block_stop` 时解析 |
| `thinking_delta` | `thinking` | `thinking` | 思考内容增量；`display` 为 `omitted` 时只有一个空字符串 |
| `signature_delta` | `thinking` | `signature` | 思考块签名，在该块的 `content_block_stop` 之前发送 |
| `citations_delta` | `text` | `citation` | 引用信息 |

`redacted_thinking` 块和服务端工具结果块会在 `content_block_start` 中一次性给出，没有 delta。

流开始后（HTTP 已返回 200）如果出错，会以 `error` 事件下发：

```text
event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
```

### 错误响应

请求失败时返回 4XX / 5XX 状态码，上游 Anthropic 错误的格式为：

```json
{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "This model does not support assistant message prefill. The conversation must end with a user message."
  },
  "request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"
}
```

部分错误还会在 `error.details.error_code` 中给出更细的错误码。

| HTTP 状态码 | `error.type` | 含义 |
| --- | --- | --- |
| 400 | `invalid_request_error` | 请求格式或内容有误（参数不合法、模型不支持某个功能等） |
| 401 | `authentication_error` | API 密钥有误 |
| 402 | `billing_error` | 账单或支付问题 |
| 403 | `permission_error` | 密钥无权访问该资源 |
| 404 | `not_found_error` | 资源不存在 |
| 409 | `conflict_error` | 请求与资源当前状态冲突 |
| 413 | `request_too_large` | 请求体超过大小上限 |
| 429 | `rate_limit_error` | 触发速率限制 |
| 500 | `api_error` | 上游内部错误 |
| 504 | `timeout_error` | 处理超时，长请求建议改用流式 |
| 529 | `overloaded_error` | 上游暂时过载 |

?> 本站网关层面的错误（如令牌无效、余额不足、无可用渠道）可能以 OpenAI 风格返回，例如 `{"error": {"code": "", "message": "错误描述", "type": "new_api_error"}}`。解析错误时请同时兼容两种格式：优先读取 `error.message`，再按 HTTP 状态码处理。

常见 400 错误与处理：

| 错误信息（节选） | 原因与处理 |
| --- | --- |
| `This model does not support assistant message prefill` | 模型不支持 prefill，去掉末尾的 `assistant` 消息 |
| `"thinking.type.enabled" is not supported for this model` | Claude 4.7 及之后的模型请改用 `{"type": "adaptive"}` 和 `output_config.effort` |
| `"thinking.type.disabled" is not supported for this model` | 该模型思考不能关闭，去掉 `thinking` 字段或降低 effort |
| `tool_choice: type "tool" and "any" are not supported for this model` | 改用 `tool_choice: {"type": "auto"}` |
| `` `thinking` or `redacted_thinking` blocks in the latest assistant message cannot be modified `` | 思考块被改动，请原样回传 |
