IamBishal

Module 2Lesson 1 of 2Hands-on

2.1 Trim at the tool boundary, clear with honest placeholders

Shrinks the window at the tool boundary with per-tool trimmers and clears finished tickets with placeholders, on the client or with clear_tool_uses on the server. On the scripted Sonnet shift trim cuts cost 26% and clear 9%, because clearing rebuilds the cache at every ticket; on a live Haiku shift clear cost more than raw while trim saved 27%. A misleading placeholder stops the copilot; wording is checked with a live run.

Lesson 2 laid the prompt out so the cached prefix survives a whole shift. This lesson makes the window smaller without undoing that work. The goal is cost. Experiment 7 found no context rot up to a 73k-token window, and its remedies changed the bill, not the answers, with one exception this lesson covers: a badly worded placeholder. So each remedy here is judged on what it saves, what it costs the cache, and whether the copilot keeps working.

The short version: shrink what the copilot carries at the tool boundary, once. If you clear results later, do it at a ticket boundary with a placeholder that says what happened, and expect to pay for a cache rebuild.

By the end you will be able to:

  • trim get_ticket and search_kb results once, as they enter the history, with copilot/trim.py
  • clear a finished ticket's tool results at the ticket boundary, on the client with a placeholder or on the server with a clear_tool_uses edit
  • read compare.py's cache writes and decide whether a clear removes enough to pay for its rebuild
  • explain why placeholder wording needs a live check, and what one measured

Before you start. You need lesson 2's stable-to-volatile layout, the cache usage fields and the cache-hit rate. The companion folder adds copilot/trim.py, the trim and clear policies in copilot/policies.py, clear_tool_uses() in copilot/model.py, compare.py, and live_placeholders.py for an optional live check.

1. Two places to shrink the window

A policy is a named strategy for what stays in the window during a shift. Lesson 1 and 2 used raw: keep everything. This lesson adds two more behind one function, build_messages(), which builds each request's messages; lesson 4 adds the rest behind the same function.

The two differ in when they shrink something, and the timing decides what they do to the cache. Caching reuses an identical prefix and stops at the first change.

Trimming shrinks a tool result before it enters the history. The model only ever sees the trimmed version, so nothing is edited later. The history stays append-only and the cached prefix only grows.

Clearing replaces tool results after the model has seen them. That changes bytes inside the prefix, so the cache is rebuilt from the cleared point on. You can't avoid that cost, but you choose how often you pay it: once per ticket, when the ticket closes, rather than once per tool call.

flowchart LR
    subgraph T["trim: at the tool boundary"]
        direction LR
        T1["tool result arrives"] --> T2["trimmer keeps the fields<br/>the copilot acts on"] --> T3["append to history"] --> T4["prefix only grows"]
    end
    subgraph C["clear: at the ticket boundary"]
        direction LR
        C1["ticket finishes"] --> C2["its tool results become<br/>placeholders, in one batch"] --> C3["prefix rebuilt once<br/>from that ticket on"] --> C4["append continues"]
    end

2. Step 1: trim at the tool boundary

Lesson 1 showed what a get_ticket result carries: the fields the copilot acts on, plus an audit trail, a customer record and SLA data. search_kb returns whole articles when the copilot only needs to pick one. copilot/trim.py keeps a trimmer per tool:

python
def _ticket(data: dict[str, Any]) -> dict[str, Any]:
    t = data["ticket"]
    return {
        "ticket": {
            "id": t["id"],
            "subject": t["subject"],
            "kind": t["kind"],
            "customer_name": t["customer_name"],
            "refund_amount": t["refund_amount"],
            "messages": [m["body"] for m in t["messages"]],
        }
    }

def _kb(data: dict[str, Any]) -> dict[str, Any]:
    return {
        "articles": [
            {"id": a["id"], "title": a["title"], "summary": a["body"].split(". ")[0] + "."}
            for a in data["articles"]
        ]
    }

TRIMMERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
    "get_ticket": _ticket,
    "search_kb": _kb,
}

def trim_result(tool: str, text: str) -> str:
    """The trimmed result, or the original when there is no trimmer or it isn't JSON."""
    trimmer = TRIMMERS.get(tool)
    if trimmer is None:
        return text
    try:
        return json.dumps(trimmer(json.loads(text)))
    except (ValueError, KeyError):
        return text

The fields that survive are the ones the copilot and the standing instructions depend on. It drafts from the subject, the kind and the message bodies, and the Corvid instruction needs customer_name and refund_amount. Drop either and the copilot can no longer keep that instruction. For articles, the id, the title and the first sentence are enough to pick one and cite it.

The fall-through matters. A missing ticket comes back as the plain string No ticket HL-9999., which isn't JSON, and a payload of an unexpected shape raises KeyError. Both pass through whole rather than ending the shift. Trimming is also lossy: a dropped field can't be recovered from the history, so if the copilot later needs it, it has to call the tool again.

In run_shift the trimmer runs in exactly one place, as each result is added:

python
out = result.tools.run(c["name"], c["input"])
if policy == "trim":
    out = trim_result(c["name"], out)  # once, at the boundary
results.append({"type": "tool_result", "tool_use_id": c["id"], "content": out})

Never trim a result that is already in the history. That edit changes bytes inside the cached prefix, raises nothing, and shows up only as cache reads falling on later requests: lesson 2's silent invalidator again.

Why trim in the client rather than make the tools return less? Anthropic's tool-writing guidance recommends filtering or truncation with sensible defaults for responses that could use a lot of context, and when you own the tool, do that. Here the tools stand in for a helpdesk and a knowledge base that usually belong to other teams, and a client-side trimmer is also a policy you can switch off and measure against raw.

3. Step 2: clear a finished ticket on the client

The runner keeps the shift as one TicketLog per ticket. When a ticket finishes, run_shift closes it, and from the next request on build_messages() sends that ticket with its tool results replaced by a placeholder:

python
def build_messages(policy: str, logs: list[TicketLog], stub: str = STUB) -> list[dict[str, Any]]:
    if policy not in POLICIES:
        raise ValueError(f"unknown policy {policy!r}")
    msgs: list[dict[str, Any]] = []
    for log in logs:
        _add_user(msgs, opening_for(log.ticket_id) if log.first else announce(log.ticket_id))
        msgs += stubbed(log, stub) if (policy == "clear" and log.closed) else log.turns
    return msgs

stubbed() replaces each tool result's content with the placeholder and keeps its tool_use_id, so every tool_use still has its matching result and the model can see what it called and with which arguments. The placeholder this tutorial uses says what happened:

python
STUB = (
    "[Result removed from the context after {ticket} was finished, to save space. "
    "You received the full result at the time and acted on it; that ticket is done "
    "and needs no more work. The call was {call}.]"
)

Batching is what keeps this affordable. Stubbing each result as soon as it had been used would break the prefix on almost every request. Closing once per ticket breaks it once and removes several results at a time: clear rarely, clear big.

close() also drops the finished ticket's thinking blocks:

python
def close(log: TicketLog) -> None:
    for m in log.turns:
        if m["role"] == "assistant":
            kept = [b for b in m["content"] if b["type"] not in ("thinking", "redacted_thinking")]
            m["content"] = kept or [{"type": "text", "text": "(done)"}]
    log.closed = True

That is safe only because this ticket's part of the window is being rebuilt anyway: clearing thinking invalidates the cache from the clearing point, so doing it at the same boundary costs no second break. Inside a live tool loop nothing is dropped; under raw and trim, close() is never called.

4. Step 3: let the API clear with clear_tool_uses

Context editing moves the same job to the API: you describe the edit, and the server applies it before the model reads the request. clear_tool_uses() in copilot/model.py builds the description:

python
def clear_tool_uses(trigger: int = 30_000, keep: int = 3, clear_at_least: int = 5_000) -> dict[str, Any]:
    return {
        "type": "clear_tool_uses_20250919",
        "trigger": {"type": "input_tokens", "value": trigger},
        "keep": {"type": "tool_uses", "value": keep},
        "clear_at_least": {"type": "input_tokens", "value": clear_at_least},
    }

trigger says when clearing starts, in input tokens; keep how many of the most recent tool uses survive; and clear_at_least the least a clear must remove before the API applies it, which is how you make each clear worth the cache rebuild. The API's own defaults are a 100,000-token trigger and keep 3. A raw shift here peaks near 24,000 tokens, so those defaults would never fire, and neither would this helper's own defaults of 30,000 and 5,000. Pass values sized for your shift, as live_server_clearing.py does with trigger=5_000. Size them from compare.py's raw row, and remember that keep counts tool uses, not tickets: set it at least to the number of calls a ticket takes, or the server can clear the ticket still in progress.

AnthropicModel sends the edit through the beta endpoint when you pass one:

python
if self.server_clearing:
    r = await self.client.beta.messages.create(
        **request,
        betas=[CONTEXT_EDITING_BETA],
        context_management={"edits": [self.server_clearing]},
    )
else:
    r = await self.client.messages.create(**request)

Your stored history is never rewritten, so your own serialization can't introduce a byte change. The cache cost is the same, though: clearing tool results invalidates cached prompt prefixes when content is cleared. And you give up two controls the client version has: the clear can land in the middle of a ticket, and the placeholder wording is the API's. test_server_side_clearing_goes_through_the_beta_endpoint checks the request shape with a stub client and no network call. To confirm the server cleared something, read the live response: response.context_management.applied_edits lists each edit it applied, and a clear_tool_uses entry reports cleared_tool_uses and cleared_input_tokens. live_server_clearing.py runs six tickets on Haiku 5.5 with trigger=5_000 and prints both, about a cent's worth:

text
request cache write cache read  applied edits
     14         191       5715
     15        5019          0  3 tool uses, 1617 tokens
     16         349       5019  3 tool uses, 1612 tokens
     20         141       6789  3 tool uses, 1622 tokens
     21        6452          0  6 tool uses, 2906 tokens
     22         313       6452  6 tool uses, 2903 tokens

The first clear removed three tool uses and the whole prompt was written to the cache again, with nothing read. The same edit is applied to every later request, so the cleared form stays stable and reads resume. When the window grows past the trigger again, a bigger clear rebuilds it once more. (The first requests in this run read from the cache because an earlier run's entries were still inside their five minutes.) On that request you should also see cache_creation_input_tokens jump, because the prefix after the cleared point is written again.

5. Verify: run compare.py and read the cache writes

bash
cd build-a-long-running-support-copilot/02-managing-the-window/03-trim-and-clear
uv run python compare.py
uv run pytest tests/test_trim_and_clear.py -q
text
policy                   mean window last window cache write        $ handled
raw                            12215       23646       24126   0.3097   24/24
trim                            6909       13240       13720   0.2296   24/24
clear                           6860       13002       35289   0.2808   24/24
clear, misleading stub          1475        2243        4125   0.0395    1/24
The tests report `8 passed`.

Read it column by column. Trim and clear both roughly halve the window. Trim also writes less to the cache, because each tail it appends is smaller; nothing is ever rewritten. Clear appends results at full size, exactly as raw does, and then rewrites everything from the closed ticket on at every ticket boundary: those rebuilds are why it writes about 1.5 times as much as raw. So trim cuts cost by 26% and clear by 9%. Experiment 7 saw the same shape with real models: clearing cut the window by about half but cost only 27% on Sonnet and 6% on Haiku, because the cache is rebuilt once per ticket.

The prices explain why. On Sonnet 5.5 a cache read costs 0.05 times the input price and a 5-minute write 1.25 times. A clear that removes R tokens from each of the N later requests saves about 0.05 × R × N in input-price units; the rebuild rewrites S tokens at about (1.25 − 0.05) × S. Clearing pays when 0.05 × R × N > 1.2 × S, so R × N has to be roughly 24 times S. Use that to size clear_at_least, not as a forecast: it ignores cache expiry and assumes every later read hits.

6. Placeholder wording, and why it needs a live check

The fourth row is the failure lesson 1 named. MISLEADING_STUB is experiment 7's pilot wording: "[cleared after {ticket} closed: {call}. Call it again if needed.]". In the pilot it made Haiku decide it had never received real data, and it took no action on 9 of 24 tickets; with a placeholder that said the result had been received and acted on, the same queue solved 23 of 24. The scripted copilot reproduces it in the extreme, stopping on every ticket after the first clearing. It reacts to a wording the same way every time, which is what makes it useful in a test and useless for judging a new wording.

So wording is checked live. live_placeholders.py runs one real clear shift on Haiku 5.5 per wording and counts re-fetches, get_ticket calls for a ticket that is already finished. Experiment 7's final wording ends "call the tool again if you need the details", which looks like an invitation to re-fetch. Measured over a full shift, it wasn't taken:

PlaceholderRe-fetches of finished ticketsCostHandled
experiment 7's final wording0$0.039224/24
this tutorial's STUB1$0.041524/24
Both wordings work on this queue; one run each can't separate them. What breaks a copilot is a placeholder that lets it believe it never had the data. Say that it had the result, acted on it, and is done.

7. On a real model, measure before you clear

The scripted shift says clearing saves a little. The live run says something else. One real Haiku 5.5 shift per policy:

PolicyMean windowCache writesCost per shift
raw19,64037,038$0.0292
trim12,22322,308$0.0213
clear17,76282,228$0.0431

Live, clear cost more than keeping everything. The real copilot writes long assistant turns, so tool results are a smaller share of its window and clearing them shrank it by only 10%, while the rebuild at every ticket boundary rewrote those long turns too: more than twice raw's cache writes. In the break-even terms above, R shrank and S grew. Trim still saved 27%. Clearing is a decision to make with your own numbers, which is what lesson 5 does.

Live on Haiku, clearing cost more than keeping everything; trimming saved 27%.

8. Common problems

Cache reads fall under trim. The trimmer is running over the history at send time. Move it to the one place a tool result is built and appended.

Clear writes far more than expected. Results are being stubbed per call instead of per ticket. Close once, at the boundary.

The copilot stops working after a clear. The placeholder reads as if it never had the data. Say it received the result and acted on it, then check the wording live.

The server never clears anything. Your window never reaches trigger, or the clear would remove less than clear_at_least, in which case the API skips it by design.

9. Exercise: write your own placeholder

STUB is a format string: stubbed() fills {ticket} with the finished ticket's id and {call} with the call it replaces, such as get_ticket(ticket_id=HL-2003). Add MY_STUB next to it in copilot/policies.py, using either field or neither, and run:

python
result = await run_shift(ShiftModel(), policy="clear", stub=MY_STUB)
print(grade(result.tools).handled)

Expected result. 24 handled, unless your wording contains the pilot's phrase "[cleared after": that is the text the scripted copilot reacts to, and it stops after the first clearing, handling 1. Try MISLEADING_STUB to see it.

Then check it live. WORDINGS in live_placeholders.py maps a label to each wording it runs. Add yours and run uv run python live_placeholders.py --cap 0.20; --cap stops the run before it spends more than that many dollars. Compare re-fetches and tickets handled with the two rows above.

Common mistake. A long, friendly placeholder. Every word is written once per cleared result and carried on every request after the clear.

10. Summary

  • Trim once, as results arrive. Nothing already in the history changes, so the prefix only grows: 26% cheaper on the scripted shift and 27% on the live one.
  • Clearing is a deliberate rebuild. Do it in one batch per ticket, with a placeholder that says the result was received and acted on, and only when the removed tokens outweigh the rewrite.
  • clear_tool_uses moves the edit to the server, not the cost. Your history stays untouched; the cached prefix is still rebuilt.
  • Judge wording and clearing live. On real Haiku, clearing cost more than raw.

Lesson 4 replaces history instead of shrinking it, with summaries, compaction, memory and starting each ticket over, behind the same build_messages().

Key Takeaways

  • Write per-tool trimmers that keep the fields the copilot acts on and let unexpected or error payloads pass through whole
  • Apply trimming once, as a result is appended, so the history stays append-only and the cached prefix only grows
  • Clear a finished ticket's tool results in one batch at the ticket boundary, so the prefix breaks once per ticket
  • Explain why trim writes less to the cache than raw while clear writes more
  • Build a clear_tool_uses edit with trigger, keep and clear_at_least sized from your own measurements
  • Use the break-even check (0.05 x R x N against 1.2 x S at Sonnet 5.5 rates) to decide whether clearing pays
  • Write a placeholder that says the result was received and acted on, and check new wordings with a live run
  • Explain why clearing cost more than raw in the live Haiku run while trimming saved 27%

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.