Topic 5 of 5 · 5 min read
Prompt caching inside agent loops
Goal: Design an agent loop's context so each turn reuses the cached prefix, and weigh the cache loss of compaction against its gains.
Design an agent's context as an append-only log with a fixed head, so each turn starts with the exact tokens of the previous turn and only the newest steps are processed fresh. Agents are where caching matters most, because their input grows with every step.
Check yourself · 1 of 3
Why are agent loops a good fit for prompt caching?
Why it matters
An agent loop sends the full context on every step: tools, instructions, the task, then each tool call and result so far. After 30 steps the input may be 50,000 tokens, but 49,000 of them are the same as in the previous step. Without caching you pay for them again each time. Teams that build agents, such as the Manus team in the references, call the cache hit rate one of the most important metrics in production.
How to do it
- Fixed head. Tools and system prompt stay unchanged for the whole run. Do not add or remove tools mid-run. If a tool must be unavailable, keep its definition and tell the model in the context or block the call in code.
- Append only. New observations and actions go at the end. Never rewrite earlier steps, reorder them or change how results are formatted.
- Deterministic format. Serialise tool calls and results the same way every time, with stable key order.
- Move the breakpoint forward. On Claude, mark the last block each turn so the next turn can read what the previous turn wrote.
- Put volatile state at the end. A running to-do list or a clock can be re-stated at the tail of the context rather than edited higher up.
- Weigh compaction. Summarising old steps or clearing old tool results frees space, but it changes the middle of the context, so everything after the edit becomes a fresh write. Compact rarely and in large steps, not a little every turn, and do it when the saved tokens exceed the cost of one rewrite.
Before and after
Weak plan: "At each step, rebuild the prompt: current date, a fresh summary of progress, and only the three most recent tool results." Every step changes the early part, so nothing is reused.
Better plan: "Fixed tools and rules. Append each action and result. At step 40, or at 80 percent of the window, compact steps 1 to 30 into one summary and accept one cache rewrite."
What goes wrong
- Dropping or editing old tool results every turn to keep the context short.
- A tool list that changes by step, such as loading tools on demand into the middle of the prompt.
- Compacting too early, so you pay a rewrite many times for small gains.
- Letting the loop idle past the TTL between steps, so the next step is a write.
Examples
A cache-friendly agent plan
Head (never changes): tools, system rules
Task: the user's goal
Log (append only): step 1 action, result; step 2 action, result; ...
Tail (restated each step): short to-do list
Compaction: at 80% of the window, replace steps 1-30 with one summary
Each step reuses everything up to the tail. The tail is small, so little is reprocessed.
Compaction trade-off
A run has 60,000 tokens of context, read at 0.30 per million. Compacting to 15,000 tokens saves 45,000 tokens on every later step, but the next step rewrites 15,000 tokens at the write price. If 20 more steps follow, the savings in size and latency usually exceed one rewrite. If 2 steps follow, they usually do not.
Key points
- Keep an agent's head fixed and its history append-only so each turn reuses the previous turn's prefix.
- Never add, remove or reorder tools mid-run. Block a tool in code rather than editing the tool list.
- Serialise tool calls and results identically every time.
- Compaction and context edits change the middle of the context, so everything after them is rewritten in the cache.
- Compact in rare, large steps and only when the saved tokens outweigh the one-time rewrite.
Common mistakes
- Rebuilding the prompt from scratch each step instead of appending to it.
- Loading and unloading tools during the run, which edits the head.
- Compacting a little every turn, so the cache never gets to reuse a long prefix.
- Leaving long gaps between steps, so the cache expires.
Check yourself · 2 of 3
An agent adds a tool to its tool list at step 12 when it needs it. What happens to the cache from step 12 onward?
Check yourself · 3 of 3
A 70,000-token agent context is compacted to 10,000 tokens, and 25 more steps are expected. How should you judge the cache cost?
Practice items, not counted towards your mastery.
Start here
- Prompt caching (Claude docs) (opens in a new tab)DocsFree
Breakpoints, cache lifetimes, what invalidates the cache and the usage fields that report reads and writes.
- Prompt caching (OpenAI API docs) (opens in a new tab)DocsFree
How automatic prefix caching works on OpenAI models, the cache key and the cached-token usage field.
- Context caching (Gemini API docs) (opens in a new tab)DocsFree
Implicit and explicit caching on Gemini, with storage-time and token-count details.
More for this topic
- Context engineering for AI agents: lessons from building Manus (opens in a new tab)ArticleFree
A production team explains why a stable prefix and append-only context matter in agent loops.