> ## Documentation Index
> Fetch the complete documentation index at: https://docs.playapi.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude 原生协议

> 通过网关调用 Messages，检查内容块与结束原因。

本指南直接使用网关的 Claude Messages 协议。先确认模型及渠道支持 `/v1/messages`；模型在列表中可见并不保证原生协议可用。这里的 `API_KEY` 是部署方签发的网关令牌，不是上游供应商密钥。

## 地址与请求结构

| 项目 | 本例约定 |
| - | - |
| 请求 | `POST /v1/messages` |
| 根地址 | `API_ROOT_URL` 不含 `/v1`，允许部署路径前缀 |
| 认证 | `x-api-key: API_KEY` |
| 版本 | `anthropic-version: 2023-06-01` |
| 指令与输入 | 顶层 `system`；`messages` 使用 `user` / `assistant` |
| 文本输出 | `content[]` 中的 `type: text` 块 |

项目接受原生认证头，按网关令牌校验；渠道适配器再设置上游凭据。不要把 Chat 的 `choices` 或 Responses 的 `output` 用于解析这个接口。项目适配器在请求未带版本头时使用上述默认版本，本例显式发送它。

## 运行准备

需要 Node.js 22.18+ 或 24；使用内置 `fetch`，无需安装 Anthropic SDK。在终端预先设置 `API_KEY`，然后设置根地址和实际模型 ID：

```sh theme={null}
export API_ROOT_URL="https://gateway.example.com"
export API_MODEL="YOUR_MODEL_ID"
# API_KEY must already be set in the process environment.
```

保存下方代码为 `native-claude.mts`，运行 `node native-claude.mts`。在文档目录可直接运行 `node examples/native-claude.mts`。成功时打印一行模型回答；固定 `max_tokens: 256` 是本例的输出预算，需目标模型支持，并不保证一定够用。

## TypeScript

完整示例：

```typescript theme={null}
const { API_ROOT_URL, API_KEY, API_MODEL } = process.env;
if (!API_ROOT_URL || !API_KEY || !API_MODEL) {
  throw new Error('Set API_ROOT_URL, API_KEY, and API_MODEL first.');
}

try {
  const response = await fetch(`${API_ROOT_URL.replace(/\/+$/, '')}/v1/messages`, {
    method: 'POST', redirect: 'error', signal: AbortSignal.timeout(60_000),
    headers: { 'Content-Type': 'application/json', 'x-api-key': API_KEY, 'anthropic-version': '2023-06-01' },
    body: JSON.stringify({
      model: API_MODEL, max_tokens: 256,
      system: 'Answer briefly in plain text.',
      messages: [{ role: 'user', content: 'Say hello in one short sentence.' }],
    }),
  });
  if (!response.ok) {
    console.error(`Request failed (HTTP ${response.status}). No automatic retry.`);
    process.exitCode = 1;
  } else {
    const result = await response.json();
    if (result.type !== 'message' || result.role !== 'assistant' || result.stop_reason !== 'end_turn'
      || !Array.isArray(result.content) || result.content.length === 0) {
      throw new Error('No complete text response.');
    }
    const text = result.content.map((block: { type?: string; text?: string }) => {
      if (!block || block.type !== 'text' || typeof block.text !== 'string') {
        throw new Error('Unsupported content block.');
      }
      return block.text;
    }).join('');
    if (!text.trim()) throw new Error('Empty text response.');
    console.log(text);
  }
} catch {
  console.error('Claude request failed or did not produce complete plain text. No automatic retry.');
  process.exitCode = 1;
}
export {};
```

## 完成状态与扩展边界

本例仅接受 `stop_reason: end_turn` 且全部内容块为文本。`max_tokens` 表示可能截断；`tool_use` 需要工具流程；`pause_turn`、拒答、空内容或其他块均使这个纯文本示例失败。HTTP 200 不等于已得到完整文本。本例禁用重定向，不自动重试，不输出上游错误体或密钥。

多轮时保留完整 assistant 内容块，再追加 user 消息；不要把上一轮压平成文本后丢弃工具或推理信息。原生工具通过 `tools[].input_schema` 定义，响应为 `tool_use`（`id`、`name`、`input`）；结果放在下一条 user 消息的 `tool_result`，用 `tool_use_id` 关联。不能发送 Chat 的 `role: tool`。涉及 thinking 时还需保留模型要求的签名和块顺序；本例不启用也不重放 thinking。

## 原生流式与计数接口

同一端点设置 `stream: true` 会使用 Claude SSE：`message_start`、`content_block_start/delta/stop`、`message_delta`、`message_stop`；错误也可能在 HTTP 200 后出现。工具参数增量是 `input_json_delta.partial_json`，按内容块索引组装，完整结束后再解析，不能套用 Chat 的 `delta.tool_calls`。

此页的可运行脚本覆盖非流式纯文本；[原生 SSE 与工具闭环](/zh/guides/native-claude-streaming)提供 Python 实现，包含参数组装和 thinking 签名重放。真实渠道仍需联调。[流式工具调用](/zh/guides/streaming-tools)提供 Chat / Responses 的可运行实现，并非 Claude 事件解析器。

项目尚未启用 `POST /v1/messages/count_tokens`，不要因为供应商 SDK 提供计数方法就假设网关也支持。

[Claude Messages 参考](/zh/api-reference/claude-messages) · [错误处理](/zh/guides/errors)

协议依据：[Anthropic Messages](https://platform.claude.com/docs/en/api/messages/create)、[流式事件](https://platform.claude.com/docs/en/build-with-claude/streaming)。项目路由和认证行为以本仓库实现为准。

[Read in English](/en/guides/native-claude)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.