Sub topic 10
Tools, system prompts and growing conversation history
This chapter covers how the parts of a real request (tool definitions, system prompt, and a growing message list) fit into one cached prefix. It assumes you can call an LLM API, know what tokens and context windows are, and can read short Python snippets. It also assumes you know that a cache hit needs an identical prefix, which an earlier chapter covered.
The request is one ordered sequence
Provider APIs present tools, system prompt and messages as separate fields. The model still sees them as one long sequence, and the cache matches against that sequence from the start. In Anthropic's Messages API the order is tools, then system, then messages. Other providers use their own order, so check the documentation for yours.
This order has a direct consequence. A change in an early part invalidates everything after it:
- Editing a tool definition invalidates the tools, the system prompt and all messages.
- Editing the system prompt keeps the tools reusable but invalidates the messages.
- Editing an old message invalidates that message and every message after it.
The practical rule is to order content from least to most likely to change. Tools change rarely, the system prompt changes occasionally, history grows by appending, and the newest user message is different on every call.
Tool definitions
Tool definitions are often large. A set of ten tools with detailed JSON schemas can run to several thousand tokens, so they are good caching candidates. They are also a frequent source of silent misses, for these reasons:
- Order. If you build the tools list from a set, a dictionary with unstable ordering, or a plugin registry, the same tools can arrive in a different order on each call. The text differs, so the prefix differs.
- Serialization. Two JSON objects with the same content can serialize differently if key order or whitespace differs. Most SDKs produce stable output for the same Python object, but a schema you assemble by hand or merge from several sources may not.
- Dynamic tools. Adding or removing a tool per request, for example showing only the tools a user may use, changes the prefix for every distinct tool set.
- Embedded variable text. A tool description that includes the current date, a user name or a counter changes on every call.
A defensive approach is to sort tools by name and serialize them deterministically:
import json
def stable_tools(tools):
"""Return tools in a fixed order with keys sorted inside each schema."""
ordered = sorted(tools, key=lambda t: t["name"])
# Round-trip through sorted JSON so key order cannot vary between calls.
return [json.loads(json.dumps(t, sort_keys=True)) for t in ordered]
tools_a = [
{"name": "search", "description": "Search docs", "input_schema": {"type": "object", "properties": {}}},
{"name": "lookup", "description": "Look up an order", "input_schema": {"type": "object", "properties": {}}},
]
tools_b = list(reversed(tools_a))
same = json.dumps(stable_tools(tools_a)) == json.dumps(stable_tools(tools_b))
print(same) # TrueIf you do need different tool sets for different situations, group users into a small number of fixed sets. Each set gets its own cache entry, which is far better than a different set per request.
Tool choice and other settings
Some request settings can also affect the cached prefix. With Anthropic, changes to tool_choice, to images in the prompt, or to extended thinking settings can invalidate cached message content. Treat any setting that changes how the prompt is built as part of the prefix, and check your provider's list of what invalidates a cache.
The system prompt
The system prompt should hold content that is the same for many requests: role, policy, formatting rules and reference documents. Put anything that varies per request somewhere later.
A common mistake is placing user-specific text in the system prompt, such as the user's name, account tier or the current time. Each distinct value creates a separate prefix. Instead, keep the system prompt fixed and pass the variable facts in the latest user message, or in a short block placed after the cached part.
If you have several tiers of stability, you can use more than one breakpoint (on providers that support explicit breakpoints). For example, mark the end of the policy document as one breakpoint and the end of a per-customer context block as another. When the customer context changes, the policy part can still be read from cache.
system = [
{
"type": "text",
"text": "You are a support assistant.\n" + open("policy.md").read(),
"cache_control": {"type": "ephemeral"}, # breakpoint 1: shared by all users
},
{
"type": "text",
"text": "Customer plan: premium. Region: EU.",
"cache_control": {"type": "ephemeral"}, # breakpoint 2: shared within one customer
},
]Providers limit the number of breakpoints per request. Check the current limit before designing around several.
Growing conversation history
In a chat or an agent loop, each turn sends the whole conversation again, plus one new message. Turn 1 sends A. Turn 2 sends A, B, C. Turn 3 sends A, B, C, D, E. The earlier turns are a prefix of the later request, so they are cacheable, provided you resend them unchanged.
Where this goes wrong is when the application edits history between turns:
- Trimming the oldest messages to stay within a budget moves the start of the conversation, so nothing after the trim matches the earlier prefix.
- Summarizing old turns replaces many messages with new text. The first request after the summary writes a new cache entry.
- Changing how earlier tool results are rendered, for example truncating them differently, alters text that was already cached.
- Removing or rewriting earlier assistant messages, such as stripping reasoning text, changes the prefix at that point.
The trade-off is real. You must eventually shrink history, because the context window is finite. Do it in large, infrequent steps rather than a small trim on every turn. A trim on every turn means a cache miss on every turn. A trim once every 30 turns means a miss once, and 29 hits.
Moving the breakpoint forward
With explicit breakpoints, you place a marker on the last block of the previous turn so that the whole conversation up to that point is cached. On the next turn you move it forward to the new last block. Providers typically look back a limited distance from a breakpoint for an earlier cache entry, so the earlier prefix still produces a read even though the marker moved. The exact look-back distance is provider-specific. If a conversation adds many blocks between calls, such as an agent that makes many tool calls in one turn, the write position can move out of reach of the previous entry.
This helper adds a breakpoint to the last content block of the last message:
import copy
def with_history_breakpoint(messages):
"""Return a copy of messages with a cache breakpoint on the final block."""
msgs = copy.deepcopy(messages)
last = msgs[-1]
if isinstance(last["content"], str):
last["content"] = [{"type": "text", "text": last["content"]}]
last["content"][-1]["cache_control"] = {"type": "ephemeral"}
return msgs
history = [
{"role": "user", "content": "What is your refund window?"},
{"role": "assistant", "content": "30 days from delivery."},
{"role": "user", "content": "And for gift purchases?"},
]
marked = with_history_breakpoint(history)
print(marked[-1]["content"][-1]["cache_control"]) # {'type': 'ephemeral'}Because the function copies the list, the stored history never accumulates old markers. Old markers left in place count against the breakpoint limit and can cause errors or wasted writes.
With automatic caching, the provider finds the longest matching prefix itself, so you need no markers. You still need to keep the history byte-stable.
Agent loops with tool calls
In an agent loop, one user turn can produce many model calls: the model requests a tool, you run it, you append the result, and you call again. Each call extends the previous one by an assistant message and a tool result. This is the best case for caching, since each call is the previous call plus a small suffix.
The things that break it are the same as above, with two additions:
- Non-deterministic tool results in history. If you re-render a tool result differently on the next call (a timestamp added, a different JSON key order), the prefix no longer matches. Store the exact text you sent the first time and reuse it.
- Compaction mid-loop. Clearing old tool results to save space is useful, but each clear rewrites the prefix. Clear in batches, and only when the savings clearly outweigh the cost of one cache write.
Checking that it works
Log the cache read and write counts for every call in a conversation. In a healthy multi-turn session, expect this pattern:
| Call | Cache write | Cache read | Meaning |
|---|---|---|---|
| 1 | large | 0 | Prefix stored for the first time |
| 2 | small (new turn only) | large | Earlier prefix reused, new content added |
| 3 | small | larger | Same, with the prefix growing |
| After a trim or edit | large | 0 or small | Prefix changed, so the cache was rebuilt |
If calls 2 and later show a read of 0, one of the causes above is changing the early part of the prompt. Compare the serialized request bodies of two consecutive calls and find the first position where they differ. The chapter on finding cache breakers covers this in more detail.
Exercise
An agent builds its tool list from a Python set of tool objects, then sends the tools, a fixed system prompt, and the growing message history on each call. Cache reads are 0 on every call, even though the system prompt and history are unchanged. What is the most likely cause, and what is the fix?
Show answer
Iterating a set gives no guaranteed order, so the tools can be serialized in a different order on each call. Tools come first in the prefix, so any difference there invalidates the system prompt and all messages after it. The fix is to sort the tools by a stable key such as name and serialize them deterministically before each request.
Exercise
A chat app trims the oldest message from history on every turn once the conversation passes 20 messages. Explain why this lowers the hit rate, and describe a better policy.
Show answer
Removing the oldest message changes the start of the sequence, so the new request no longer shares a prefix with the previous one, and every turn becomes a cache miss. A better policy is to let history grow until it nears a limit, then cut or summarize a large chunk at once. The cache is rebuilt once for that turn, and following turns hit again.