Claude缓存
# Anthropic Prompt Caching Guide / Anthropic 提示缓存指南 --- To enable prompt caching, your request body needs TWO things: 要让缓存生效,你的请求体需要 **两样东西**: 1. `cache_control: {"type": "ephemera...
Anthropic Prompt Caching Guide / Anthropic 提示缓存指南
本站所有后缀为-thinking的模型均为openai格式适配,使用缓存时不要添加-thinking 当您使用claude/anthropic的v1/massage路径请求时,请勿添加-thinking后缀;模型的思考/推理只要传递正确参数,即为thinking模型。 当您启用缓存时,添加-thinking后缀会因为格式转化成openai导致缓存字段失效,请务必注意。
To enable prompt caching, your request body needs TWO things:
要让缓存生效,你的请求体需要 两样东西:
-
cache_control: {"type": "ephemeral"}on system/message content blocks在 system 或 message 的内容块上加
cache_control -
metadata: {"user_id": ""}at the top level of the request body在请求体顶层加
metadata.user_id(填一个固定值)
(请注意,claude-fable-5不再支持使用metadata控制缓存节点)
Missing either one will cause caching to silently fail.
少了任何一个,缓存都会静默失败(不报错,但也不生效)。
How It Works / 原理
Anthropic prompt caching stores the prefix of your prompt on their servers for 5 minutes. When the next request has the same prefix, Anthropic skips re-processing it — you pay only 1/10 of the input token cost for the cached portion.
Anthropic 会把你 prompt 的前缀缓存在他们服务器上,有效期 5 分钟。下一次请求如果前缀一样,就不用重新处理了——缓存命中的部分只收 1/10 的价格。
The metadata.user_id field tells Anthropic to route requests with the same user_id to the same backend node. Without it, consecutive requests may land on different nodes, and the cache from the first request won't be found by the second.
metadata.user_id 的作用是告诉 Anthropic 把同一个 user_id 的请求路由到同一台服务器。不加这个字段,两次请求可能被分配到不同的节点,第二次根本找不到第一次创建的缓存。
Minimum Token Thresholds / 最低 Token 门槛
Caching has a minimum content size. If the cached block is too small, Anthropic silently ignores it — no error, no warning.
缓存有最低内容长度要求。如果打了 cache_control 的内容块太短,Anthropic 会直接忽略,不报错也不提示。
| Model family / 模型 | Minimum tokens / 最低 Token 数 |
|---|---|
| Opus, Haiku | 2,048 |
| Sonnet | 2,048 |
Request Example / 请求示例
{
"model": "claude-sonnet-4-5-20250929",
"system": [
{
"type": "text",
"text": "你的系统提示词(必须超过上面的 token 门槛)...",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{
"role": "user",
"content": "你好"
}
],
"metadata": {
"user_id": "任意固定字符串"
},
"max_tokens": 1024
}
metadata.user_id
Use any string that stays consistent across requests from the same user/session.
填任何一个在同一个用户/会话内保持不变的字符串就行。
Examples / 例子:
-
A user account ID / 你的用户账号 ID
-
A session/conversation ID / 对话 ID
-
Any fixed string for testing / 测试时随便填一个固定值
The value doesn't need to match a real Anthropic account. It's purely a routing hint.
这个值不需要是真的 Anthropic 账号,纯粹是一个路由提示。
cache_control
Place "cache_control": {"type": "ephemeral"} on the content blocks you want cached.
把 "cache_control": {"type": "ephemeral"} 加在你想缓存的内容块上。
Typically / 一般缓存这些:
-
System prompt — character/persona instructions that rarely change / 角色设定、人设,不怎么变的内容
-
Long user context — reference documents, history prefix / 参考文档、对话历史前缀
Content AFTER the last cache_control marker is not cached, and that's fine — it's the part that changes every turn.
最后一个 cache_control 标记之后的内容不会被缓存,这没关系——那些是每轮都会变的部分。
How to Verify / 怎么确认缓存生效了
Check the usage object in the API response:
看返回结果里的 usage 字段:
"usage": {
"input_tokens": 7,
"cache_creation_input_tokens": 6601,
"cache_read_input_tokens": 0
}
| Field / 字段 | Meaning / 含义 |
|---|---|
| cache_creation_input_tokens > 0 | Cache written / 缓存已创建(首次请求,收费 1.25 倍) |
| cache_read_input_tokens > 0 | Cache hit / 缓存命中(后续请求,收费 0.1 倍) |
| Both are 0 / 两个都是 0 | Caching not working / 缓存没生效——检查 token 门槛和 metadata.user_id |
| cache_creation > 0 every time / 每次都在创建 | Cache created but never read / 缓存建了但读不到——大概率没加 metadata.user_id,或两次请求间隔超过 5 分钟 |
Quick Test / 快速测试
First request / 第一次请求(creates cache / 创建缓存):
curl -s -X POST "https://gua.guagua.uk/v1/messages" \
-H "x-api-key: YOUR_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d "$(python3 -c "
import json
text = 'This is a stable system prompt for testing. ' * 200
body = {
'model': 'claude-sonnet-4-5-20250929',
'system': [{'type': 'text', 'text': text, 'cache_control': {'type': 'ephemeral'}}],
'messages': [{'role': 'user', 'content': 'hi'}],
'metadata': {'user_id': 'my-test-user'},
'max_tokens': 30
}
print(json.dumps(body))
")"
Second request / 第二次请求(should hit cache / 应该命中缓存——5 分钟内再跑一次同样的命令):
Same command again. Check the response:
跑同样的命令。看返回:
-
cache_creation_input_tokens: 0+cache_read_input_tokens: ~6000= cache is working / 缓存生效了 -
cache_creation_input_tokens: ~6000+cache_read_input_tokens: 0= cache NOT working / 缓存没生效
Common Pitfalls / 常见问题排查
| Symptom / 症状 | Cause / 原因 | Fix / 解决 |
|---|---|---|
| cache_creation > 0 every time, cache_read always 0 / 每次都在创建缓存,从来读不到 | Missing metadata.user_id / 没加 metadata.user_id,请求被分配到不同节点 | Add "metadata": {"user_id": "..."} / 加上这个字段 |
| cache_creation = 0, cache_read = 0 / 两个都是 0 | Content below minimum threshold / 缓存内容太短,没到最低门槛 | Make cached block longer (Sonnet: 2048+) / 增加缓存内容长度 |
| Cache works then stops / 缓存一开始有用后来失效了 | TTL expired (5 min) / 缓存过期了(有效期只有 5 分钟) | Send requests more frequently / 请求间隔不要超过 5 分钟 |
| Costs seem unchanged / 费用没变化 | Cached block is too small relative to total / 缓存的部分占总输入比例太小 | Cache more content / 把更多不变的内容放进缓存块 |
Multi-block Caching / 多块缓存
You can mark multiple blocks with cache_control. Anthropic caches the prefix up to each breakpoint.
你可以在多个内容块上加 cache_control。Anthropic 会把从头到每个标记点的前缀都缓存。
{
"system": [
{
"type": "text",
"text": "Stable instructions / 不变的系统指令...",
"cache_control": {"type": "ephemeral"}
},
{
"type": "text",
"text": "Semi-stable context / 偶尔变的上下文..."
}
],
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Long reference doc / 长参考文档...",
"cache_control": {"type": "ephemeral"}
}
]
},
{
"role": "assistant",
"content": "Previous response / AI 上一次回复..."
},
{
"role": "user",
"content": "New message (not cached) / 新消息(不缓存,每轮都变)"
}
],
"metadata": {"user_id": "user-123"}
}
The rule: everything before a cache_control marker gets cached as a prefix. Content after the last marker is processed fresh every time.
规则:每个 cache_control 标记之前的内容都会被缓存为前缀。最后一个标记之后的内容每次都重新处理。
Cost Summary / 费用总结
| Token type / 类型 | Price / 价格倍率 | Explanation / 说明 |
|---|---|---|
| Normal input / 普通输入 | 1x | No caching / 没走缓存 |
| Cache write / 缓存写入 (cache_creation) | 1.25x | First request only / 只有第一次请求会写 |
| Cache read / 缓存读取 (cache_read) | 0.1x | Subsequent requests / 后续命中的请求 |
Cache write happens once, cache read happens on every hit within the 5-minute window. For multi-turn conversations with long system prompts, savings are significant after the second message.
缓存写入只发生一次(首次请求),之后 5 分钟内每次命中都只收 0.1 倍。对于系统提示词很长的多轮对话,从第二条消息开始就能明显省钱。