消息接口 (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请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 模型名称,详见模型列表 |
messages | array | 是 | 对话消息列表,详见消息格式 |
max_tokens | integer | 是 | 最大生成 token 数(1-128000) |
system | string 或 array | 否 | 系统提示词,详见系统提示词 |
stream | boolean | 否 | 是否流式输出 |
temperature | float | 否 | 控制随机性,范围 0-1,默认 1。Opus 4.7+ 不支持 |
top_p | float | 否 | 核采样参数,范围 0-1。Opus 4.7+ 不支持 |
top_k | integer | 否 | Top-k 采样参数。Opus 4.7+ 不支持 |
stop_sequences | array | 否 | 自定义停止序列 |
tools | array | 否 | 工具定义,详见工具调用 |
tool_choice | object | 否 | 工具选择策略,详见工具调用 |
thinking | object | 否 | 思维/推理配置,详见思维模式 |
系统提示词
与 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_delta | text | delta.text | 文本内容增量 |
thinking_delta | thinking | delta.thinking | 思维内容增量 |
input_json_delta | tool_use | delta.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 | 请求参数无效 |
| 401 | API Key 无效或缺失 |
| 404 | 模型不存在 |
| 429 | 触发限流 |
| 503/504 | 服务暂时不可用 |
Last updated on