IamBishal

Module 1Lesson 2 of 2Hands-on

1.2 Lay out the prompt for the cache

This lesson orders the support copilot's request from stable to volatile, with automatic caching on: deterministic tools through stable_tools(), a frozen system prompt, then an append-only history. You run layout.py to compare six layouts by cache-hit rate and cost per shift. You add operator notes as mid-conversation system messages after a user turn. Then you write tests on the scripted model that fail when a silent invalidator breaks the cache.

A long shift is affordable only while each request starts with the same bytes as the one before it. Lesson 1 showed that the copilot re-sends the whole conversation on every request, and that the same shift cost $2.67 without prompt caching and $0.31 with it. Caching lets the API read that repeated prefix at a twentieth of the input price, but only while nothing in it moves. This lesson lays the request out so nothing does, and adds tests that fail when something starts to.

By the end you will be able to:

  • order a request from stable to volatile: tools in a fixed form, a frozen system prompt, a history you only append to
  • read the cache usage fields and compute a shift's cache-hit rate
  • add an operator note mid-shift as a role system message, in a place where it is followed and keeps the cache
  • find a silent invalidator with tests and with first_difference()

Before you start. You need lesson 1's picture of a request (tools, system prompt, a growing history of turns and tool results). The code runs on Python 3.12 with uv 0.12, and the tests need no API key. The companion folder adds copilot/prompt.py, options in run_shift for building requests in the ways real code does, layout.py and tests/test_layout.py.

1. What the API can reuse

Before a request reaches the model, the API renders it in one order: tool definitions, then the system prompt, then the messages. Prompt caching matches that rendered request as a strict prefix. It asks one question: how far from the start does this request match one it has already cached?

It reads the longest previously cached prefix that ends at a breakpoint and matches byte for byte. So a changed byte invalidates everything after it, and only an earlier write that ends before the change can still be read. With automatic caching, every cache entry ends where some earlier request ended, so a request can read only up to the end of one of those entries. A change in the newest message costs almost nothing; a change in an old message is read up to the last request that ended before it; a change in the tools or the system prompt leaves nothing to read at all.

You don't have to place breakpoints by hand. A top-level cache_control of {"type": "ephemeral"} turns on automatic caching: the API puts the breakpoint on the last cacheable block and moves it forward as the conversation grows. Each request writes its prompt, and the next one reads it. That is exactly the shape of a shift, and AnthropicModel sends it on every request:

python
r = await self.client.messages.create(
    model=self.model,
    max_tokens=self.max_tokens,
    system=system,
    messages=messages,
    tools=tools,
    cache_control={"type": "ephemeral"},
)

Sonnet 5.5 and Haiku 5.5 cache prefixes of 512 tokens or more. This copilot's tool definitions and system prompt are only 347 tokens together, and the first request, with the opening message added, is 480. That is under the minimum, so it can't be read back: the second request reads nothing. From the third request on, each one reads the one before.

flowchart LR
  subgraph S["Nothing earlier changed"]
    direction LR
    a1["tools"]:::read --> a2["system"]:::read --> a3["earlier messages"]:::read --> a4["new turn"]:::written
  end
  subgraph M["An old message changed"]
    direction LR
    m1["tools"]:::read --> m2["system"]:::read --> m3["messages up to the last request before the change"]:::read --> m4["changed message and everything after"]:::rewritten
  end
  subgraph T["Tools or system prompt changed"]
    direction LR
    b1["tools"]:::rewritten --> b2["system"]:::rewritten --> b3["earlier messages"]:::rewritten --> b4["new turn"]:::rewritten
  end
  classDef read fill:#d9f2e3,stroke:#2e7d4f,color:#1b3a2a
  classDef rewritten fill:#f6d5d5,stroke:#b03a3a,color:#4a1515
  classDef written fill:#eef0f4,stroke:#6b7280,color:#1f2937

Green is read from the cache, red is written again at the write price, grey is the new turn. The rule follows: the more often something changes, the later it belongs in the request.

2. Reading the cache in the usage fields

With caching on, input_tokens is no longer the whole input. It counts only the tokens after the last breakpoint. Two more fields account for the rest: cache_creation_input_tokens is what this request wrote to the cache, and cache_read_input_tokens is what it read from an earlier write. The prompt is the sum of all three.

text
prompt size = input_tokens + cache_creation_input_tokens + cache_read_input_tokens

The three are priced differently. On Sonnet 5.5, input is $2 per million tokens and output $10; a 5-minute cache write is $2.50 (1.25 times input) and a cache read $0.10 (0.05 times input). A write costs a quarter more than sending the tokens uncached, and one read of the same tokens saves 95% of them, so a write pays for itself after a single read.

One number sums up how well a layout uses the cache, the cache-hit rate: the share of the shift's prompt tokens served from the cache.

text
cache-hit rate = Σ cache_read_input_tokens / Σ (input_tokens + cache_creation_input_tokens + cache_read_input_tokens)

Here are the first five requests of the shift as the usage fields report them (uv run python layout.py --per-request):

text
request ticket   input cache write cache read prompt
      1 HL-2001      0         480          0    480
      2 HL-2001      0        1008          0   1008
      3 HL-2001      0         288       1008   1296
      4 HL-2001      0         106       1296   1402
      5 HL-2002      0          41       1402   1443

Request 2 reads nothing because request 1 was under the 512-token minimum. Request 3 reads all of request 2 and writes only what is new. From then on each request reads the one before. input_tokens stays 0 because automatic caching puts the breakpoint at the very end.

Sum each field over the whole shift before dividing. Even a perfect layout stays under 100% (98.1% for the stable layout below): every request writes its own new tokens once, as the table shows, and the first two requests here read nothing. Every later lesson uses this formula.

3. Run the shift six ways

layout.py plays the same scripted shift through six ways of building its requests and prices each one. It makes no live calls. The copilot is the scripted model, ShiftModel: the test double that decides each turn from what is in its window, the way lesson 1 described. Its usage is computed, not recorded: it comes from CacheSim, which works out what the API would read and write by comparing each request's bytes with earlier requests, at 4 characters per token. Nothing is recorded from a live run, so layout.py, the tests and CI run without an API key. The real API caches over tokens and blocks, does not write a prompt under the minimum, and has a lookback limit, so treat these numbers as direction and size, not as an invoice.

bash
cd build-a-long-running-support-copilot/01-foundations/02-lay-out-the-prompt-for-the-cache
uv run python layout.py
text
layout                       cache hit cache write        $
stable layout                    98.1%       24126   0.3097
clock in system prompt            0.0%     1271567   3.3037
tools in random order            24.9%      953551   2.5404
same, via stable_tools()         98.1%       24126   0.3097
note appended as message         98.1%       24151   0.3099
note edited into system          97.2%       36213   0.3388

The second row is the one to remember. Here is the whole change:

python
def system_with_clock() -> str:
    # The classic silent invalidator: "helpful" context that changes every request.
    return f"{SYSTEM_PROMPT} Current time: {datetime.now().isoformat()}."

Nothing about it looks wrong. It raises no error, every request is accepted, and the replies are the same. But the system prompt renders before every message, so a new time on each request rewrites the whole window. The hit rate falls to 0% and the shift costs more than ten times as much. That is a silent invalidator: the only place it shows is in the cache fields.

The other rows follow from the render order. Tools come first, so a tool list that arrives in a different order breaks the prefix at the very start. Passing the same tools through stable_tools() restores the stable row exactly. Editing an operator note into the system prompt costs less than a point of hit rate but writes the whole window again once, about 12,000 tokens. Appending the note as a message adds 25.

4. Step 1: freeze the tools and the system prompt

Real code builds requests in ways that move bytes without anyone noticing. A tool registry that collects tools as modules import, a dict merged from two sources or a set of enabled tools can produce the same tools in a different order, or the same schema with its keys in a different order. The meaning is unchanged; the bytes are not. stable_tools() in copilot/prompt.py removes both kinds of drift:

python
def stable_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """The same tools, always in the same order with the same key order.

    Tool lists built from a registry, a plugin scan or a set can come out in a
    different order on each request. To the cache that is a different prompt.
    """
    canonical = [json.loads(json.dumps(t, sort_keys=True)) for t in tools]
    return sorted(canonical, key=lambda t: t["name"])

sort_keys=True sorts dictionary keys at every level. It does not reorder lists inside a schema, such as required or an enum, so build those from a list, never from a set.

The system prompt is the second band. It holds the copilot's role and is fixed for the whole shift. The standing instructions are not in it: they arrive in the first user message (lesson 1). Per-request data such as the time, the queue position or the ticket belongs in a user turn, never in the system prompt.

run_shift accepts system and tools either as values or as functions it calls before every request, which is how they get built in real services and how layout.py injects the mistakes:

python
sys_text = system() if callable(system) else system
sys_text = "\n".join([sys_text, *system_notes])
tool_list = tools() if callable(tools) else tools
reply = await model.complete(system=sys_text, messages=messages, tools=tool_list)

Nothing in this code stops a caller from passing system_with_clock. The tests are the guard.

5. Step 2: append the history exactly as it came back

The messages are the band that grows. For the cache to carry the shift, every request has to start with all of the previous request's messages, unchanged, and add the new ones after them. Inside the tool loop that means append and nothing else: run_shift appends each assistant turn as it came back and each set of tool results as the next user message, and never edits an earlier one.

Trimming, summarizing or reformatting an earlier message invalidates everything after it. Reformatting is the case that slips through review: if one code path serializes SDK blocks with every field and another drops the empty ones, the same block becomes different bytes. Pick one form and use it everywhere. This tutorial uses model_dump(exclude_none=True), applied once, in AnthropicModel.complete(), as the reply comes back:

python
[b.model_dump(exclude_none=True) for b in r.content],

From there the blocks are plain dicts that are never serialized any other way. Thinking blocks stay in, in the order the model produced them. These are the only two places run_shift touches the history:

python
messages.append({"role": "assistant", "content": reply.content})
calls = reply.tool_calls()
if not calls:
    break
messages.append(
    {
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": c["id"],
                "content": result.tools.run(c["name"], c["input"]),
            }
            for c in calls
        ],
    }
)

A test shows what breaking the rule costs. ResavedHistory in tests/test_layout.py sends the same history in two forms on alternating requests, one with empty fields kept and one without, as two code paths might:

python
async def test_red_re_serializing_earlier_messages_breaks_the_prefix(stable):
    resaved = await run_shift(ResavedHistory())
    # Each request breaks the previous one's prefix; the cache can still read the
    # request two back, which used the same form, so the damage is partial: about 19%.
    assert hit_rate(resaved) < hit_rate(stable) - 0.01
    assert resaved.usd > 1.15 * stable.usd

The hit rate drops from 98.1% to 96.2% and the shift costs $0.3687 instead of $0.3097. It is less than you might expect, because the request two back was written in the same form and is still a prefix. That is exactly why this kind of bug survives review: it costs a fifth more, quietly, rather than failing.

Lessons 3 and 4 do rebuild the window, but only on purpose, at a ticket boundary, knowing each rebuild costs a cache write.

6. Step 3: operator notes as mid-conversation system messages

On HL-2013 the operator sends: "Corvid's billing review now runs until next Friday." The obvious move is to add it to the top-level system prompt. That works, and it costs the "note edited into system" row: the system prompt sits before the whole history, so the edit invalidates every message after it.

The cheaper move is to leave the system prompt alone and append the note to the conversation as a message with role: "system". Everything already cached stays a valid prefix. Sonnet 5.5 and Haiku 5.5 accept such messages; Sonnet 5 does not.

Where you put it matters. It must follow a user turn and can't be the first message. It can't sit between a tool_use and its tool_result, which is a 400. And on Sonnet 5.5 and Haiku 5.5, a system message right after a tool result can be treated as untrusted text and ignored. add_operator_note() enforces all of that by accepting only one position, right after a plain user turn:

python
def add_operator_note(messages: list[dict[str, Any]], note: str) -> None:
    if not messages:
        raise NotePlacementError("a system message cannot be the first message")
    last = messages[-1]
    blocks = last["content"] if isinstance(last["content"], list) else []
    if last["role"] != "user" or any(b.get("type") == "tool_result" for b in blocks):
        raise NotePlacementError(
            "add operator notes after a plain user turn, e.g. right after a ticket is announced"
        )
    messages.append({"role": "system", "content": f"Operator note: {note}"})

In a shift there is a natural place for that: right after a ticket is announced, before the first request for it. That is where run_shift adds notes:

python
_user(messages, opening_for(ticket["id"]) if i == 0 else announce(ticket["id"]))
if notes and ticket["id"] in notes:
    if note_mode == "message":
        add_operator_note(messages, notes[ticket["id"]])
    else:  # the mistake: grow the top-level system prompt
        system_notes.append(f"Operator note: {notes[ticket['id']]}")

Once a note is sent it is part of the prefix like any other message. To change it, append a new note that replaces it; don't edit the old one.

7. Step 4: tests that go red when the cache breaks

A silent invalidator raises nothing, and the copilot drafts the same replies. A test that checks answers will never see it, so tests/test_layout.py checks the cache instead:

python
async def test_red_a_clock_in_the_system_prompt_breaks_every_request(stable):
    clocked = await run_shift(ShiftModel(), system=system_with_clock)
    assert hit_rate(clocked) < 0.01
    assert clocked.usd > 8 * stable.usd

async def test_red_then_green_tool_order(stable):
    shuffled = await run_shift(ShiftModel(), tools=tools_from_registry)
    assert hit_rate(shuffled) < 0.5
    fixed = await run_shift(ShiftModel(), tools=lambda: stable_tools(tools_from_registry()))
    assert fixed.usd == pytest.approx(stable.usd)

async def test_an_appended_note_keeps_the_prefix_an_edited_system_prompt_does_not(stable):
    appended = await run_shift(ShiftModel(), notes=NOTE)
    edited = await run_shift(ShiftModel(), notes=NOTE, note_mode="edit_system")
    extra_appended = appended.usage.cache_write_tokens - stable.usage.cache_write_tokens
    extra_edited = edited.usage.cache_write_tokens - stable.usage.cache_write_tokens
    assert extra_appended < 50  # just the note's own tokens
    window_at_note = stable.window_at_end("HL-2012")
    assert extra_edited > window_at_note  # the whole window, written again

The test_red_ tests inject each mistake on purpose and assert its damage, so the numbers in this lesson stay true. The guard for your own code is the green test next to them:

python
async def test_green_a_stable_layout_reads_almost_everything_from_cache(stable):
    assert hit_rate(stable) > 0.95

The stable fixture runs the shift exactly as run_shift builds it by default. Put a clock into the default system prompt, where a well-meaning change would put it, and that test fails:

text
>       assert hit_rate(stable) > 0.95
E       assert 0.0 > 0.95
FAILED tests/test_layout.py::test_green_a_stable_layout_reads_almost_everything_from_cache

That is the failure CI shows you before the invoice does. test_note_placement_rules in the same file checks that add_operator_note() refuses the first position, a position after a tool result and a position after an assistant turn.

Run them from the lesson folder:

bash
uv run pytest tests -q
text
.............                                                            [100%]
14 passed

8. Finding the invalidator you didn't test for

When cache reads collapse and no test caught it, find the first byte that changed. first_difference() in copilot/prompt.py compares two rendered requests:

python
def first_difference(before: str, after: str) -> int | None:
    """Where `after` stops extending `before`: the first changed character, or None
    when `after` only appends to it (the cache can read all of `before`)."""
    for i, (a, b) in enumerate(zip(before, after, strict=False)):
        if a != b:
            return i
    return None if len(after) >= len(before) else len(after)

Render two consecutive requests with copilot.model.render_request(system, messages, tools) and pass them in. None means the second only appended to the first, which is what you want. A position means everything from there on was written again; print the text around it and the culprit is usually obvious: a timestamp, a reordered tool, a re-serialized block or an edited note.

9. Exercise: add a silent invalidator of your own

Add a layout to LAYOUTS in layout.py that numbers the requests in the system prompt, the kind of "helpful" context that creeps in:

python
from itertools import count

_requests = count(1)

def system_with_request_number() -> str:
    return f"{SYSTEM_PROMPT} This is request {next(_requests)} of the shift."

Register it as "request number in system prompt": {"system": system_with_request_number} and run layout.py. Then add a test in tests/test_layout.py, modelled on test_red_a_clock_in_the_system_prompt_breaks_every_request, that asserts the damage you measured.

Expected result. The new row reads close to 0% cache hits and costs about as much as the clock row: the system prompt changes on every request, so nothing after it can be read.

Then explain. Where would a request number belong if the copilot really needed it? (In the user turn that starts each request, after everything cached; in run_shift that means a user message, not the system prompt.)

10. Summary

The copilot's request now runs from stable to volatile: tools through stable_tools(), a system prompt that never changes during a shift, and a history that is only appended to. Operator notes go in as system messages right after a ticket is announced. A clock in the system prompt or a reordered tool list now turns a test red, and first_difference() finds the one no test anticipated.

Lesson 3 turns to the tool results themselves. Trimming a result before it enters the history leaves the cached prefix alone; clearing one the copilot has already seen rewrites the prefix on purpose, and needs a placeholder worded with care.

Key Takeaways

  • Explain the render order (tools, then the system prompt, then messages) and why one changed byte invalidates the cached prefix from that point on
  • Turn on automatic caching with a top-level cache_control of {"type": "ephemeral"} so that each request reads the prefix the previous request wrote
  • Read input_tokens, cache_creation_input_tokens and cache_read_input_tokens, and add them together to get the prompt size
  • Compute a shift's cache-hit rate by summing each usage field over every turn before dividing, instead of averaging per-turn rates
  • Make tool definitions deterministic with stable_tools(), which produces canonical JSON with sorted keys and a fixed order by name
  • Keep the system prompt frozen for the shift and put per-turn data such as timestamps in user turns
  • Append assistant content exactly as it came back, in one serialized form, and never edit earlier messages
  • Add operator notes with add_operator_note() as role system messages after a plain user turn, never after a tool result and never between a tool_use and its tool_result
  • Write tests that turn red on the clock and tool-order invalidators and that compare cache writes for an appended note against an edited note
  • Spot a silent invalidator when cache_read_input_tokens stays near zero, then find the first changed byte with first_difference() on two rendered requests
  • Explain why CacheSim's numbers show direction, not what the API bills

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.