Sub topic 10
Tools, system prompts and growing conversation history
This chapter assumes you know that a cache hit needs an identical prefix, that breakpoints mark where a cached prefix ends, and that you can read short Python snippets. Here you apply those ideas to the three parts that make up most real requests: tool definitions, the system prompt, and the message history.
The order of a request is the order of the prefix
A request is read from top to bottom. With Anthropic's Messages API the order is tools, then system prompt, then messages. A change at one level invalidates that level and every level after it.
| What you change | What stays reusable |
|---|---|
| A tool definition | Nothing after the tools |
| The system prompt | Tools only |
| An earlier message | Tools, system, and messages before the edit |
| A new final message | Everything before it |
Check your provider's documentation for its exact ordering and invalidation rules. The pattern is the same everywhere. Content that changes rarely should come first.
Tools: keep them byte-stable
Tool definitions are serialized into the prompt, so any difference in text is a different prefix. Common ways to break them:
- Building the tool list from a set or dictionary with unstable order.
- Adding or removing a tool per request, for example "only include the search tool for search questions".
- Putting dynamic values, such as a user name or today's date, inside a tool description.
Fix this by sorting tools by name, keeping one fixed list per deployment, and moving per-request facts into the final user message.
Growing history: append only
In a conversation, turn N+1 contains all of turn N plus new content. If you only append, the prefix from turn N is reusable. You get that reuse by moving the breakpoint to the end of the newest message on every call.
import copy
def build_request(tools, system_text, history):
"""Return request arguments with stable tool order and a breakpoint on the last message."""
ordered_tools = sorted(tools, key=lambda t: t["name"])
messages = copy.deepcopy(history) # keep the stored history free of markers
last = messages[-1]
if isinstance(last["content"], str):
last["content"] = [{"type": "text", "text": last["content"]}]
last["content"][-1]["cache_control"] = {"type": "ephemeral"}
return {
"model": "YOUR_MODEL_NAME",
"max_tokens": 512,
"tools": ordered_tools,
"system": [{"type": "text", "text": system_text}],
"messages": messages,
}
tools = [
{"name": "search", "description": "Search the docs.",
"input_schema": {"type": "object", "properties": {"q": {"type": "string"}}}},
{"name": "calc", "description": "Do arithmetic.",
"input_schema": {"type": "object", "properties": {"expr": {"type": "string"}}}},
]
history = [{"role": "user", "content": "What is the refund window?"}]
request = build_request(tools, "You are a support assistant.", history)
print([t["name"] for t in request["tools"]])
print(request["messages"][-1]["content"][-1]["cache_control"])On the next turn you append the assistant reply and the new user message to history and call the function again. The earlier prefix is unchanged, so it can be read from the cache. The new breakpoint then writes the extended prefix.
Check your provider's rules on how far back it looks for an earlier match. If one turn adds many content blocks, such as several tool calls and results, the old entry may fall outside that window. Placing a breakpoint on an earlier stable block as well keeps it reachable.
Edits to history break the cache
Trimming old turns to save context seems harmless. It is not. Removing or rewriting a message near the start changes the prefix from that point on, so every later token is reprocessed and billed as a write. Two patterns work better:
- Truncate rarely and in large steps, for example summarize the oldest half once, so the new prefix stays stable for many turns.
- Keep tool results exactly as received. Re-formatting or compressing an old result on a later turn is an edit.
Exercise
A chat app sends tools, a system prompt and the full history on every turn, with a breakpoint on the last message. Hit ratio is high for 20 turns, then drops to zero on turn 21. The only change is that the app dropped the first four messages to stay under a length limit. Why did the hits stop, and what is a better approach?
Show answer
Removing the first messages changed the start of the message prefix, so nothing after it matches the cached entry and the whole history is rewritten. Instead, trim rarely and in large steps, or replace the oldest turns with a summary once, so the new prefix stays stable for many later turns.