Sub topic 11
Keeping the Context Window Useful
This chapter assumes you have read the earlier chapters on the context window, tool results, and the agent loop. You should be comfortable with Python and with the idea that every model call receives the whole conversation again.
Why context needs active management
A model call is stateless. The harness resends the full message list on every step. In an agent loop, that list only grows: each tool call adds an assistant message and a tool result. A single read_file on a large file, or a test run with thousands of lines of output, can use a large share of the window in one step.
A full window causes two problems:
- Hard failure. If the request exceeds the window, the API rejects it, or the oldest content is dropped.
- Soft failure. Before the window is full, quality often drops. Relevant facts sit among large amounts of irrelevant text, and the model can miss or misuse them. Cost and latency also grow with the size of every call.
The goal is not to fit as much as possible. The goal is to keep the content that helps with the next decision and leave out the rest.
Where the tokens go
Look at what a typical coding session puts in the window.
| Source | Typical size | Notes |
|---|---|---|
| System prompt and project instructions | Small to medium | Sent on every call. Fixed cost. |
| Tool definitions | Small to medium | Also sent on every call. More tools means a larger fixed cost. |
| User messages | Small | Rarely the problem. |
| Assistant messages and tool calls | Small | Short, but they accumulate over many steps. |
| Tool results | Often the largest | Whole files, search hits, command output, web pages. |
Tool results are the main target for management, because the harness controls them and they vary the most in size.
Estimating the budget
You can estimate usage cheaply. English text and code average roughly four characters per token. This is a rule of thumb, and real counts depend on the model's tokenizer.
def rough_tokens(messages):
# Crude estimate of about 4 characters per token; real counts need the model's tokenizer.
return sum(len(str(m.get("content", ""))) for m in messages) // 4
def needs_compaction(messages, window=200_000, threshold=0.8):
return rough_tokens(messages) > window * thresholdThe harness calls needs_compaction before each model call. The threshold is below 1.0 on purpose. You need headroom for the model's reply and for the next tool result, and you want to act before quality degrades. The window size of 200,000 is an example value. Use the limit of the model you actually call.
This estimate ignores the system prompt, tool definitions, and the tool_calls field. Many providers also return exact token counts in the response metadata. When they do, prefer those numbers and use the character estimate only as a fallback.
Strategy 1: Search instead of reading everything
The cheapest token is the one never loaded. A coding agent should locate code before reading it.
- Use a file-name search or directory listing to find candidate files.
- Use a text search (such as grep) to find the lines that matter.
- Read only the relevant file, or only a range of lines.
A search that returns twenty matching lines with file names and line numbers costs a few hundred tokens. Reading all twenty files could cost hundreds of thousands. The model can then read a range around a specific match.
A line-range option makes read_file far more useful for large files:
from pathlib import Path
def read_file(path, start_line=1, end_line=None, max_chars=20000):
lines = Path(path).read_text().splitlines()
end = end_line if end_line is not None else len(lines)
chunk = lines[start_line - 1:end]
numbered = [f"{start_line + i}: {line}" for i, line in enumerate(chunk)]
text = "\n".join(numbered)
if len(text) > max_chars:
text = text[:max_chars] + "\n[truncated: use start_line/end_line to read more]"
return textLine numbers in the output let the model refer to exact positions in later edits and searches.
Strategy 2: Truncate, and say that you did
Every tool should cap its output. The two tools from the toolbox chapter do this with slices: read_file keeps the first 20,000 characters, and run_command keeps the last 5,000.
Where you cut matters:
- File contents: keep the head. The start of a file usually holds imports and structure.
- Command output: keep the tail. Errors and test summaries usually appear at the end.
- Search results: keep the first N matches, and report the total count.
Silent truncation is a trap. If the model does not know output was cut, it may treat partial data as complete. It may conclude that a function does not exist because the part of the file that defines it was cut off. Always add a marker that tells the model what happened and how to get more.
def truncate(text, limit, keep="head"):
if len(text) <= limit:
return text
omitted = len(text) - limit
note = f"[{omitted} characters omitted]"
if keep == "head":
return text[:limit] + "\n" + note
return note + "\n" + text[-limit:]Strategy 3: Summarize and compact old history
Search and truncation slow the growth. Over a long session, the history still fills up. Compaction replaces old messages with a shorter summary.
A common design:
- Keep the system prompt unchanged.
- Keep the most recent messages verbatim, because the model is working with them right now.
- Ask the model (or a cheaper one) to summarize everything older.
- Replace the old messages with one message that holds the summary.
def compact(messages, call_model, keep_recent=6):
if len(messages) <= keep_recent + 1:
return messages
first = messages[0]
old = messages[1:-keep_recent]
recent = messages[-keep_recent:]
# Do not split a tool call from its result: start recent at a clean boundary.
while recent and recent[0]["role"] == "tool":
old.append(recent.pop(0))
transcript = "\n".join(f"{m['role']}: {m.get('content', '')}" for m in old)
prompt = ("Summarize this work so far for a coding agent that will continue it. "
"Include the goal, files changed, decisions made, test status, "
"and open problems.\n\n" + transcript)
summary = call_model([{"role": "user", "content": prompt}])["text"]
return [first,
{"role": "user", "content": "Summary of earlier work:\n" + summary},
*recent]The while loop handles a real constraint. Most providers require that every tool result follows the assistant message holding the matching tool call. If compaction cuts between them, the next request is rejected. Keep each call and its results together.
Compaction is lossy. The summary can drop a detail that matters later, such as the exact text of an error or a constraint the user stated early. To limit the damage:
- Ask for specific categories in the summary: goal, files touched, decisions, failing tests, user constraints.
- Keep the original user request intact outside the summary.
- Store the full transcript on disk. The agent can search it if the summary proves too thin.
Strategy 4: Clear stale tool results
A cheaper option than full summarization is to replace old tool results with a short stub. A file read from fifty steps ago is rarely needed again, and if it is, the agent can read it again. The stub, for example [tool result removed: read_file src/app.py], keeps the shape of the conversation and the record of what was done.
Strategy 5: Move work out of the window
Two more techniques keep the main context clean:
- Notes on disk. The agent writes a plan or progress file and reads it back when needed. This survives compaction and even a new session.
- Sub-agents. A separate agent with a fresh window does a noisy task, such as searching a large codebase, and returns only a short answer. The details are in the delegation chapter.
How the strategies fit together
Order the steps from least to most lossy. Truncation with a marker loses little. Clearing old results loses data that can be fetched again. Summarization loses the most, so it runs last.
Common mistakes
- Counting only the latest message. The cost is the whole list, resent each time.
- Truncating without a marker. The model treats a partial view as the full one.
- Breaking tool call and result pairs during compaction or trimming.
- Compacting too late. At 99% full, there is no room for the summary request itself.
- Dropping the system prompt when trimming old messages. It must stay.
- Loading whole directories "for context" at the start of a task.
Exercises
Exercise
A run_command tool returns the first 5,000 characters of a test run's output. The test run produces 80,000 characters, and the failure summary is at the end. What goes wrong, and what are two fixes?
Show answer
The model never sees the failure summary, so it may report that tests passed or guess at the cause. Fix 1: keep the tail of the output instead of the head, as the toolbox chapter's run_command does. Fix 2: add a marker such as "[75000 characters omitted]" so the model knows output was cut, and optionally support a filter (for example running only the failing test) to get the part it needs.
Exercise
Your harness compacts by summarizing messages[1:-6]. Right after compaction, the API rejects the request with an error about a tool result with no matching tool call. What is the likely cause, and how do you fix it?
Show answer
The cut landed between an assistant message with a tool call and its tool result, so the kept slice begins with an orphaned tool message. Fix it by moving the boundary: either include the orphaned tool messages in the part being summarized, or extend the kept slice back to include the assistant message that made the call. The compact function above does the first by popping leading tool messages from the recent slice.