用提示词缓存降低 Claude API 费用
依据 Anthropic 官方提示词缓存文档,介绍缓存如何计价、什么时候划算,以及如何用一个顶层 cache_control 字段或显式断点开启缓存。
验证方式
- 测试环境
- 未知
- 测试日期
- 未知
- 最后更新
- 2026-11-11
如果你的请求总在重复发送同一段很长的前缀(系统提示词、工具定义、文档、不断变长的聊天记录),提示词缓存可以让 Claude 以远低于输入价的费用复用它。以下内容全部来自 Anthropic 官方文档 Prompt caching,代码照搬自该页面,我们没有实际运行过。
怎么计价
写入缓存比普通输入贵,读取缓存则便宜得多。以下为 Anthropic 价格表(美元 / 百万 token):
| 模型 | 基础输入 | 5 分钟缓存写入 | 1 小时缓存写入 | 缓存读取 | 输出 |
|---|---|---|---|---|---|
| Claude Opus 5.5 | $4 | $5 | $8 | $0.20 | $20 |
| Claude Sonnet 5.5 | $2 | $2.50 | $4 | $0.10 | $10 |
| Claude Haiku 5.5(提示词不超过 10 万 token) | $0.10 | $0.125 | $0.20 | $0.01 | $0.50 |
价格表背后的规则:5 分钟写入是基础输入价的 1.25 倍,1 小时写入是 2 倍,读取通常是 0.1 倍,而 Opus 5.5 和 Sonnet 5.5 更低,只有 0.05 倍。这些倍率可以和 Batch API 折扣、长上下文定价叠加。
什么时候划算: 在 Opus 5.5 或 Sonnet 5.5 上用 5 分钟缓存,同一段前缀发两次的费用是 1.25 + 0.05 = 1.3 倍基础价,不缓存则是 2 倍。所以第二次请求就已经省钱,之后在有效期内每命中一次,这段前缀都能省约 95%。
需要注意的限制
- 缓存默认有效 5 分钟,每次命中都会免费续期。也可以选 1 小时有效期,写入价更高。
- 短于最小长度的提示词不会被缓存,也不会报错。Opus 5.5、Sonnet 5.5 和 Haiku 5.5 的最小长度是 512 token。
- 缓存覆盖从
tools、system到messages(按此顺序)直到断点为止的全部内容。断点之前任何内容变了,都会生成新的缓存条目。
方式一:自动缓存
在请求顶层加一个 cache_control 字段。接口会把断点放在最后一个可缓存的内容块上,并随着对话变长自动后移:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
cache_control={"type": "ephemeral"},
system="You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.",
messages=[
{
"role": "user",
"content": "Analyze the major themes in 'Pride and Prejudice'.",
}
],
)
print(response.usage.model_dump_json())
需要 1 小时有效期时,改用 {"type": "ephemeral", "ttl": "1h"}。
方式二:显式断点
如果提示词结尾每次都会变(时间戳、用户的问题),自动缓存就会把断点放在这个变化的块上。这时应把 cache_control 放在最后一个保持不变的块上:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system=[
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing legal documents.",
},
{
"type": "text",
"text": "Here is the full text of a complex legal agreement: [Insert full text of a 50-page legal agreement here]",
"cache_control": {"type": "ephemeral"},
},
],
messages=[
{
"role": "user",
"content": "What are the key terms and conditions in this agreement?",
}
],
)
print(response.usage.model_dump_json())
确认缓存生效
查看响应里的 usage:
cache_creation_input_tokens:本次写入缓存的 token 数cache_read_input_tokens:从缓存读取的 token 数input_tokens:断点之后未缓存的 token 数
如果两个缓存字段都是 0,说明没有缓存,最常见的原因是前缀没达到最小长度。
想看缓存读写对不同服务商总费用的影响,可以在本站 价格 页面的缓存字段里填入对应的 token 数。
来源
- Prompt caching (Anthropic docs)platform
.claude .com(在新标签页打开) · 核对于 2026-11-11