Search⌘ K
AI Features

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 a top_k limit 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.

One context item, four possible moves, labeled with what each would do
One context item, four possible moves, labeled with what each would do

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.

write_move.py · Python 3.14.0
import litellm
from engine_config import MODEL, SYSTEM_PROMPT
SCRATCHPAD = []
def write_scratchpad(line):
SCRATCHPAD.append(line)
def turn_messages(include_scratchpad):
user = "Continue with the checkout latency incident."
if include_scratchpad:
user += "\nChecked so far:\n" + "\n".join(SCRATCHPAD)
return [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user}]
if __name__ == "__main__":
for turn in range(1, 6):
write_scratchpad(f"turn {turn}: checked note-{turn} for the checkout rollback steps")
resent = litellm.token_counter(model=MODEL, messages=turn_messages(True))
written = litellm.token_counter(model=MODEL, messages=turn_messages(False))
print(f"turn {turn}: resend-every-turn={resent} tokens | write-to-scratchpad={written} tokens")

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. With include_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 tokens
turn 2: resend-every-turn=105 tokens | write-to-scratchpad=74 tokens
turn 3: resend-every-turn=119 tokens | write-to-scratchpad=74 tokens
turn 4: resend-every-turn=133 tokens | write-to-scratchpad=74 tokens
turn 5: resend-every-turn=147 tokens | write-to-scratchpad=74 tokens
Resending the scratchpad versus writing it to a store

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-4 shorter, but it’s still in the list, so the model can still cite it.

  • Write: Saves note-4 to 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-4 is still inside whichever call includes it.

  • Select: Decides which notes enter the call at all. If note-4 is 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.

select_move.py · Python 3.14.0
from note_store import NOTE_STORE, search_documents
QUERY = "Checkout latency spiked at 14:05. What changed, and what should we roll back?"
NOTE_STORE[3]["superseded_by"] = "note-1"
def dedup_notes(notes):
return [note for note in notes if "superseded_by" not in note]
def select_notes(query, top_k=5):
candidates = search_documents(query, top_k=len(NOTE_STORE))
return dedup_notes(candidates)[:top_k]
if __name__ == "__main__":
print("Before dedup:", [n["doc_id"] for n in search_documents(QUERY, top_k=5)])
print("After dedup: ", [n["doc_id"] for n in select_notes(QUERY)])

Here’s what the code does:

  • Line 3: We store the running question in QUERY.

  • Line 5: We tag note-4 (index 3 in NOTE_STORE) with superseded_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 a superseded_by field.

  • Lines 12–14: We define select_notes(). It ranks the whole store, removes superseded notes, and only then takes top_k, so the slot note-4 held 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']
Top five notes before and after removing superseded notes

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.

compress_move.py · Python 3.14.0
import re
import litellm
from engine_config import MODEL
from note_store import tokenize
from select_move import QUERY, select_notes
def compress_note(note, query):
sentences = re.split(r"(?<=[.!?])\s+", note["text"])
query_words = tokenize(query)
best = max(sentences, key=lambda s: len(query_words & tokenize(s)))
return {"doc_id": note["doc_id"], "text": best}
if __name__ == "__main__":
selected = select_notes(QUERY)
compressed = [compress_note(n, QUERY) for n in selected]
before = litellm.token_counter(model=MODEL, text=" ".join(n["text"] for n in selected))
after = litellm.token_counter(model=MODEL, text=" ".join(n["text"] for n in compressed))
print(f"Tokens before: {before} | after: {after}")
print("Same notes kept:", [n["doc_id"] for n in compressed])
print("note-1 now reads:", compressed[0]["text"])

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_id values, and the compressed note-1.

Running this step prints the token counts and the compressed first note:

Tokens before: 160 | after: 82
Same 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.
Token counts before and after compression

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.

isolate_move.py · Python 3.14.0
import litellm
from engine_config import MODEL
from select_move import QUERY, select_notes
def citation_check(draft, valid_ids):
prompt = (
f"Valid doc_ids: {', '.join(valid_ids)}\n"
f"Draft answer: {draft}\n"
"Reply with exactly one word: PASS if every [doc_id] in the draft "
"is in the valid list, otherwise FAIL."
)
response = litellm.completion(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
max_tokens=1024,
)
verdict = (response.choices[0].message.content or "").strip()
return verdict, response.usage.total_tokens
if __name__ == "__main__":
valid_ids = [n["doc_id"] for n in select_notes(QUERY)]
drafts = [
"First turn off the newest checkout feature flag [note-1].",
"First restart the Redis cache cluster [note-4].",
]
for draft in drafts:
verdict, spent = citation_check(draft, valid_ids)
print(f"{verdict:<5} ({spent} tokens spent in the isolated call) <- {draft}")

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 generous max_tokens leaves 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(), so note-4 is already excluded.

  • Lines 24–30: We check one draft that cites note-1 and one that cites note-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.

Python 3.14.0
def route_context(task):
if task.get("must_persist"):
return "Write", "it has to survive past this call without being resent"
if task.get("wrong_candidate"):
return "Select", "a wrong or duplicate item must never enter the call"
if task.get("needs_side_reasoning"):
return "Isolate", "its reasoning should stay out of the main thread"
if task.get("oversized"):
return "Compress", "the item is correct but larger than the next step needs"
return "Keep", "nothing about this item needs to change"

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.

route_tasks.py · Python 3.14.0
from router import route_context
TASKS = [
{"name": "checked-notes scratchpad line", "must_persist": True},
{"name": "stale duplicate note-4", "wrong_candidate": True},
{"name": "five selected notes", "oversized": True},
{"name": "citation check on the draft", "needs_side_reasoning": True},
{"name": "system prompt"},
]
for task in TASKS:
move, reason = route_context(task)
print(f"{task['name']:<32} -> {move:<8} because {reason}")

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 resent
stale duplicate note-4 -> Select because a wrong or duplicate item must never enter the call
five selected notes -> Compress because the item is correct but larger than the next step needs
citation check on the draft -> Isolate because its reasoning should stay out of the main thread
system prompt -> Keep because nothing about this item needs to change
The router’s decision for each task

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.

Compress First?

Q1. A teammate runs compress_note() on all five search results before any dedup step. The candidates still include note-4. What happens to the stale-duplicate risk?

Do you find this helpful?

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.