> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# Claude Messages

POST https://direct.beatapi.io/v1/messages
Content-Type: application/json

用一个 BeatAPI 密钥，通过同一个 Anthropic Messages 端点调用 Claude Fable 5.1、Opus 5.5、Sonnet 5.5 和 Haiku 5.5。- 一个端点 `POST /v1/messages` 覆盖当前所有 Claude 模型，改 `model` 即可切换。
- 支持文本与图片输入、文本输出、流式输出、工具调用、扩展思考和提示缓存。
- 兼容 Anthropic SDK：把 base URL 设为 `https://direct.beatapi.io`（不带 `/v1`），换成 BeatAPI 密钥即可。
- Claude 模型只用 Anthropic Messages。调用 `/v1/responses` 会返回 `400`。文本请求建议使用 `https://direct.beatapi.io` 作为 base URL：它不受 Cloudflare 100 秒限制，长时间的非流式请求不会被中途切断。`https://api.beatapi.io` 同样可用；如果你的网络访问不了 `direct.beatapi.io`，请改用它作为备用。两个域名的密钥、模型和价格完全一致。图片和视频 API 只使用 `https://api.beatapi.io`。POST/v1/messages试一试在调试窗口里打开本接口，填入你的 BeatAPI API 密钥即可发送。调用是真实的，费用从你自己的余额中扣除。## 模型把下列 ID 之一作为 `model` 发送。它们是各自独立的模型，不是互相的别名。| 模型 ID               | 上下文（tokens） | 最大输出（tokens） | 定位                                                | 输入，美元 / 100 万 tokens | 输出，美元 / 100 万 tokens | 说明                            |
| ------------------- | ----------- | ------------ | ------------------------------------------------- | -------------------- | -------------------- | ----------------------------- |
| `claude-opus-5-5`   | 1,000,000   | 128,000      | Claude Opus 模型，面向长程智能体编程与知识工作，价格低于 Opus 5         | \$2.00               | \$10.00              | 适合长时间运行的智能体编程和知识工作。           |
| `claude-sonnet-5-5` | 1,000,000   | 128,000      | Claude Sonnet 5.5，面向编程、推理与专业工作，支持 100 万 token 上下文 | \$1.00               | \$5.00               | 日常编程、推理和专业工作。                 |
| `claude-haiku-5-5`  | 1,000,000   | 128,000      | 速度最快的 Claude 模型，适合分类、抽取、路由等大批量低延迟任务               | \$0.05               | \$0.25               | 速度最快的 Claude，适合分类、抽取、路由等高频任务。 |
| `claude-fable-5-1`  | 1,000,000   | 128,000      | Claude 模型，面向高难度推理与长程智能体任务                         | \$5.00               | \$25.00              | 适合长文写作，以及对文风和结构要求最高的工作。       |- 价格为基础档，已计入折扣。长上下文档、缓存命中输入价和缓存写入价不在本表内，见[价格表](https://beatapi.io/pricing)。
- `—` 表示目录未公布该数字。本系列仍可调用的旧 ID 见[旧型号](/text-api/legacy-models)。## 快速开始在服务端安装 `anthropic` 包，把密钥放在 `BEATAPI_API_KEY`，不要把它写进浏览器代码。以下是请求示例，不是真实的模型输出记录。从 `content` 里的 `text` 块读取答案，再检查 `stop_reason` 和 `usage`。HTTP 200 不能证明答案满足你的任务，请在应用里校验内容。文本请求直接返回，不要为它们轮询 `/v1/tasks`。```bash title="cURL"
curl --request POST \
  --url https://direct.beatapi.io/v1/messages \
  --header "x-api-key: $BEATAPI_API_KEY" \
  --header 'anthropic-version: 2023-06-01' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
}'
``````python title="Python"
import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ["BEATAPI_API_KEY"], base_url="https://direct.beatapi.io")
message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[
      {
        "role": "user",
        "content": "Design a resilient webhook retry strategy for a payments API."
      }
    ],
)
print(message.content[0].text)
``````javascript title="JavaScript"
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({ apiKey: process.env.BEATAPI_API_KEY, baseURL: "https://direct.beatapi.io" });
const message = await client.messages.create({
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
});
console.log(message.content[0].text);
```## 端点与鉴权`POST https://direct.beatapi.io/v1/messages`x-api-key
string
必需你的 BeatAPI 密钥。也接受 `Authorization: Bearer <BEATAPI_API_KEY>`。请求要带 `anthropic-version` 头，例如 `anthropic-version: 2023-06-01`。密钥放在 `x-api-key`，或放在 `Authorization: Bearer <key>`，两种都行，所以现有的 Anthropic 客户端只需要改 base URL。Claude 模型只用 Anthropic Messages。调用 `/v1/responses` 会返回 `400`。## 请求参数接受标准的 Anthropic Messages 字段。请求格式兼容不代表每个 beta 功能或服务端工具都受支持，请测试你依赖的选项。model
string
必需准确的模型 ID。**可选值**：`claude-fable-5-1`, `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5`- 仍可调用的旧 ID（`claude-opus-5`、`claude-sonnet-5`、`claude-haiku-4-5-20251001`）见[旧型号](/text-api/legacy-models)。
- 用你的密钥调用 `GET /v1/models`，确认该密钥已开通哪些模型。max_tokens
integer
必需生成 token 数的上限，包含思考。- 请始终显式传入。缺省或为 `0` 时会套用一个默认上限，这个默认值可能比你预期的小。
- 接受的最大值是 1,073,741,823，更大的值返回 `400 bad_request`。请保持在上表中该模型的最大输出以内。
- `max_tokens` 还用来估算请求需要的余额。过大的值即使实际输出很短，也可能被 `402 insufficient_credits` 拒绝。按实际需要设置。messages
object[]
必需对话内容，最早的消息在前。每条消息有 `role`（`user` 或 `assistant`）和 `content`。`content` 可以是字符串，也可以是内容块数组。- 常用的块类型：`text`、`image`（base64 或 URL 来源）、`tool_use`（在 assistant 消息里）和 `tool_result`（在 user 消息里）。
- `messages` 为空或缺失会返回 `400 bad_request`。**示例**```json
[
  {
    "role": "user",
    "content": [
      { "type": "text", "text": "What is in this image?" },
      { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "<base64>" } }
    ]
  }
]
```system
string | object[]
可选系统提示词。可以是字符串，也可以是 `text` 块数组。在块上加 `cache_control`，可以缓存一段较长且稳定的前缀。**示例**```json
[
  {
    "type": "text",
    "text": "<long, stable instructions>",
    "cache_control": { "type": "ephemeral" }
  }
]
```stream
boolean
可选默认值: false以服务端推送事件的形式返回答案。见下文的流式输出一节。**默认值**：`false`stop_sequences
string[]
可选遇到这些自定义字符串就停止生成。此时响应里 `stop_reason` 为 `"stop_sequence"`。tools
object[]
可选模型可以调用的工具。每个工具有 `name`、`description` 和 `input_schema`（JSON Schema）。模型调用工具时，响应里 `stop_reason` 为 `"tool_use"`；运行工具后，在下一条消息的 `tool_result` 块里返回结果。**示例**```json
[
  {
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "input_schema": {
      "type": "object",
      "properties": { "city": { "type": "string" } },
      "required": ["city"]
    }
  }
]
```tool_choice
object
可选是否以及如何必须使用 `tools`。**可选值**：`{"type":"auto"}`, `{"type":"any"}`, `{"type":"tool","name":"..."}`, `{"type":"none"}`- `auto` 由模型决定，`any` 强制使用某个工具，`tool` 强制使用指定名称的工具，`none` 禁止使用工具。**示例**```json
{ "type": "auto" }
{ "type": "tool", "name": "get_weather" }
```thinking
object
可选扩展思考。用 `type` 打开或关闭。思考 token 计入 `max_tokens`，并按输出 token 计费。**可选值**：`adaptive`, `enabled`, `disabled`- `thinking.type` 取上面的值之一。`enabled` 需要同时传 `thinking.budget_tokens`（整数，至少 1,024，且小于 `max_tokens`）。
- `thinking.display` 取 `summarized` 或 `omitted`。较新的模型除非你要求 `summarized`，否则可能不返回思考文本。
- 自适应思考的深度用 `output_config.effort` 设置。**各模型说明**- `claude-fable-5-1`：用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。
- `claude-opus-5-5`：用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。
- `claude-sonnet-5-5`：用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。**示例**```json
{
  "thinking": { "type": "adaptive" },
  "output_config": { "effort": "high" }
}
```output_config.effort
string
可选模型的推理强度。建议从 `high` 开始，再在你自己的负载上评估低一档和高一档的效果。**可选值**：`low`, `medium`, `high`, `xhigh`, `max`cache_control
object
可选提示缓存。放在 `system`、`messages` 或 `tools` 的块上，缓存到该块为止的全部内容；也可以放在请求顶层。`ttl` 取 `5m`（默认）或 `1h`。**可选值**：`{"type":"ephemeral"}`- 缓存读取、5 分钟缓存写入和 1 小时缓存写入分别计量；命中缓存的前缀按缓存读取收费，不按新输入收费。
- 命中情况见 `usage.cache_read_input_tokens` 和 `usage.cache_creation_input_tokens`。**示例**```json
{ "type": "ephemeral" }
{ "type": "ephemeral", "ttl": "1h" }
```## 工具调用循环当 `stop_reason` 为 `tool_use` 时，把 assistant 消息原样追加到 `messages`，运行工具，再把结果放进下一条 `user` 消息的 `tool_result` 块里。再次发送同样的 `tools`。```json
{
  "max_tokens": 1024,
  "messages": [
    { "role": "user", "content": "What is the weather in Paris?" },
    {
      "role": "assistant",
      "content": [
        { "type": "tool_use", "id": "toolu_example", "name": "get_weather", "input": { "city": "Paris" } }
      ]
    },
    {
      "role": "user",
      "content": [
        { "type": "tool_result", "tool_use_id": "toolu_example", "content": "18 C, light rain" }
      ]
    }
  ]
}
```## 响应非流式调用返回一个 JSON 对象。以下是精简后的示例。```json
{
  "id": "msg_example",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-5-5",
  "content": [
    {
      "type": "text",
      "text": "Retry with exponential backoff and jitter, and make every handler idempotent."
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 19,
    "output_tokens": 16
  }
}
```### 响应字段| 字段                                  | 类型        | 说明                                                                                        |
| ----------------------------------- | --------- | ----------------------------------------------------------------------------------------- |
| `id`                                | `string`  | 消息 ID。请与请求 ID 一起记录，便于支持排查和账单核对。                                                           |
| `model`                             | `string`  | 实际回答的模型。                                                                                  |
| `content[].type`                    | `string`  | `text`、`tool_use`，返回思考文本时还有 `thinking`。                                                   |
| `content[].text`                    | `string`  | `text` 块里的答案文本。                                                                           |
| `stop_reason`                       | `string`  | `end_turn` 表示答案完整；`max_tokens` 表示达到了 `max_tokens`；还有 `stop_sequence`；模型调用工具时为 `tool_use`。 |
| `usage.input_tokens`                | `integer` | 没有命中缓存的输入 token 数。                                                                        |
| `usage.output_tokens`               | `integer` | 输出 token 数，包含思考。                                                                          |
| `usage.cache_read_input_tokens`     | `integer` | 从提示缓存读取的输入 token 数。                                                                       |
| `usage.cache_creation_input_tokens` | `integer` | 写入提示缓存的输入 token 数。                                                                        |## 流式输出设置 `"stream": true`。响应是 Anthropic 格式的服务端推送事件流，与 Anthropic SDK 兼容。- 事件依次为 `message_start`、`ping`、`content_block_start`、`content_block_delta`、`content_block_stop`、`message_delta` 和 `message_stop`。
- 文本在 `text_delta` 里，工具入参在 `input_json_delta` 里（把片段拼起来再解析），思考文本在 `thinking_delta` 里。
- `stop_reason` 和最终的输出 token 数在 `message_delta` 里。
- 流式响应是 `text/event-stream`，非流式是 `application/json`。调用模型之前发生的失败，以带 HTTP 状态码的普通 JSON 错误返回，不会作为流事件出现。
- 请设置明确的超时，并安全地重连流式响应。```text
event: message_start
data: {"type":"message_start","message":{"id":"msg_example","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":19,"output_tokens":1}}}

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

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

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Retry"}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" with backoff"}}

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":16}}

event: message_stop
data: {"type":"message_stop"}
```## 错误| 错误或现象                                           | 原因                                                           | 处理                                          |
| ----------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------- |
| `400`：缺少 `messages` 或 `model`，或 `max_tokens` 过大 | `messages` 为空或缺失、`model` 为空，或 `max_tokens` 超过 1,073,741,823。 | 两个字段都要传，并让 `max_tokens` 在限制以内。              |
| `400`：调用 `/v1/responses`                        | Claude 模型不在 OpenAI Responses 上提供服务。                          | 改用 `POST /v1/messages`。                     |
| `400`：与 `thinking` 设置有关                         | 模型不接受该设置，例如在使用自适应思考的模型上传了 `budget_tokens`。                   | 按上文 `thinking` 下为该模型列出的方式设置。                |
| `402 insufficient_credits`                      | 余额低于请求的价格，常见原因是 `max_tokens` 过大。                             | 充值，或调低 `max_tokens`。                        |
| `403 forbidden`                                 | 账号使用的是免费额度，而该模型不在免费清单里；或该模型不在密钥所属分组的范围内。                     | 充值、改用免费模型，或使用分组能访问该模型的密钥。                   |
| `404 not_found`                                 | 模型 ID 不存在，或该密钥没有开通它。                                         | 用 `GET /v1/models` 查看已开通的模型。                |
| `429 rate_limit_exceeded`                       | 达到账号或免费模型的限额。                                                | 等待 `Retry-After` 指定的时间后重试。                  |
| `200`，但 `stop_reason: "max_tokens"` 且答案很短或为空    | `max_tokens` 在写出答案之前就被用完了，常常是被思考占掉。                          | 调高 `max_tokens`，或调低 `output_config.effort`。 |### HTTP 错误速查认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。| HTTP 状态码 | 错误码                                                      | 怎么做                                             |
| -------- | -------------------------------------------------------- | ----------------------------------------------- |
| 400      | `bad_request`、`content_policy_violation`                 | 修正请求或输入，不要原样重发。                                 |
| 401      | `missing_api_key`、`invalid_api_key`                      | 检查密钥，不要重试。                                      |
| 402      | `insufficient_credits`                                   | 充值，或提高密钥额度。过大的 `max_tokens` 也可能触发。              |
| 403      | `forbidden`                                              | 模型不在该密钥的分组或 IP 白名单内，或免费额度不能调用该模型。               |
| 404      | `not_found`                                              | 模型不存在：用 `GET /v1/models` 查看已开通的模型。              |
| 429      | `rate_limit_exceeded`                                    | 等待 `Retry-After` 或 `retry_after_seconds` 后退避重试。 |
| 500      | `internal_error`、`temporary_error`                       | 退避后重试一两次。                                       |
| 503      | `model_unavailable`、`upstream_timeout`、`temporary_error` | 退避重试，或换用其他模型。                                   |完整的错误码表和重试策略见[错误码](/errors#text-endpoints)。## 注意事项- Claude 模型只用 Anthropic Messages，不在 [OpenAI Responses](/text-api/gpt/responses) 上提供。
- 思考 token 按输出 token 计费，并计入 `max_tokens`。请为思考和答案一起预留足够的输出额度。
- 密钥只放在可信的服务端，记录响应里的请求 ID，只对 `429`、`500` 和 `503` 重试。

Reference: https://docs.beatapi.io/api-reference/text-api/claude-messages

## Authentication

- `Authorization` header (bearer token, required) — Send your API key as `Authorization: Bearer <BEATAPI_API_KEY>`.

## Servers

- `https://direct.beatapi.io` (Direct, default)
- `https://api.beatapi.io` (API)

## Request

### Body (application/json)

This endpoint expects an object.

- `model` (enum, required) — 准确的模型 ID。 仍可调用的旧 ID（`claude-opus-5`、`claude-sonnet-5`、`claude-haiku-4-5-20251001`）见[旧型号](/text-api/legacy-models)。 用你的密钥调用 `GET /v1/models`，确认该密钥已开通哪些模型。 `claude-fable-5-1`, `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5`
  - Allowed values: `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5`, `claude-fable-5-1`
- `max_tokens` (integer, required) — 生成 token 数的上限，包含思考。 请始终显式传入。缺省或为 `0` 时会套用一个默认上限，这个默认值可能比你预期的小。 接受的最大值是 1,073,741,823，更大的值返回 `400 bad_request`。请保持在上表中该模型的最大输出以内。 `max_tokens` 还用来估算请求需要的余额。过大的值即使实际输出很短，也可能被 `402 insufficient_credits` 拒绝。按实际需要设置。
- `messages` (list of V1MessagesPostRequestBodyContentApplicationJsonSchemaMessagesItems, required) — 对话内容，最早的消息在前。每条消息有 `role`（`user` 或 `assistant`）和 `content`。`content` 可以是字符串，也可以是内容块数组。 常用的块类型：`text`、`image`（base64 或 URL 来源）、`tool_use`（在 assistant 消息里）和 `tool_result`（在 user 消息里）。 `messages` 为空或缺失会返回 `400 bad_request`。
- `system` (V1MessagesPostRequestBodyContentApplicationJsonSchemaSystem, optional) — 系统提示词。可以是字符串，也可以是 `text` 块数组。在块上加 `cache_control`，可以缓存一段较长且稳定的前缀。
- `stream` (boolean, optional, default: false) — 以服务端推送事件的形式返回答案。见下文的流式输出一节。
- `stop_sequences` (list of string, optional) — 遇到这些自定义字符串就停止生成。此时响应里 `stop_reason` 为 `"stop_sequence"`。
- `tools` (list of V1MessagesPostRequestBodyContentApplicationJsonSchemaToolsItems, optional) — 模型可以调用的工具。每个工具有 `name`、`description` 和 `input_schema`（JSON Schema）。模型调用工具时，响应里 `stop_reason` 为 `"tool_use"`；运行工具后，在下一条消息的 `tool_result` 块里返回结果。
- `tool_choice` (V1MessagesPostRequestBodyContentApplicationJsonSchemaToolChoice, optional) — 是否以及如何必须使用 `tools`。 `auto` 由模型决定，`any` 强制使用某个工具，`tool` 强制使用指定名称的工具，`none` 禁止使用工具。 `{"type":"auto"}`, `{"type":"any"}`, `{"type":"tool","name":"..."}`, `{"type":"none"}`
- `thinking` (V1MessagesPostRequestBodyContentApplicationJsonSchemaThinking, optional) — 扩展思考。用 `type` 打开或关闭。思考 token 计入 `max_tokens`，并按输出 token 计费。 `thinking.type` 取上面的值之一。`enabled` 需要同时传 `thinking.budget_tokens`（整数，至少 1,024，且小于 `max_tokens`）。 `thinking.display` 取 `summarized` 或 `omitted`。较新的模型除非你要求 `summarized`，否则可能不返回思考文本。 自适应思考的深度用 `output_config.effort` 设置。 `claude-fable-5-1`: 用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。 `claude-opus-5-5`: 用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。 `claude-sonnet-5-5`: 用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。 `adaptive`, `enabled`, `disabled`
- `output_config` (V1MessagesPostRequestBodyContentApplicationJsonSchemaOutputConfig, optional)
- `cache_control` (V1MessagesPostRequestBodyContentApplicationJsonSchemaCacheControl, optional) — 提示缓存。放在 `system`、`messages` 或 `tools` 的块上，缓存到该块为止的全部内容；也可以放在请求顶层。`ttl` 取 `5m`（默认）或 `1h`。 缓存读取、5 分钟缓存写入和 1 小时缓存写入分别计量；命中缓存的前缀按缓存读取收费，不按新输入收费。 命中情况见 `usage.cache_read_input_tokens` 和 `usage.cache_creation_input_tokens`。 `{"type":"ephemeral"}`

## Response

### 200

非流式调用返回一个 JSON 对象。以下是精简后的示例。

- `id` (string, optional) — 消息 ID。请与请求 ID 一起记录，便于支持排查和账单核对。
- `model` (string, optional) — 实际回答的模型。
- `content` (list of V1MessagesPostResponsesContentApplicationJsonSchemaContentItems, optional)
- `stop_reason` (string, optional) — `end_turn` 表示答案完整；`max_tokens` 表示达到了 `max_tokens`；还有 `stop_sequence`；模型调用工具时为 `tool_use`。
- `usage` (V1MessagesPostResponsesContentApplicationJsonSchemaUsage, optional)

## Errors

### 400 Bad Request Error

`bad_request`、`content_policy_violation` 修正请求或输入，不要原样重发。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

### 401 Unauthorized Error

`missing_api_key`、`invalid_api_key` 检查密钥，不要重试。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

### 402 Payment Required Error

`insufficient_credits` 充值，或提高密钥额度。过大的 `max_tokens` 也可能触发。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

### 403 Forbidden Error

`forbidden` 模型不在该密钥的分组或 IP 白名单内，或免费额度不能调用该模型。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

### 404 Not Found Error

`not_found` 模型不存在：用 `GET /v1/models` 查看已开通的模型。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

### 429 Too Many Requests Error

`rate_limit_exceeded` 等待 `Retry-After` 或 `retry_after_seconds` 后退避重试。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

### 500 Internal Server Error

`internal_error`、`temporary_error` 退避后重试一两次。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

### 503 Service Unavailable Error

`model_unavailable`、`upstream_timeout`、`temporary_error` 退避重试，或换用其他模型。 认证、路由、限速和未知模型这几类失败发生在调用模型之前，返回 BeatAPI 信封：`error.code`、`error.message`、`retryable`、`request_id`。其余失败保持 Anthropic 格式 `{"type": "error", "error": {"type", "message"}}`：错误码在 `error.type`，request id 附在 `message` 末尾。详见[错误码](/errors#text-endpoints)。

- `map from string to any`

## Types

### V1MessagesPostRequestBodyContentApplicationJsonSchemaMessagesItems

- `role` (string, required)
- `content` (V1MessagesPostRequestBodyContentApplicationJsonSchemaMessagesItemsContent, required)

### V1MessagesPostRequestBodyContentApplicationJsonSchemaSystem

系统提示词。可以是字符串，也可以是 `text` 块数组。在块上加 `cache_control`，可以缓存一段较长且稳定的前缀。

### V1MessagesPostRequestBodyContentApplicationJsonSchemaToolsItems

### V1MessagesPostRequestBodyContentApplicationJsonSchemaToolChoice

是否以及如何必须使用 `tools`。 `auto` 由模型决定，`any` 强制使用某个工具，`tool` 强制使用指定名称的工具，`none` 禁止使用工具。 `{"type":"auto"}`, `{"type":"any"}`, `{"type":"tool","name":"..."}`, `{"type":"none"}`

### V1MessagesPostRequestBodyContentApplicationJsonSchemaThinking

扩展思考。用 `type` 打开或关闭。思考 token 计入 `max_tokens`，并按输出 token 计费。 `thinking.type` 取上面的值之一。`enabled` 需要同时传 `thinking.budget_tokens`（整数，至少 1,024，且小于 `max_tokens`）。 `thinking.display` 取 `summarized` 或 `omitted`。较新的模型除非你要求 `summarized`，否则可能不返回思考文本。 自适应思考的深度用 `output_config.effort` 设置。 `claude-fable-5-1`: 用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。 `claude-opus-5-5`: 用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。 `claude-sonnet-5-5`: 用 `{"type":"adaptive"}`，深度用 `output_config.effort` 设置；`budget_tokens` 会被拒绝。 `adaptive`, `enabled`, `disabled`

- `type` (enum, optional)
  - Allowed values: `adaptive`, `enabled`, `disabled`

### V1MessagesPostRequestBodyContentApplicationJsonSchemaOutputConfig

- `effort` (enum, optional) — 模型的推理强度。建议从 `high` 开始，再在你自己的负载上评估低一档和高一档的效果。 `low`, `medium`, `high`, `xhigh`, `max`
  - Allowed values: `low`, `medium`, `high`, `xhigh`, `max`

### V1MessagesPostRequestBodyContentApplicationJsonSchemaCacheControl

提示缓存。放在 `system`、`messages` 或 `tools` 的块上，缓存到该块为止的全部内容；也可以放在请求顶层。`ttl` 取 `5m`（默认）或 `1h`。 缓存读取、5 分钟缓存写入和 1 小时缓存写入分别计量；命中缓存的前缀按缓存读取收费，不按新输入收费。 命中情况见 `usage.cache_read_input_tokens` 和 `usage.cache_creation_input_tokens`。 `{"type":"ephemeral"}`

### V1MessagesPostResponsesContentApplicationJsonSchemaContentItems

- `type` (string, optional) — `text`、`tool_use`，返回思考文本时还有 `thinking`。
- `text` (string, optional) — `text` 块里的答案文本。

### V1MessagesPostResponsesContentApplicationJsonSchemaUsage

- `input_tokens` (integer, optional) — 没有命中缓存的输入 token 数。
- `output_tokens` (integer, optional) — 输出 token 数，包含思考。
- `cache_read_input_tokens` (integer, optional) — 从提示缓存读取的输入 token 数。
- `cache_creation_input_tokens` (integer, optional) — 写入提示缓存的输入 token 数。

### V1MessagesPostRequestBodyContentApplicationJsonSchemaMessagesItemsContent

## Examples

**Request**

```json
{
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
}
```

**Response**

```json
{
  "id": "msg_example",
  "model": "claude-sonnet-5-5",
  "content": [
    {
      "type": "text",
      "text": "Retry with exponential backoff and jitter, and make every handler idempotent."
    }
  ],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 19,
    "output_tokens": 16
  },
  "role": "assistant",
  "stop_sequence": null,
  "type": "message"
}
```

**SDK Code**

```python 快速开始
import requests

url = "https://direct.beatapi.io/v1/messages"

payload = {
    "model": "claude-sonnet-5-5",
    "max_tokens": 1024,
    "messages": [
        {
            "role": "user",
            "content": "Design a resilient webhook retry strategy for a payments API."
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 快速开始
const url = 'https://direct.beatapi.io/v1/messages';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"claude-sonnet-5-5","max_tokens":1024,"messages":[{"role":"user","content":"Design a resilient webhook retry strategy for a payments API."}]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 快速开始
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://direct.beatapi.io/v1/messages"

	payload := strings.NewReader("{\n  \"model\": \"claude-sonnet-5-5\",\n  \"max_tokens\": 1024,\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 快速开始
require 'uri'
require 'net/http'

url = URI("https://direct.beatapi.io/v1/messages")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"claude-sonnet-5-5\",\n  \"max_tokens\": 1024,\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java 快速开始
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://direct.beatapi.io/v1/messages")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"claude-sonnet-5-5\",\n  \"max_tokens\": 1024,\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}")
  .asString();
```

```php 快速开始
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://direct.beatapi.io/v1/messages', [
  'body' => '{
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 快速开始
using RestSharp;

var client = new RestClient("https://direct.beatapi.io/v1/messages");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"claude-sonnet-5-5\",\n  \"max_tokens\": 1024,\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Design a resilient webhook retry strategy for a payments API.\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 快速开始
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "messages": [
    [
      "role": "user",
      "content": "Design a resilient webhook retry strategy for a payments API."
    ]
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://direct.beatapi.io/v1/messages")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```