Sub topic 13
Structuring prompts for caching
This chapter assumes you have read the earlier chapters on the parts of a context and on ordering content. You should be comfortable with tokens and with short Python code.
Why caching matters
Many applications send the same large block of text on every call: system rules, tool descriptions, and reference material. Processing that text costs time and money each time. Prompt caching lets a provider reuse the work it already did for text it has seen before. Cached input is usually cheaper and faster than fresh input. Exact prices, minimum sizes, and lifetimes differ by provider, so check your provider's documentation.
Caching depends on one rule: the match is by prefix. The provider compares the start of your new prompt with a prompt it processed earlier. The cache can be reused only up to the first character that differs. Everything after that point is processed again.
The stable prefix
Because only an identical prefix can be reused, order content from least to most frequently changing:
- System rules, which rarely change.
- Tool descriptions, which change when you add or remove tools.
- Reference documents, which change per task or per question.
- Recent history, which grows each turn.
- The new question, which changes every call.
def assemble_prompt(system_rules, tool_descriptions, reference_docs, recent_history, question):
# Stable content first, so a provider's prefix cache can reuse it across calls.
# Content that changes on every call goes last.
stable = [system_rules, tool_descriptions]
variable = [reference_docs, recent_history, question]
return "\n\n".join(stable + variable)This is the same ordering question you met in the placement chapter, now with a second goal. Placement asked where the model attends best. Caching asks where changes can happen without throwing away reusable work. Usually the two agree: rules first, the question last.
Common ways to break the cache
A cache hit needs byte-identical text up to the point of reuse. These mistakes quietly destroy it:
- Putting a timestamp, request ID, or user name near the top of the system prompt.
- Reordering tools or rebuilding their JSON with unstable key order.
- Editing an earlier message in the history, for example by trimming or rewriting it, instead of appending.
- Changing the model, or settings the provider includes in the cache key.
- Waiting longer than the cache lifetime between calls.
Fixing a broken prefix
Suppose your system prompt starts with the current time:
from datetime import datetime
def bad_system(rules):
return f"Current time: {datetime.now().isoformat()}\n{rules}"
def good_system(rules):
return rules # Pass the time in the final user message instead.
def build_question(question):
return f"Current time: {datetime.now().isoformat()}\n{question}"With bad_system, the first line differs on every call, so nothing after it can be reused. With good_system, the rules stay identical and the time moves to the end, where changes are cheap.
Tracking whether it works
Most providers report how many input tokens were read from the cache in each response. Log that number next to the total input tokens. A healthy long-running agent shows a high cached share after the first call. If the share drops suddenly, a recent change probably altered the prefix. Treat cache hit rate as one of the measurements you compare when you evaluate a context change, together with answer quality.
Exercise
Your agent's prompt is: tool descriptions, then a line with the current time, then system rules, then history, then the question. Cache hits are near zero. What is the cause, and how do you fix it?
Show answer
The current time sits before the system rules, so the prefix differs on every call and the rules and everything after them cannot be reused. Move the time to the end, next to the question, and put the system rules and tool descriptions first, unchanged.
Exercise
You trim the oldest message from the history on every turn to stay within budget. Why might this raise your costs, and what could you do instead?
Show answer
Removing the oldest message changes the text near the start of the history, so the cache is invalidated from that point on and most of the history is reprocessed each turn. Instead, let history grow, and trim or compact it in occasional batches so the prefix stays identical across many calls.