03Prompt Caching

L1P0五步章 · 技术章
Why · 为什么要学
你的 agent system prompt + tool 定义占 input 12K token,日活 1 万,每用户每天 30 次请求。光 input 成本就是月 ~$32K。开 Prompt Caching 后,这 12K 的命中价是标价的 10%——降到月 ~$3K。这不是"优化",是工程级别的成本量级切换。这一节是把生产 agent 账单从五位数降到四位数的物理基础。
1 ·核心要点

Prompt Caching 是在 inference server 层把公共前缀的 KV cache 持久化,跨请求复用。它是 #2 KV Cache 的工程产物——同样的 K/V 计算,跳过即省。

Anthropic 的 cache 价格表:

类型 TTL 命中价 写入价 最小单元
ephemeral5 分钟× 0.1× 1.251024 / 2048 token
1-hour1 小时× 0.1× 2.01024 / 2048 token

最小单元:Sonnet/Opus 1024 token,Haiku 2048 token。不到这个数不会被 cache。

Cache 边界规则:

· 只能从前往后连续命中,改中间任何字符后面全失效

· cache_control 是"在此处设 breakpoint",一个请求最多 4 个 breakpoint

· 每个 breakpoint 之间是一段 cache 块,可以独立命中

breakpoint 放置策略(从最稳定到最易变):

system → 设 breakpoint
  ↓
tools → 在最后一个 tool 设 breakpoint
  ↓
messages 的前几轮(可选)→ 设 breakpoint
  ↓
最新一轮(永远不 cache)

监控指标:每次 response 的 usage 含四个 input token 字段

· input_tokens:未 cache 部分

· cache_creation_input_tokens:本次写入 cache 的 token 数

· cache_read_input_tokens:本次从 cache 读取的 token 数

· output_tokens:输出

命中率 = read / (read + creation + uncached input)。生产 agent 这个值应 ≥ 80%。

2 ·最小代码示例
from anthropic import Anthropic
client = Anthropic()

SYSTEM = "你是一个 coding assistant..." * 200  # ≥ 1024 tokens

response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    system=[{
        "type": "text",
        "text": SYSTEM,
        "cache_control": {"type": "ephemeral"}  # ← breakpoint
    }],
    messages=[{"role": "user", "content": "hello"}]
)

print(f"creation: {response.usage.cache_creation_input_tokens}")
print(f"read:     {response.usage.cache_read_input_tokens}")
print(f"uncached: {response.usage.input_tokens}")

# 第一次跑:  creation 非零, read = 0
# 5 分钟内再跑: creation = 0, read 非零, uncached 只算 messages 增量
# 改 1 个字 SYSTEM 再跑: creation 又非零(全部重建)
3 ·工程权衡

何时该用

  1. system prompt ≥ 1024 token 且固定——agent 的标准场景
  2. tool 定义 ≥ 2KB 且不常变——单独 cache 一段
  3. 同 prompt 5 分钟内反复访问——高频 agent / chatbot
  4. 多轮对话——每轮共享 system + tools + 历史 messages