Claude Messages
Anthropic 原生 Messages 协议。如果你的代码使用官方 anthropic SDK,只需将 base_url 指向网关即可。你也可以通过 OpenAI 兼容的 Chat Completions 端点调用 Claude 模型。
POST
https://apicdn.xyc.ai/v1/messages
鉴权请求头不同
该协议使用 x-api-key(而非 Authorization: Bearer),并且必须携带 anthropic-version。
请求示例
from anthropic import Anthropic
client = Anthropic(
base_url="https://apicdn.xyc.ai",
api_key="sk-xxxxxxxx",
)
msg = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Introduce yourself in one sentence."}],
)
print(msg.content[0].text)
curl https://apicdn.xyc.ai/v1/messages \
-H "x-api-key: sk-xxxxxxxx" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Introduce yourself in one sentence."}
]
}'
主要参数
| 参数 | 类型 | 说明 |
|---|---|---|
model | string | 必填。Claude 模型名称 |
messages | array | 必填。对话消息列表 |
max_tokens | int | 必填。生成的最大 token 数 |
system | string | 系统提示词 |
stream | bool | 是否流式输出 |
temperature | number | 采样温度 |
提示缓存(Prompt Caching)
对重复使用的长前缀(系统提示、工具定义、长文档)启用缓存,可大幅降低输入费用:缓存命中部分按输入价的 0.1 倍计费。支持 5 分钟(默认)与 1 小时两档 TTL。
使用 1h TTL 须同时满足三点:
| 要点 | 说明 |
|---|---|
| 请求头 | anthropic-beta: extended-cache-ttl-2025-04-11(缺失时 ttl 会被忽略,按 5m 处理) |
| 内容块标记 | 在要缓存前缀的末尾块加 "cache_control": {"type": "ephemeral", "ttl": "1h"} |
| 前缀长度 | 断点之前内容(含 system、tools)需 ≥ 约 1024 token,过短不会建缓存 |
{
"model": "claude-opus-5",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "…你的长系统提示…",
"cache_control": {"type": "ephemeral", "ttl": "1h"}
}
],
"messages": [{"role": "user", "content": "你好"}]
}
验证是否生效看响应 usage:首次请求 cache_creation.ephemeral_1h_input_tokens > 0 表示建缓存成功(此时 cache_read_input_tokens 为 0 是正常的);后续相同前缀命中时 cache_read_input_tokens > 0。
TTL 是上限而非保证
TTL 表示缓存最长保留时间(超时过期),并非"时限内保证命中"。长间隔请求偶发未命中并重建缓存属于机制内行为(官方直连相同)。请求间隔多在 5 分钟内时建议用默认 5m TTL:每次命中免费刷新计时,写入费率也更低(1.25x vs 1h 的 2x)。计费上:5m 写入按输入价 1.25 倍、1h 写入按 2 倍、命中读取按 0.1 倍。
响应结构
{
"id": "msg_xxxxxxxx",
"type": "message",
"role": "assistant",
"model": "claude-opus-5",
"content": [{"type": "text", "text": "..."}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 12, "output_tokens": 30}
}