kv-cache-design

kv-cache-design is a skill for Claude Code, Codex from bojieli/ai-agent-book. It costs 91 tokens per session (2,652 once invoked), scanned A, original, Apache-2.0.

A guide to arranging an AI agent's conversation so previously processed text can be reused. A KV cache stores intermediate results for earlier tokens, while a prompt cache reuses a stable beginning across requests.

In plain words
What is it for?
Use it to design stable system prompts and tool definitions, append changing information safely, preserve standard chat formatting, and investigate slow first responses or low cache hit rates.
Why use it?
It helps reduce the delay and cost caused by recalculating a long, changing conversation. It explains how small changes to early instructions, tool definitions, or message formatting can break reuse.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one.

Good fit Use it to design stable system prompts and tool definitions, append changing information safely, preserve standard chat formatting, and investigate slow first responses or low cache hit rates.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/bojieli/ai-agent-book/kv-cache-design
About the project

AI Agent: Design Principles and Engineering Practice is an open-source book that explains how AI agents combine language models, context, and tools, with accompanying experiments and code. It is intended for readers studying the principles and engineering of AI agents, from fundamentals through production use. The catalogue skills support coding-agent work related to the book's subject matter.

bojieli/ai-agent-book · 54,406 stars · on GitHub

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add bojieli/ai-agent-book --skill kv-cache-design
Clone the repo
git clone --depth 1 https://github.com/bojieli/ai-agent-book

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for kv-cache-design

README.md
[![agentmods](https://agentmods.dev/badge/skills/bojieli/ai-agent-book/kv-cache-design/github.svg)](https://agentmods.dev/skills/bojieli/ai-agent-book/kv-cache-design)
Your own site
<a href="https://agentmods.dev/skills/bojieli/ai-agent-book/kv-cache-design"><img src="https://agentmods.dev/badge/skills/bojieli/ai-agent-book/kv-cache-design/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for kv-cache-design

Your own site · 80×15
<a href="https://agentmods.dev/skills/bojieli/ai-agent-book/kv-cache-design"><img src="https://agentmods.dev/badge/skills/bojieli/ai-agent-book/kv-cache-design.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 91 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,652 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00091 $0.02652
Opus 5.5 $0.00036 $0.01061
Sonnet 5.5 $0.00018 $0.00530
Haiku 4.5 $0.00009 $0.00265

Measured 22d ago against content hash 9e44bc53c0df, method: parsed. Prices are Anthropic first-party input rates as of 2026-10-07, from the pricing page.

Security

Grade A, and why

kv-cache-design scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 22d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/kv-cache-design/SKILL.md · 93 lines

How it starts

The opening of the file, as written. The whole thing — 93 lines — stays where its author put it; the contents beside it link to each section on GitHub.

KV Cache 友好的上下文设计

KV Cache 把前文 token 的键值对(K/V)缓存下来,下一轮只计算新增部分。前提是要复用的 token 前缀保持不变——若序列从某位置开始不同,首个不同 token 及其后的 KV 状态需重新计算,此前位置不受影响。跨请求的对应机制叫 Prompt Cache。一行看似无害的动态代码,可能让整条推理链路慢一个量级。

何时使用

  • 诊断首 token 延迟(TTFT)升高、推理账单翻倍、cached_tokens 命中率低
  • 设计 Agent 的上下文布局(哪些内容进 system、哪些追加到末尾)
  • 决定子 Agent 派生方式、工具定义加载方式、会话恢复机制
  • 处理历史思维链(reasoning_content / thinking block)的回传与跨模型轨迹迁移
  • 评估「动态信息该怎么送进上下文」的任何技术方案

核心原则

  • 铁律一:系统提示词和工具定义一旦确定就不要改。 任何改动,哪怕多一个空格,都可能改变 token 序列,使首个不同 token 及其后的缓存无法复用;改动越靠前,重新计算和计费的 token 越多,延迟影响通常越大(实测可达数倍)。
  • 铁律二:动态信息永远追加到末尾。 时间戳、用户状态、TODO 进度等变化内容作为新消息追加到对话末尾,而不是修改已有的系统提示词。
  • 铁律三:使用标准 API 格式,不要自行拼接消息。 结构化消息经 Chat Template 翻译成模型训练时见过的固定 token 序列;自行拼成 USER: ... ASSISTANT: ... 的根本问题是偏离训练格式,会削弱多步思考能力。
  • Transformer 层是串联的:第 k 个 token 变化,k 之前状态不受影响,从 k 开始的表示逐层受影响——缓存只能保留到首个不同 token 之前。
  • 无缓存时 prefill 注意力计算量随上下文长度平方级增长;有缓存时省去历史 K/V 投影重算,但每个新 token 的注意力仍要遍历全部缓存 K/V(线性增长)——这是长上下文解码变慢、显存带宽成为瓶颈的原因。
  • Prompt Cache 的读取成本远低于首次计算,约为十分之一(Anthropic、DeepSeek、GPT-5 量级);各家启用方式与计费细节差异大,使用前查最新文档。
  • 缓存是架构约束,不是事后优化。 越早纳入设计,后续工程代价越小。

实践模式

1. 上下文分层布局

[ system prompt ][ tool definitions ]   静态前缀,字节级稳定,跨请求/用户/会话缓存
[ user / assistant / tool ... ]         轨迹,只追加不修改
[ 状态栏 / 新工具 schema / 动态信息 ]    追加到末尾
  • 每个运行时条件(OS 类型、当前模式、用户偏好)若放在缓存边界之前,就会把缓存键的变体数量翻倍;N 个二值条件产生 2^N 种组合(3 个条件 = 2x2x2 = 8 种缓存键)。所有动态元素放到边界之后。
  • 提示词的排列顺序首先由缓存的经济性决定,其次才是语义逻辑。
  • 按需加载的工具 schema 追加到末尾是安全的:因果注意力决定每个 token 的 KV 只依赖它之前的 token,末尾追加不改变任何已缓存 token 的 K/V;新增 schema 首次出现时计算一次(一次性写入),此后并入持续增长的前缀,后续所有轮次持续命中。

2. 三种缓存一致性设计

  • 子 Agent 字节级对齐:主 Agent 派生子 Agent 或旁路查询时,子 Agent 的提示词、工具定义、模型配置、消息前缀和思考配置必须与父 Agent 逐字节匹配,才能命中服务商 Prompt Cache。若框架故意使用不同上下文/提示词,则不要求对齐。
  • 替换字符串首次出现即冻结:大型工具输出被替换为摘要预览时,替换后的字符串持久化保存;即使会话重启,也使用完全相同的替换字符串,保证恢复后的消息序列与缓存字节流一致。
  • 思考配置与前缀一起冻结:CoT 是否回传、回传哪些字段,属于前缀的一部分,改动同样使缓存失效。

3. Chat Template 与历史思维链

  • Chat Template 是「信封格式」:API 消息是信的内容,模板规定如何用 system、user、assistant、tool 等特殊 token 划分每条消息的边界和角色。不同模型家族(Qwen、Llama、Gemma)格式不同,服务端自动转换,开发者不需要手写,但必须知道它的存在。
  • 偏离标准格式的真实代价:Qwen3 会把 <think> 内的历史思考保留下来以保证多步思考连贯,但 Chat Template 检测到新的用户查询时默认「用户换了个话题」,清理之前的思考。若工具结果被错误标记为 user 消息,就会误触发清理——相当于模型正算到一半,草稿纸被人收走了。
  • 各厂商历史思考回传策略差异极大,迁移前必查文档:
    • DeepSeek R1:剥离全部历史思考,只回传 content,不回传 reasoning_content(训练时历史 CoT 从不出现在输入里)。
    • DeepSeek V4:彻底反转——只要请求携带 tools,两个 user 消息之间的每条 assistant 消息(哪怕该轮未调用工具)都必须原样回传 reasoning_content,否则 API 直接返回 400。Kimi K2、GLM-5 采用同样协议。
    • Claude:工具调用循环中必须把带签名校验的 thinking block 原样回传;新的用户输入之后,服务端会忽略最后一次用户输入之前的 thinking block。
  • 这些差异在多轮对话里只关系省不省 token,一旦要把跑到一半的轨迹交给另一家模型接着跑,就会变成实打实的接口错误。

Read the full file on GitHub · 93 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 22d ago First seen · 93 lines · 91 tokens per session scan A 9e44bc53c0df

Subscribe to this mod's changes

kv-cache-design is a skill published in the GitHub repository bojieli/ai-agent-book (54,406 stars, last pushed 7d ago), licensed Apache-2.0. It adds 91 tokens to every session and 2,652 once invoked, about $0.0004 per session on Opus 5.5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-24.

Related

Other skills, from other repositories

code-runner

Execute Python code snippets with best-effort resource limits. Supports data analysis, visualization, and quick scripts.

fuyuxiang/echo-agent · 25 tokens

huggingface

Work with the Hugging Face Hub — search models/datasets, inspect model cards, download weights, and upload artifacts — via the huggingface-cli and the keyless public API. Token only needed for private/gated repos. Use when asked to "find a model for", "download this HF model", "search datasets", "what's on the Hub".

diillson/chatcli · 76 tokens

pi

Use when needing a minimal, extensible terminal AI coding agent harness in TypeScript with plugin architecture. Pi: minimalist terminal AI coding agent emphasizing simplicity and composability.

znlgis/opengis-skills · 35 tokens

mfs-ingest

Register, update, or re-sync data sources for MFS so they become searchable — postgres / mysql / mongo / snowflake / bigquery, github / jira / linear / notion / hubspot / zendesk, slack / discord / gmail / feishu, s3 / gdrive / web / file. Use whenever the user wants to ADD a new data source to MFS, change an existing…

zilliztech/mfs · 196 tokens

remem-mcp

Long-term memory for coding agents. Auto-applies at the start of any coding task — recall past context before answering, capture decisions/learnings/fixes after work, use CodeGraph instead of grep for symbol lookup. Invoke when you see [remem-mcp] in your context or when starting any non-trivial coding work.

tinhien11/remem-mcp · 71 tokens

setup-open-index

Install and configure Open Index as the read/write context layer for a domain-specialized agent. Use when setting up a legal, marketing, customer support, sales, infrastructure, or other domain agent with Open Index over MCP.

DrDroidLab/open-index · 48 tokens