Sub topic 11
Keeping the context window useful
This chapter assumes you know that a model call is stateless and that the harness resends the whole message list on every call. It also assumes you have seen the agent loop and the tool results it appends. Here you will learn how to keep that list from filling up with noise.
Why the window fills up
Every tool result is appended to the messages and resent on every later step. A 20,000-character file read costs about 5,000 tokens, and it keeps costing that on each following call. Three problems follow:
- Hard limit. Once the messages exceed the window, the call fails or the oldest content is dropped.
- Cost and latency. More input tokens means slower and more expensive calls.
- Quality. Old logs and irrelevant files compete with the details that matter, and the model can lose track of the task.
Estimating the budget
The harness should check the size before each model call. A rough estimate of 4 characters per token is good enough to trigger action:
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 * threshold
history = [{"role": "tool", "content": "x" * 700_000}]
print(rough_tokens(history)) # 175000
print(needs_compaction(history)) # TrueThe window size is an example value. Check your model's real limit. The 0.8 threshold leaves room for the next reply and for the tool definitions and system prompt, which also count.
Three strategies
Search instead of reading everything
Give the agent tools that find the relevant part first. A search for a function name returns a few lines with file and line numbers. The agent can then read only that range. This keeps the window small from the start, so it is the cheapest strategy.
Truncate tool output
Cap every result at a fixed length, as the read_file and run_command tools do with [:20000] and [-5000:]. Keep the end of command output, because errors and test summaries usually appear last. For long files, return a note such as "truncated, 1,840 lines total" so the model knows to ask for a specific range.
Summarize old history
When the budget check fires, replace the older messages with a short summary. Keep the original task and the most recent turns word for word. The summary should record decisions made, files changed, and what remains to do.
def compact(messages, summarize, keep_recent=6):
# summarize(messages) -> str is a placeholder for a model call.
head, tail = messages[:1], messages[1:]
if len(tail) <= keep_recent:
return messages
old, recent = tail[:-keep_recent], tail[-keep_recent:]
note = {"role": "user", "content": "Summary of earlier work:\n" + summarize(old)}
return head + [note] + recentThis version has a flaw you must handle in real code. If the cut falls between an assistant message with tool calls and its tool results, the provider may reject the list. Move the cut point so each call stays with its results.
Common errors
- Summarizing away the task. Always keep the first user message intact.
- Truncating the wrong end. Cutting the end of a test log removes the failure.
- Trusting the estimate. The 4-characters-per-token rule is poor for code and non-English text. Leave a margin.
- Compacting too late. If you wait until the call fails, there may be no room left to produce the summary.
Exercise
An agent runs the test suite and gets 300 KB of output. Which part should run_command keep when it truncates, and why?
Show answer
Keep the end (as [-5000:] does). Test runners print the failure details and the pass/fail summary last, so the tail holds the information the model needs to fix the problem. The result should also say that earlier output was cut.