How the two-layer caching of Prompt Caching and Semantic Caching saves LLM costs
English text is being prepared.
Shao Meng relays content published by Samuel Wong on ByteByteGo, distinguishing two types of caching for LLM applications: Prompt Caching reuses the KV computation of a shared prefix, while Semantic Caching reuses the entire answer to semantically similar questions. The article cites Anthropic's pricing: cache reads cost about 1/10 of regular input, a 5-minute write costs 1.25x, and a 1-hour write costs 2x. It recommends stacking them in the order of exact match, semantic cache, then calling the LLM. Semantic caching requires using a labeled set to evaluate the similarity threshold, and putting order status, permissions, versions, etc. into metadata filters.
Why read this
AI score 62
The original article clearly explains the matching rules, invalidation strategies, and stacking order of the two types of caching, and provides an example of Anthropic's cache pricing.
Topics
View original postLLM Prompt Caching Versus Semantic Caching Caching LLM costs is two different problems: reuse the prefix with prompt caching, reuse the answer with semantic caching, and never confuse one for the other https://t.co/vuFGgKiIvJ
View original
LLM Prompt Caching Versus Semantic Caching Caching LLM costs is two different problems: reuse the prefix with prompt caching, reuse the answer with semantic caching, and never confuse one for the other https://t.co/vuFGgKiIvJ
Body
节约成本的两层缓存:Prompt Caching 复用前缀计算,Semantic Caching 复用整条答案
来自 @samuel_wong_ 在 @bytebytego 发布的内容,主要针对 LLM 应用里的两类缓存:Prompt Caching 复用共享前缀的 KV 计算,Semantic Caching 复用语义相近问题的整条答案。前者减输入成本,后者可能完全跳过模型调用。二者可叠加,但语义缓存的阈值、失效和适用范围要单独设计。 https://t.co/d0goDAJHuO
为什么要缓存 一次请求的费用来自输入 token 和输出 token。客服类应用里,系统指令、产品手册、历史对话往往远长于用户问题。重复出现在两类地方:同一份长文档被无数次送进模型;大量用户用不同措辞问同一件事。前者对应 Prompt Caching,后者对应 Semantic Caching。
Prompt Caching:复用输入处理 · 匹配规则是输入开头完全一致。模型先做 prefill,再做 decoding;前缀的 KV 状态可跨请求复用。 · 示例:两条请求共享「支持指令 + 产品手册」,只是问题不同。处理完第一条后,第二条可直接复用前缀的 KV。 · 共享内容必须放在前缀。因果模型里,后面的内容会改变前面文本的表示;时间戳、请求 ID 哪怕只放在开头,也会打断整段复用。 · 指令必须字面完全相同,措辞、文档顺序、请求设置都不能变。 · 费用不会归零:缓存写入通常更贵,读取更便宜。文中引用 Anthropic 的标准定价:缓存读约为普通输入的 1/10;5 分钟写为 1.25 倍,1 小时写为 2 倍。例如前缀原价 $1,则一次写 + 一次读 = $1.35,而不是 $2;读得越多越划算,从不复用则亏。 · 它主要省输入处理和首包等待时间,不省生成长答案的工作。
Semantic Caching:复用答案 · 通常做在应用层或独立服务:用嵌入模型把问题变成向量,检索相近的历史问答;命中则直接返回缓存答案,未命中再调 LLM 并可能写入。 · 命中时跳过整次 LLM 调用;未命中则多付一层嵌入与检索成本。 · 难点是相似度阈值:严则命中率低,松则可能答错。相近但不该复用的例子包括:发货前取消 vs 发货后取消;Basic 套餐 vs Pro 套餐;否定词、数字、日期、版本差异。相似度分数不等于正确概率,需要用标注集评估阈值,并同时看命中率和答案合适率。 · 不能只看问题文本。订单状态、指代、语言、权限、产品版本、对话状态都要进元数据过滤,不能指望嵌入模型从问题里自己推断。 · 失效策略:TTL(短但到期前仍可能过期)、版本号(整库失效简单但粗暴,按依赖文档选择性失效更优)、以及指令/格式/模型行为变更时的失效。Prompt cache 的失效不同:前缀一变,旧 KV 从变更点起就不能用;但应用若继续塞旧政策进 prompt,缓存本身不会发现业务规则已变。
如何一起用 推荐顺序:先精确匹配缓存 → 再语义缓存 → 未命中再走 LLM,并尽量吃到前缀缓存。需要校验源数据版本的检查应放在更前面。行动类请求(如「订阅已取消」)绝不能用缓存文案代替真实操作。
方案选型 · Prompt Caching:共享手册、稳定工具定义、长对话历史,但每个问题仍要新鲜答案。 · Semantic Caching:FAQ、稳定说明;不适合强个性化、事实变化快、或需要新鲜创意输出的场景。