Claude 提示缓存
本页说明如何为 Claude 开启提示缓存并确认命中。模型 ID 与接口地址见 Claude 系列概览。
要点Claude 的缓存需要显式标记 cache_control,两种接口都不会自动缓存。
将长且固定的内容(系统提示词、文档、工具定义)放在请求开头,并在最后一个固定内容块上标记 cache_control。后续请求的前缀与之完全一致时,即可命中缓存。
Anthropic 原生接口
claude_cache.py
import os
import anthropic
client = anthropic.Anthropic(base_url="https://api.ofox.ai/anthropic", api_key=os.environ["OFOX_API_KEY"])
LONG_DOC = open("manual.txt", encoding="utf-8").read() # 一份较长的固定文档
for question in ["第 3 章讲了什么?", "总结全文要点。"]:
message = client.messages.create(
model="anthropic/claude-sonnet-4.6",
max_tokens=1024,
system=[
{"type": "text", "text": "根据下面的文档回答问题。"},
{"type": "text", "text": LONG_DOC, "cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": question}],
)
u = message.usage
print("写入:", u.cache_creation_input_tokens, "读取:", u.cache_read_input_tokens)缓存的通用说明见提示缓存。
其他报错见常见报错。
最后更新于