LLM 中的 Prompt Caching 技术详解:以 Claude 为例的高效缓存策略 ✍ Avi Chawla🕐 2026-04-20📦 10.8 KB 🟢 已读 𝕏 文章列表 本文深入探讨了 LLM 中的 Prompt Caching 技术,解释了其背后的 KV Cache 机制及静态/动态上下文分离原理。文章通过 Claude Code 的案例分析,展示了如何通过保持 92% 的缓存命中率来将计算成本降低 81%,并总结了哈希敏感性和工程化落地的关键约束。 Prompt CachingLLMAgentClaudeKV Cache成本优化系统架构Transformer # Prompt caching in LLMs, clearly explained **作者**: Avi Chawla **日期**: 2026-04-16T06:52:15.000Z **来源**: [https://x.com/_avichawla/status/2044670188998803855](https://x.com/_avichawla/status/2044670188998803855) ---  A case study on how Claude achieves 92% cache hit-rate Every time an AI agent takes a step, it sends the entire conversation history back to the LLM. That includes the system instructions, the tool definitions, and the project context it already processed three turns ago. All of it gets re-read, re-processed, and re-billed on every single turn.  For long-running agentic workflows, this redundant computation is often the most expensive line item in your entire AI infrastructure. A system prompt with 20,000 tokens running over 50 turns means 1 million tokens of redundant computation billed at full price, producing zero new value. And that cost compounds across every user and every session. The fix is prompt caching. But to use it well, you need to understand what’s actually happening under the hood. ## Static vs. Dynamic context Before you can optimize a prompt, you need to understand what changes and what doesn’t. Every agent request has two fundamentally different parts:  - The static prefix that stays identical across turns: system instructions, tool definitions, project context, and behavioral guidelines. - The dynamic suffix that grows with every turn: user messages, assistant responses, tool outputs, and terminal observations. This split is what makes prompt caching possible. The infrastructure stores the mathematical state of the static prefix so that subsequent requests sharing that exact prefix can skip the computation entirely and read from memory. Once you internalize this, every architectural decision in this article becomes obvious. ## How does the KV Cache work? To understand why caching is so effective, you need to know what the transformer actually does when it processes your prompt. Every LLM inference request has two phases:  - The prefill phase handles the entire input prompt. It runs dense matrix multiplications across all tokens in context to build the model’s internal representation. This is compute-bound and expensive. - The decode phase generates tokens one at a time. Each new token gets added to the sequence, and the model predicts the next one. This phase is memory-bound because it mostly reads the historical state rather than doing heavy computation. During the prefill phase, the transformer computes three vectors for each token: a Query, a Key, and a Value. The attention mechanism uses these to determine how each token relates to every other token. The Key and Value vectors for any given token depend only on the tokens before it, and once computed, they never change.  Without caching, these Key and Value tensors get thrown away after every request, and the next request recomputes them from scratch. For a 20,000-token prefix, that’s 20,000 tokens worth of attention computation that didn’t need to happen again. The KV cache fixes this by persisting those tensors on the inference servers, indexed by a cryptographic hash of the token sequence. When a new request comes in with the same prefix, the hash matches, the tensors are loaded from memory, and the prefill computation for those tokens is skipped entirely. This drops computational complexity from O(n²) per generated token to O(n). And for a 20,000-token prefix repeated across 50 turns, that's an enormous reduction. ## The Economics The pricing structure is what makes this architectural decision so consequential. Cache reads cost 0.1x the base input price, which is a 90% discount on every cached token. Cache writes cost 1.25x, a 25% premium to store the KV tensors. Extended one-hour caching costs 2.0x. Here’s what this looks like across Anthropic’s Claude models:  This math only works if the cache hit rate stays high. The best production example of what that looks like is Claude Code. ## A 30-minute coding session with Claude Code Claude Code is built entirely around one objective: keep the cache hot. Here’s what a real 30-minute coding session looks like from a billing perspective. Minute 0: Claude Code loads its system prompt, tool definitions, and the project’s CLAUDE.md file. This payload exceeds 20,000 tokens, and since every token is new, this is the most expensive moment of the entire session. But you only pay this cost once. Minutes 1 to 5: You start giving instructions, and Claude Code dispatches its Explore Subagent to navigate the codebase, open files, and run grep commands. All of this gets appended to the dynamic suffix. But the 20,000-token static prefix is now reading from cache at $0.30/MTok instead of $3.00/MTok. Minutes 6 to 15: The Plan Subagent receives a summarized brief rather than the raw results, because passing raw output would bloat the dynamic suffix unnecessarily. It produces an implementation plan, you approve it, and Claude Code starts making changes. Every turn reads the static prefix from cache, the hit rate climbs past 90%, and each access resets the TTL to keep the cache warm. Minutes 16 to 25: You request changes, which means more tool calls, more terminal output, and more context accumulating in the dynamic suffix. By now the session has processed hundreds of thousands of tokens, but every single turn has read the 20,000-token foundation from cache. Minute 28: You run /cost in the terminal. Without caching, 2 million tokens at the Sonnet 4.5 rate would cost $6.00. With the cache running at 92% efficiency, 1.84 million tokens were cache reads, bringing the total cost to $1.15. That’s an 81% reduction on a single task.  This is how a hot cache looks. You have to pay for the static foundation once, and then you can read it for free. The dynamic tail is the only thing that is ever charged. ## The fragility of hash-based caching Here’s the most counterintuitive thing about prompt caching: “1 + 2 = 3” works but “2 + 1” is a cache miss. The infrastructure hashes the full token sequence from the beginning. If anything in that sequence changes, even just the order of two elements, the hash changes and the entire prefix gets recomputed at full price.  This isn’t a minor implementation detail. It’s the central constraint that every engineering decision in Claude Code is designed around. Here are real examples of what has broken caches in production: - A timestamp injected into the system prompt created a unique hash on every request. - A JSON serializer that sorted tool schema keys differently between requests invalidated the prefix. - An AgentTool whose parameters were updated mid-session wiped the entire 20,000-token cache. Three rules follow from this: Don’t modify tools during a session. The tool definitions are part of the cached prefix, so adding or removing a tool invalidates everything downstream. Never switch models mid-session. Caches are model-specific, which means switching to a cheaper model mid-conversation requires rebuilding the entire cache from scratch. Never mutate the prefix to update state. Instead of editing the system prompt, Claude Code appends a reminder tag to the next user message so that the prefix stays untouched. ## Applying this to your own Agents The same rules apply whether you’re using Claude Code or building your own agent from scratch. Structure your prompts in this order: System instructions and behavioral rules at the top. Don’t change them mid-session. Load all tool definitions upfront. Don’t add or remove them. Retrieved context and reference documents next. Keep them stable for the session duration. Conversation history and tool outputs at the bottom. This is your dynamic suffix.  With auto-caching enabled on the Anthropic API, the cache breakpoint advances automatically as the conversation grows. Without it, you’d need to manually track token boundaries, and a wrong boundary means missing the cache entirely. For context compaction when you’re approaching the context limit, use cache-safe forking. Keep the same system prompt, tools, and conversation history, then append the compaction instruction as a new message. The cached prefix gets reused, and the only new tokens billed are the compaction instruction itself.  To verify your caching is working, monitor these three fields in every API response: - cache_creation_input_tokens are the tokens written to cache. - cache_read_input_tokens are the tokens served from cache. - input_tokens are the tokens processed without caching. Your cache efficiency is cache_read_input_tokens / (cache_read_input_tokens + cache_creation_input_tokens). Track it the same way you track uptime. ## Key takeaways Prompt caching isn’t a feature you toggle on. It’s an architectural discipline you design around. The core idea is simple: structure your prompts so the static content sits at the top and the dynamic content grows at the bottom. The infrastructure hashes the prefix, stores the KV tensors, and gives you a 90% discount on every subsequent read. But the discipline is in the details. Don’t inject timestamps into system prompts, don’t shuffle tool definitions, don’t switch models mid-session, and don’t mutate anything upstream of the cache breakpoint. Claude Code demonstrates what this looks like at scale, with a 92% cache hit rate and an 81% cost reduction. If you’re building agents and not designing around prompt caching, you’re leaving most of your margin on the table. That's a wrap! If you enjoyed this tutorial: Find me → @_avichawla Every day, I share tutorials and insights on DS, ML, LLMs, and RAGs. ## 相关链接 - [Avi Chawla](https://x.com/_avichawla) - [@_avichawla](https://x.com/_avichawla) - [479K](https://x.com/_avichawla/status/2044670188998803855/analytics) - [@_avichawla](https://x.com/@_avichawla) - [Upgrade to Premium](https://x.com/i/premium_sign_up) - [2:52 PM · Apr 16, 2026](https://x.com/_avichawla/status/2044670188998803855) - [479.6K Views](https://x.com/_avichawla/status/2044670188998803855/analytics) - [View quotes](https://x.com/_avichawla/status/2044670188998803855/quotes) --- *导出时间: 2026/4/20 17:17:41*
L LLM 提示词缓存原理与实战应用 文章深入探讨了LLM中的提示词缓存技术。通过区分静态前缀(如系统指令)和动态后缀(如用户消息),利用KV Cache机制避免重复计算,大幅降低长上下文任务的成本。文章以Claude Code为例,展示了如何通过保持92%的缓存命中率将成本降低81%。同时,强调了Hash缓存的脆弱性,任何微小的前缀变动都会导致缓存失效,并给出了在开发Agent时维持缓存热度的具体工程建议。 技术 › LLM ✍ Avi Chawla🕐 2026-04-16 Prompt CachingLLMKV CacheClaudeCost OptimizationAgentEngineeringArchitecture
使 使用 Fable 5 构建自我改进 Agent 系统的 14 步指南 本文介绍如何利用 Claude Fable 5 模型构建具有复合能力的自我改进 Agent 系统。文章首先澄清了 Fable 5 作为 Mythos 级模型的定位,强调了其支持“长周期自主会话”和“自验证”的核心能力。作者指出,真正的自我改进并非模型权重的更新,而是通过 loops、dynamic workflows 和 routines 这三种原语,构建起包含记忆层和评估反馈层的环境架构。文章还详细阐述了如何根据任务复杂度在 Fable 5、Opus 和 Sonnet 之间进行成本最优的路由配置。 技术 › LLM ✍ Codez🕐 2026-06-12 LLMAgentClaudeFable 5自我改进系统架构工作流Claude Code工程化
从 从零基础到生产环境掌握人工智能代理——完整指南 这是一份关于构建生产级 AI 智能体的完整指南。文章详细阐述了智能体与聊天机器人的本质区别,涵盖了从工具设计、系统提示词、多智能体编排到生产环境部署、测试评估的全流程。重点介绍了如何利用 API 构建可靠的智能体循环,并指出了初学者常犯的错误及生产环境下的监控与成本控制策略。 技术 › Agent ✍ Khairallah AL-Awady🕐 2026-04-07 AI代理Agent系统架构Claude工具设计多智能体生产部署大模型应用开发指南LLM
搞 搞懂缓存机制,从Gemma4到Claude Code省80%Token 文章通过本地 Gemma4 实验发现大模型对话中存在 100 倍加速的现象,深入剖析了 Transformer 的 KV 缓存原理,并逆向分析了 Claude Code 的精密缓存工程。文章解释了为何连续对话比频繁开启新 Session 更省钱,指出破坏缓存的关键行为(如切换模型、修改 System Prompt),并提供了保护缓存以节省 80% Token 的具体使用姿势。 技术 › LLM ✍ 实践哥MinLi🕐 2026-04-07 Claude Code缓存机制Token优化KV Cache成本优化Transformer源码解析ClaudeGemma提效
从 从构建 Claude Code 中汲取的经验教训:提示缓存至关重要 文章详细阐述了提示缓存在构建 Claude Code 等 AI 代理中的关键作用。核心经验包括:利用前缀匹配机制规划缓存、通过消息传递更新而非修改系统提示以保持缓存、避免中途切换模型或工具、以及利用“延迟加载”和“缓存安全分叉”等技术优化上下文管理。围绕缓存设计系统架构能显著降低延迟与成本。 技术 › LLM ✍ Thariq🕐 2026-03-22 Claude Code提示缓存Agent成本优化系统架构LLM工程实践前缀匹配延迟加载
F From GPT2 to Kimi3, Explained 文章回顾了从 GPT-2 (2019) 到 KimiK3 (2026) 的大语言模型架构演进,重点对比了参数规模从 1.24 亿到 2.8 万亿的巨大跨越。深入解析了 GPT-2 的 Transformer 解码器结构、KV 缓存机制,并探讨了线性注意力机制在降低计算复杂度方面的原理与权衡。 技术 › LLM ✍ ali🕐 2026-07-28 LLMTransformerKimiK3GPT-2AttentionKV Cache架构演进线性注意力
实 实战踩坑:便宜模型执行、贵模型编排?没这么简单! 文章通过三个真实案例,验证了“贵模型编排、便宜模型执行”这一省钱策略。作者发现,虽然便宜模型在文本判定等任务上能打平顶尖模型,但在高复杂度代码和开放式视觉任务上存在局限。关键在于控制模型能力代差和任务可验证性,否则返工成本将抵消节省的 token 费用。 技术 › Agent ✍ WquGuru🕐 2026-07-28 LLMAgent模型编排成本优化Claude Code多模型协作工程实践
浪 浪费20亿Token之后,我做了一个帮自己定义目标的Skill 作者分享了一个名为Leader.skill的开源工具,旨在解决Agent交互中目标定义模糊的问题。该工具基于“目标七问”方法论,将模糊需求转化为清晰的目标任务书,支持多模型组合(如Claude规划、GPT执行),显著提升长程任务的完成率与Token利用率。 技术 › Skill ✍ 数字生命卡兹克🕐 2026-07-27 AgentGoal Engineering目标定义自动化开源LLM效率工具方法论ClaudeGPT
H How to master graph engineering 本课程教授如何构建 AI 智能体图,涵盖图的基本概念、关键模式(如菱形模式)、停止规则及人工审批环节。包含三个实战案例:深度研究台、SEO 内容生成器和市场推广套件,旨在提升业务效率并控制成本。 技术 › Agent ✍ Machina🕐 2026-07-23 AgentGraphLLMClaudeWorkflow工程化自动化架构设计效率实战
什 什么是图工程及其走红原因解析 文章解释了从“循环工程”到“图工程”的技术演进。循环是简单的单一代理执行模式,而图(由节点、边和状态组成)通过可视化的流程图处理复杂逻辑和多代理协作。文章介绍了如何使用 LangGraph 构建第一个图,并指出在逻辑变得复杂时应从循环升级到图。 技术 › Agent ✍ Alex Martin🕐 2026-07-21 Graph EngineeringLangGraphAgentLoopsLLMClaudeOpenAI教程
H Hermes Agent 大师课程:完整指南 本文是一份关于 Hermes Agent 的 12 部分系列课程汇总,涵盖了从工作流程、学习系统、技能管理到多平台集成、浏览器控制等核心功能,详细介绍了该系统的架构设计与最佳实践。 技术 › Hermes ✍ Tony Simons🕐 2026-07-20 AgentHermesLLM教程系统架构工具集成多代理自动化
如 如何使用Linear管理Agent并构建软件工厂 作者分享了使用Linear工具管理编程Agent的实战经验。他将任务按结果层级组织,利用分流箱收集问题,并通过分批处理工作流来提高效率。文章重点强调了制定清晰的Ticket契约(目标、原因、结果)、确保Agent完整完成任务以及实现无监督并行工作,从而打造个人“软件工厂”以提升生活质量。 技术 › Agent ✍ Fred Jonsson🕐 2026-07-20 LinearAgent自动化工作流软件工程编程LLM生产力Claude效率