Sub topic 4
Explicit Breakpoints and Automatic Caching
This chapter assumes you can call an LLM API from Python and know what tokens are. It also assumes you know that a cache hit needs an identical prompt prefix, which the previous chapter covered. Here you will see how providers decide where a cached prefix ends. There are two designs: you mark the end of the prefix yourself, or the provider decides.
Two ways to choose the cached prefix
Every caching system stores the processed form of the start of a prompt. The question is who picks how much of the start to store.
- Explicit breakpoints. You add a marker to a block of the request. The provider treats everything up to and including that block as one cacheable prefix. Anthropic's Messages API works this way, using a
cache_controlfield. - Automatic caching. You add nothing. The provider caches prefixes of long prompts on its own and reuses them when a later request starts with the same text. OpenAI's API works this way for supported models.
Both designs share the same matching rule: the stored prefix must be identical to the start of the new prompt, token for token. The difference is control. With breakpoints you choose the boundary and can see what you asked for. With automatic caching you give up that choice and don't have to change your code.
| Aspect | Explicit breakpoints | Automatic caching |
|---|---|---|
| Code change needed | Yes, add markers | No |
| Who picks the boundary | You | The provider |
| Control over what is cached | High | Low, set mostly by prompt layout |
| Risk of forgetting to opt in | Yes | No |
| Typical failure | Marker placed on content that changes | Variable text early in the prompt |
Provider behavior changes over time, including lifetimes, minimum lengths, and prices. Treat the specifics below as a model of how these systems work, and confirm numbers in the provider's current documentation.
Explicit breakpoints
In Anthropic's API you attach "cache_control": {"type": "ephemeral"} to a content block. The prompt is read in a fixed order: tools first, then the system prompt, then messages. A breakpoint on a block covers that block and everything before it in that order.
import anthropic
client = anthropic.Anthropic()
POLICY = open("policy.md").read() # must meet the model's minimum cacheable length
def ask(question):
return client.messages.create(
model="YOUR_MODEL_NAME",
max_tokens=512,
system=[
{"type": "text", "text": "You are a support assistant."},
{
"type": "text",
"text": POLICY,
"cache_control": {"type": "ephemeral"},
},
],
messages=[{"role": "user", "content": question}],
)
for q in ["Summarize the refund rules.", "What is the return window?"]:
u = ask(q).usage
print(q)
print(" written:", u.cache_creation_input_tokens)
print(" read:", u.cache_read_input_tokens)
print(" uncached input:", u.input_tokens)On the first call, the usage fields should show the policy tokens as written. On a second call within the cache lifetime, they should show up as read. The question differs between the two calls, but it comes after the breakpoint, so it does not affect the match.
What a breakpoint does
A breakpoint does two things:
- It tells the provider to store the prefix ending at that block.
- It tells the provider to look for an existing stored prefix that ends at that block.
The second point matters. On each request the provider checks the position of your breakpoint for a matching entry. If it finds none, it can also check earlier block boundaries, but only a limited distance back. For Anthropic this lookback is on the order of 20 blocks. If your conversation adds more blocks than that between requests, an older entry can be missed unless you add another breakpoint closer to the end.
Multiple breakpoints
You can place several breakpoints in one request, with a small cap per request (four for Anthropic at the time of writing). Use them when parts of the prompt change at different rates:
- Tool definitions change rarely, so they are a good first segment.
- The system prompt changes occasionally.
- Retrieved documents change per task.
- Conversation history grows every turn.
Each breakpoint creates a prefix that can be reused independently. If you edit the system prompt, the tools segment can still hit, because it sits before the edit.
import anthropic
client = anthropic.Anthropic()
tools = [
{
"name": "lookup_order",
"description": "Look up an order by id.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
# Breakpoint 1: tools are stable across all requests.
"cache_control": {"type": "ephemeral"},
}
]
system = [
{
"type": "text",
"text": "You are a support assistant. Follow the policy.",
# Breakpoint 2: the system prompt changes only on deploys.
"cache_control": {"type": "ephemeral"},
}
]
history = [
{"role": "user", "content": "Hi, I need help with an order."},
{"role": "assistant", "content": "Sure. What is the order id?"},
{
"role": "user",
"content": [
{
"type": "text",
"text": "It is A-1042. Has it shipped?",
# Breakpoint 3: caches the conversation so far.
"cache_control": {"type": "ephemeral"},
}
],
},
]
response = client.messages.create(
model="YOUR_MODEL_NAME",
max_tokens=256,
tools=tools,
system=system,
messages=history,
)
print(response.usage)On the next turn you move the third breakpoint to the newest user message. The earlier prefix is still a valid match for the new request, so it is read from cache and only the new turn is processed fresh.
Automatic caching
With automatic caching you send the same kind of request you always did. The provider hashes or otherwise matches the start of your prompt against recent requests. If a long enough prefix matches, that part is served from cache and the usage data reports it.
from openai import OpenAI
client = OpenAI()
POLICY = open("policy.md").read() # long and identical on every call
def ask(question):
return client.chat.completions.create(
model="YOUR_MODEL_NAME",
messages=[
{"role": "system", "content": POLICY},
{"role": "user", "content": question},
],
)
for q in ["Summarize the refund rules.", "What is the return window?"]:
usage = ask(q).usage
cached = usage.prompt_tokens_details.cached_tokens
print(q, "-> cached:", cached, "of", usage.prompt_tokens)Things to know about this style:
- There is no write step you control. Cached tokens appear in usage data, but you do not mark anything.
- Matching is coarse. Providers using this design typically match in fixed-size chunks above a minimum length. The reported cached count is often a round number below your true shared prefix. A shared prefix of 1,500 tokens might report fewer cached tokens than that.
- Layout is your only lever. Since you cannot place a marker, static content must come first and variable content last. Otherwise the shared prefix is short and the hit is small.
- Hits are best-effort. Even with identical prompts, a request can miss, for example when it is routed to a machine that does not hold the entry. Routing hints are covered in a later chapter.
Choosing between them
Often you do not get to choose, because the provider you use already fixed the model. When you can choose, or when you design a gateway over several providers, use these criteria:
- If you need predictable behavior and want to verify exactly what is cached, explicit breakpoints are easier to reason about.
- If you want caching with no application changes, or you have many prompt shapes, automatic caching is cheaper to adopt.
- If prompts have several segments with different change rates, multiple breakpoints let you keep partial hits after an edit. With automatic caching you rely on the single longest match.
How the lookup proceeds
Common mistakes
- Breakpoint on the wrong block. Put it on the last block that is identical across requests, not the last block of the request.
- Assuming a marker guarantees caching. If the prefix is under the model's minimum length, the marker is typically ignored without an error. Check the usage fields to confirm.
- Editing text before a breakpoint. A one-character change anywhere before the marker misses that segment and everything after it.
- Expecting automatic caching to report your exact shared length. It reports what the provider matched, which can be less.
- Mixing up the three Anthropic counters.
input_tokenscounts only the tokens after the last matched or written prefix. Total input is the sum of all three fields.
Exercise
A request has tools, a 6,000-token system prompt, and a user message. You put one breakpoint on the user message, which contains the current time. The same tools and system prompt are used on every request. Why will cache reads stay near zero, and where should you move the breakpoint?
Show answer
The breakpoint covers everything up to and including the user message, so the stored prefix includes the changing timestamp. No later request has an identical prefix, so nothing is ever read. Move the breakpoint to the last system prompt block, which is identical on every request, and keep the timestamp and question after it. Adding a breakpoint on the last tool definition would also let the tools segment hit if you later edit the system prompt.