Skip to Content
模型用法Claude提示快取

Claude 提示快取

本頁說明如何為 Claude 開啟提示快取並確認命中。模型 ID 與介面位址請見 Claude 系列概覽。

重點Claude 的快取需要明確標記 cache_control,兩種介面都不會自動快取。

將冗長且固定的內容(系統提示詞、文件、工具定義)放在請求開頭,並在最後一個固定內容區塊上標記 cache_control。後續請求的前綴與之完全一致時,即可命中快取。

claude_cache.py
import os import anthropic client = anthropic.Anthropic(base_url="https://api.ofox.io/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)
項目說明
有效期預設 5 分鐘,命中後重新計時;"cache_control": {"type": "ephemeral", "ttl": "1h"} 為 1 小時
確認命中(原生介面)首次請求 usage.cache_creation_input_tokens 大於 0;命中時 usage.cache_read_input_tokens 大於 0
確認命中(OpenAI 相容介面)命中時 usage.prompt_tokens_details.cached_tokens 大於 0
最小長度內容過短時不會快取,兩個欄位皆為 0。各模型的最小可快取長度請見 Anthropic 官方文件 
計費寫入與讀取分別依快取寫入、快取讀取單價計費,請見模型頁 

快取的通用說明請見提示快取。

其他錯誤請見常見錯誤。

最後更新於