Skip to Content
WikiAPI 文档消息接口 (Anthropic)

消息接口 (Anthropic)

使用 Anthropic 兼容的 API 格式创建模型响应。

端点

POST https://gateway.mytokengate.com/v1/messages

请求示例

curl --request POST \ --url https://gateway.mytokengate.com/v1/messages \ --header 'Authorization: Bearer <token>' \ --header 'Content-Type: application/json' \ --data '{ "model": "claude-sonnet-4-6", "messages": [ { "role": "user", "content": "中国大模型行业2025年将会迎来哪些机遇和挑战?" } ], "max_tokens": 8192 }'

认证

所有请求需要在 Authorization 头中包含 Bearer token:

Authorization: Bearer YOUR_API_KEY

请求参数

参数类型必填说明
modelstring模型名称,详见模型列表
messagesarray对话消息列表,详见消息格式
max_tokensinteger最大生成 token 数(1-128000)
systemstring 或 array系统提示词,详见系统提示词
streamboolean是否流式输出
temperaturefloat控制随机性,范围 0-1,默认 1。Opus 4.7+ 不支持
top_pfloat核采样参数,范围 0-1。Opus 4.7+ 不支持
top_kintegerTop-k 采样参数。Opus 4.7+ 不支持
stop_sequencesarray自定义停止序列
toolsarray工具定义,详见工具调用
tool_choiceobject工具选择策略,详见工具调用
thinkingobject思维/推理配置,详见思维模式

系统提示词

与 OpenAI 不同,Anthropic 使用独立的顶层 system 参数,而不是 messages 中的 role: "system" 消息:

{ "model": "claude-sonnet-4-6", "system": "You are a helpful coding assistant.", "messages": [...], "max_tokens": 4096 }

如需使用 Prompt Caching,请使用数组形式并添加 cache_control

{ "system": [ { "type": "text", "text": "You are a helpful assistant with access to the following documents...", "cache_control": { "type": "ephemeral" } } ] }

消息格式

用户消息(纯文本)

{ "role": "user", "content": "你好!" }

用户消息(含图片)

{ "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "<base64 编码的图片>" } }, { "type": "image", "source": { "type": "url", "url": "https://example.com/photo.jpg" } }, { "type": "text", "text": "描述这张图片。" } ] }

用户消息(含 PDF 文档)

{ "role": "user", "content": [ { "type": "document", "source": { "type": "base64", "media_type": "application/pdf", "data": "<base64 编码的 PDF>" } }, { "type": "text", "text": "总结这份文档。" } ] }

助手消息(含工具调用)

{ "role": "assistant", "content": [ { "type": "text", "text": "让我查一下天气。" }, { "type": "tool_use", "id": "toolu_abc123", "name": "get_weather", "input": { "location": "Paris", "unit": "celsius" } } ] }

工具结果消息

在 Anthropic 格式中,工具结果作为 role: "user" 消息中的 tool_result 内容块返回(不像 OpenAI 那样使用独立的 role: "tool" 消息):

{ "role": "user", "content": [ { "type": "tool_result", "tool_use_id": "toolu_abc123", "content": "巴黎22°C,晴天", "is_error": false } ] }

与 OpenAI 的关键差异:工具结果放在 role: "user"tool_result 内容块中;input 是 JSON 对象(而非 OpenAI 的字符串 arguments)。

响应

{ "id": "msg_01XFDUDYJgAACzvnptvVoYEL", "type": "message", "role": "assistant", "content": [ { "type": "text", "text": "响应内容..." } ], "model": "claude-sonnet-4-6", "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 2095, "output_tokens": 503, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0 } }

stop_reason 枚举

说明
end_turn自然结束
max_tokens达到 max_tokens 上限
stop_sequence命中自定义停止序列
tool_use模型正在调用工具
refusal安全拒绝

usage 字段

字段说明
input_tokens输入 token 数(未缓存部分)
output_tokens输出 token 数
cache_creation_input_tokens缓存写入的 token 数
cache_read_input_tokens缓存读取的 token 数

总输入 = input_tokens + cache_creation_input_tokens + cache_read_input_tokens

流式输出

设置 stream: true 以 Server-Sent Events (SSE) 格式接收响应:

import anthropic client = anthropic.Anthropic( api_key="YOUR_API_KEY", base_url="https://gateway.mytokengate.com/v1" ) with client.messages.stream( model="claude-sonnet-4-6", max_tokens=4096, messages=[{"role": "user", "content": "你好!"}] ) as stream: for text in stream.text_stream: print(text, end="")

流式事件序列

流式输出遵循以下事件顺序:

1. message_start → 消息元数据(id、model、role、初始 usage) 2. content_block_start → 新内容块开始(text、tool_use 或 thinking) 3. content_block_delta → 增量内容(text_delta、input_json_delta、thinking_delta) 4. content_block_stop → 内容块结束 5. message_delta → 停止原因和最终输出 token 用量 6. message_stop → 流式结束

Delta 类型

delta.type对应内容块类型字段说明
text_deltatextdelta.text文本内容增量
thinking_deltathinkingdelta.thinking思维内容增量
input_json_deltatool_usedelta.partial_json工具输入 JSON 片段

流式输出 Python 示例

with client.messages.stream( model="claude-sonnet-4-6", max_tokens=4096, messages=[{"role": "user", "content": "解释量子计算"}], thinking={"type": "enabled", "budget_tokens": 10000} ) as stream: for event in stream: if event.type == "content_block_delta": if event.delta.type == "thinking_delta": print(f"[思考] {event.delta.thinking}") elif event.delta.type == "text_delta": print(event.delta.text, end="")

工具调用

工具定义

{ "name": "get_weather", "description": "获取指定城市的当前天气", "input_schema": { "type": "object", "properties": { "location": { "type": "string", "description": "城市和州/省" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } }

注意:Anthropic 工具定义使用 input_schema(而非 OpenAI 的 parameters),且没有 type: "function" 包装层。

tool_choice 选项

说明
{"type": "auto"}模型自行决定是否使用工具(默认)
{"type": "any"}必须调用至少一个工具
{"type": "tool", "name": "xxx"}必须调用指定工具
{"type": "none"}不使用任何工具

完整工具调用示例

import anthropic import json client = anthropic.Anthropic( api_key="YOUR_API_KEY", base_url="https://gateway.mytokengate.com/v1" ) tools = [ { "name": "get_weather", "description": "获取指定城市的当前天气", "input_schema": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名称"} }, "required": ["city"] } } ] # 第 1 步:模型决定调用工具 response = client.messages.create( model="claude-sonnet-4-6", max_tokens=4096, messages=[{"role": "user", "content": "巴黎天气怎么样?"}], tools=tools ) # 第 2 步:提取工具调用并执行 tool_use_block = next(b for b in response.content if b.type == "tool_use") tool_result = get_weather(**tool_use_block.input) # 第 3 步:将工具结果回传 response = client.messages.create( model="claude-sonnet-4-6", max_tokens=4096, messages=[ {"role": "user", "content": "巴黎天气怎么样?"}, {"role": "assistant", "content": response.content}, { "role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use_block.id, "content": tool_result }] } ], tools=tools ) print(response.content[0].text)

思维模式

Anthropic 模型支持扩展思维(Extended Thinking),用于复杂推理任务。

基本用法

{ "model": "claude-sonnet-4-6", "max_tokens": 16000, "thinking": { "type": "enabled", "budget_tokens": 10000 }, "messages": [{"role": "user", "content": "一步步解这道数学题..."}] }
  • budget_tokens 必须小于 max_tokens(最小 1024)
  • 启用思维模式后,响应 content 数组中会包含 thinking 块(位于 text 块之前)

含思维的响应

{ "content": [ { "type": "thinking", "thinking": "让我逐步分析..." }, { "type": "text", "text": "根据我的分析..." } ], "stop_reason": "end_turn" }

Prompt Caching

Anthropic 支持 Prompt Caching 以减少重复上下文的成本和延迟。在内容块上添加 cache_control

{ "system": [ { "type": "text", "text": "You are a helpful assistant with access to these documents: ...", "cache_control": { "type": "ephemeral" } } ], "messages": [ { "role": "user", "content": [ { "type": "text", "text": "文档中关于 X 是怎么说的?", "cache_control": { "type": "ephemeral" } } ] } ] }
  • 每请求最多 4 个缓存断点
  • 缓存 TTL:5 分钟(默认)或 1 小时({ "type": "ephemeral", "ttl": "1h" }
  • 缓存命中价格约为标准输入价格的 0.1 倍
  • 缓存写入价格为输入价格的 1.25 倍(5 分钟 TTL)或 2 倍(1 小时 TTL)
  • 通过响应中的 usage.cache_read_input_tokens 验证缓存是否命中

错误码

状态码说明
400请求参数无效
401API Key 无效或缺失
404模型不存在
429触发限流
503/504服务暂时不可用
Last updated on