Routing Context with Write, Select, Compress, and Isolate
Learn how to apply Write, Select, Compress, and Isolate to solve different context management problems. You will reduce repeated prompt costs, filter outdated notes, trim selected evidence, isolate citation checks, and build a router that chooses the appropriate strategy.
We'll cover the following...
In the previous lesson, we measured how much a context costs. A number alone doesn’t fix anything, though. To improve a context, we look at one piece of it at a time and decide what to do with it. There are four basic moves we can make: Write, Select, Compress, and Isolate. In this lesson, we’ll apply each move to the on-call assistant, see which problem each one solves, and then build a small router that picks the right move automatically.
What are the four moves?
Let’s take one concrete item from the on-call assistant: a scratchpad line recording that note-2 and note-3 were already checked during this incident. We could handle this line in four different ways:
Write: Save the item outside the call, in a scratchpad or long-term store, so it survives across turns without being sent on every call.
Select: Choose which items from a larger store enter the window for this call. Calling
search_documents()with atop_klimit is a Select.Compress: Shrink an item that’s already been selected, so it uses fewer tokens.
Isolate: Run part of the work in a separate call or agent. Only a short result comes back to the main conversation.
The diagram below shows all four moves applied to the same scratchpad line.
Any of the four moves can be applied to the same line, but for a given problem, only one of them is the right fix. In the rest of this lesson, we’ll work out which move fits each problem, using the note store from the previous lesson. That store still includes note-4, the outdated 2024 checkout runbook.
What does Write do?
Write moves the checked-notes line out of the prompt, which is resent on every turn, and into a store we read only when we need it.
Step 1: Compare resending with writing
The code below adds one scratchpad line per turn and counts the prompt in two ways: with the scratchpad pasted into every call, and with the scratchpad kept in a separate store.
In the code above:
Line 4: We create
SCRATCHPAD, a plain list that lives outside the message list sent to the model.Lines 7–8: We define
write_scratchpad(), which appends one line to the store.Lines 11–15: We define
turn_messages(), which builds the call. Withinclude_scratchpad=True, it pastes every scratchpad line into the user message, which is the resend-every-turn approach.Lines 19–23: We simulate five turns, write one line per turn, and count both versions of the prompt.
Running the five turns gives us this output:
turn 1: resend-every-turn=91 tokens | write-to-scratchpad=74 tokensturn 2: resend-every-turn=105 tokens | write-to-scratchpad=74 tokensturn 3: resend-every-turn=119 tokens | write-to-scratchpad=74 tokensturn 4: resend-every-turn=133 tokens | write-to-scratchpad=74 tokensturn 5: resend-every-turn=147 tokens | write-to-scratchpad=74 tokens
The written version stays at 74 tokens, while the resent version grows by 14 tokens on every turn. The history isn’t lost: it’s kept in SCRATCHPAD, and we read it back only on the turns that need it.
Note: A scratchpad holds memory for the current session. A long-term store holds memory that persists across sessions. Chapter 5 builds the long-term version, with rules for adding, updating, and deleting entries.
Write keeps information available across turns. It doesn’t help with another problem that appears as the store grows: choosing which notes to look at in the first place.
Which move removes the stale duplicate?
search_documents() already performs a Select: it picks five notes from the store. In the previous lesson, it returned note-1, note-2, note-4, note-5, and note-3. note-4 is the old 2024 runbook that says to restart the cache first, and it ranks third. Let’s check each move against it:
Compress: Makes
note-4shorter, but it’s still in the list, so the model can still cite it.Write: Saves
note-4to storage. Storage doesn’t check whether a note is outdated, so the old runbook comes back the next time we read it.Isolate: Moves some work into a separate call, but
note-4is still inside whichever call includes it.Select: Decides which notes enter the call at all. If
note-4is filtered out here, the model can’t cite it, because it never sees it.
Step 2: Filter superseded notes
We’ll give note-4 a superseded_by field that points to note-1, the runbook that replaced it. Then we’ll drop any note that has this field before taking the top five.
Here’s what the code does:
Line 3: We store the running question in
QUERY.Line 5: We tag
note-4(index 3 inNOTE_STORE) withsuperseded_by. In Chapter 4, this metadata comes from document versions instead of a hand edit.Lines 8–9: We define
dedup_notes(), which keeps only notes without asuperseded_byfield.Lines 12–14: We define
select_notes(). It ranks the whole store, removes superseded notes, and only then takestop_k, so the slotnote-4held goes to the next-best note.Lines 18–19: We print the plain top five and the deduplicated top five.
Here’s the candidate list before and after the filter:
Before dedup: ['note-1', 'note-2', 'note-4', 'note-5', 'note-3']After dedup: ['note-1', 'note-2', 'note-5', 'note-3', 'note-6']
note-4 is gone, and note-6 moved up to fill the fifth slot. An answer built from the first list could cite [note-4] and tell the engineer to restart the cache. An answer built from the second list can’t, because note-4 isn’t there. We didn’t change the system prompt at all; we only changed which notes were selected.
What does Compress do?
With the old runbook gone, the five remaining notes are the right ones. Compress solves a different problem: each note has two or three sentences, and often only one of them answers the question.
Step 3: Trim each note
compress_note() keeps the one sentence in each note that shares the most words with the question. It runs after Select, so it never changes which notes are present.
Let’s walk through the code:
Line 9: We split the note’s text into sentences at
.,!, or?followed by whitespace.Lines 10–11: We pick the sentence with the largest word overlap with the query.
Line 12: We return a compressed note that keeps the original
doc_id, so citations still work.Lines 16–19: We select the notes, compress each one, and count tokens for both versions with
token_counter(text=...).Lines 20–22: We print the token counts, the kept
doc_idvalues, and the compressednote-1.
Running this step prints the token counts and the compressed first note:
Tokens before: 160 | after: 82Same notes kept: ['note-1', 'note-2', 'note-5', 'note-3', 'note-6']note-1 now reads: If checkout latency spikes after a deploy, first turn off the newest checkout feature flag, then roll back the latest checkout deploy.
The evidence shrank by about half, and the key step in note-1, turning off the newest feature flag first, is still there. Just as important, the same five doc_id values remain. Compress changed how much each note costs, but not which notes are present.
What does Isolate do?
Before the on-call assistant trusts a draft answer, it should check that every [doc_id] the draft cites is in the selected set. This check needs its own reasoning, and that reasoning doesn’t belong in the main conversation. That’s exactly what Isolate is for.
Step 4: Isolate the citation check
This step calls a real model, so it needs your API key.
In this step’s code:
Lines 7–12: We build a short, self-contained prompt that holds only the valid IDs and the draft. Nothing from the main conversation goes in.
Lines 13–17: We send it as its own
litellm.completion()call. The generousmax_tokensleaves room for reasoning models that think before answering.Lines 18–19: We return the one-word verdict and the tokens this isolated call used.
Line 23: We build the valid ID list from
select_notes(), sonote-4is already excluded.Lines 24–30: We check one draft that cites
note-1and one that citesnote-4, and print each verdict.
We expect PASS for the draft that cites [note-1] and FAIL for the draft that cites [note-4]. The tokens the check uses stay inside its own call, and the main conversation receives only the one-word verdict. So if a draft ever cites [note-4], this check catches it without adding anything to the main context.
How do you automate the choice?
We’ve now worked through four examples by hand. A real system has to make these choices automatically, using signals it already has about each item.
Step 5: Build a context router
route_context() checks a task’s signals in a fixed order and returns the first move that applies, along with a one-line reason. We implement it the below router.py file.
Here’s how it works:
Lines 2–3: We check persistence first. An item that must survive the call goes to Write.
Lines 4–5: We check for a wrong or duplicate candidate next, which only Select can remove.
Lines 6–7: We send side reasoning that shouldn’t touch the main thread to Isolate.
Lines 8–9: We send a correct but oversized item to Compress. It comes last on purpose: Compress always lowers token counts, so checking it first would hide the other problems.
Line 10: We leave everything else as is.
Step 6: Route the four tasks
Now let’s run the router on the four tasks we solved by hand, plus one item that needs no move at all.
In the code above:
Lines 3–9: We describe each task by the one signal that matches its real problem.
Lines 11–13: We route each task and print the move and reason in aligned columns.
The router prints one decision per task:
checked-notes scratchpad line -> Write because it has to survive past this call without being resentstale duplicate note-4 -> Select because a wrong or duplicate item must never enter the callfive selected notes -> Compress because the item is correct but larger than the next step needscitation check on the draft -> Isolate because its reasoning should stay out of the main threadsystem prompt -> Keep because nothing about this item needs to change
The router makes the same decisions we made by hand. The function is short because the decision is simple once we ask the right question about each item.
Should you always compress first?
Compress always lowers the token count, so it’s tempting to run it on everything first. Let’s test that idea on two scenarios.
The two scenarios are opposites. note-4 was the wrong document, so shrinking it didn’t help. The deploy-log JSON is correct but too big, so shrinking it is the whole fix. The right move depends on what kind of problem we have.
What’s next?
In this lesson, we applied Write, Select, Compress, and Isolate to the on-call assistant, saw which problem each move solves, and built a router that picks the right move. Next, a short quiz checks this judgment on new scenarios, without any code. After that, Chapter 2 turns to full traces where a context has already gone wrong.