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)快取的通用說明請見提示快取。
其他錯誤請見常見錯誤。
最後更新於