Sub topic 3
The context window: the model's entire working memory
This chapter assumes you can read Python and JSON. It also assumes you know that a model call takes text in and returns text out, and that a conversation is sent as a list of messages with roles. The chapter covers what the context window holds and what happens as it fills. It then covers how a harness estimates and manages that fill level.
What the context window is
The context window is the maximum amount of text, measured in tokens, that the model can process in a single call. A token is a chunk of text, often a short word or part of a longer word. Code and non-English text usually split into more tokens per character than plain English prose does.
Everything the model can use for its next reply must be inside that window. The model has no other memory, because each call is stateless. If a file, an error message, or an instruction is not in the text sent on this call, the model cannot see it.
The window holds all of the following:
- The system prompt and any project instructions.
- The tool definitions, because they are sent as text the model reads.
- Every earlier user, assistant, and tool message that the harness chooses to resend.
- The reply the model is about to write.
The last item matters. Input and output share the same budget in most APIs. A window of 200,000 tokens does not mean you can send 200,000 tokens and still get a long answer. The reply must fit in what is left. Many providers also set a separate cap on output length.
The window size in this chapter is an example value. Real sizes differ by model and change over time, so check your provider's documentation.
Why a coding agent fills the window quickly
A chat with a person adds a few sentences per turn. A coding agent adds far more, because tool results are pasted back into the conversation as text. The agent loop resends the whole history on every step, so the cost of each early result is paid again at every later step.
Consider a short task:
- The agent reads a 600-line source file. That is roughly 6,000 tokens.
- It runs the test suite and gets 3,000 tokens of output.
- It reads two more files, about 12,000 tokens in total.
- It edits one file and runs the tests again, adding another 3,000 tokens.
After four steps the history holds around 24,000 tokens of tool output, before counting the system prompt and tool definitions. A twenty-step session that reads large files can pass 100,000 tokens.
Two effects follow from this growth:
- Hard limit. If the input exceeds the window, the API rejects the call or the harness must cut something.
- Rising cost and latency. Providers charge per input token, and longer inputs take longer to process. A session that resends 100,000 tokens at every step is much more expensive than one that resends 10,000.
Some providers cache a repeated prefix of the input at a lower price. That reduces cost but does not remove the window limit.
Seeing the window fill
The diagram shows how the token count grows across steps of one session. The system prompt and tool definitions form a fixed base. Each step adds assistant text and tool results.
The numbers are illustrative. The shape is the point: the curve never goes down unless the harness removes something.
Estimating tokens
A harness needs to know roughly how full the window is before each call. The exact count requires the model's own tokenizer, which is a program that splits text into the tokens that model uses. Different models use different tokenizers, so the same text yields different counts.
When an approximation is enough, the harness can use a rule of thumb. For English text and typical source code, about four characters per token is a common estimate. This is the approach in the following function.
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 * thresholdNotice what this function leaves out:
- It ignores the system prompt and the tool definitions, which count against the window.
- It reads only the
contentfield. Tool call arguments stored in a separate field are not counted. - It assumes four characters per token. Minified code, long identifiers, and non-English text can use more tokens per character than that.
The threshold of 0.8 leaves a margin for these errors and for the model's reply. A harness that cuts it close will sometimes send a request that is rejected. Many providers also return the exact input token count in each API response, and a careful harness uses that figure for the next decision in place of its own estimate.
Limits that are not just size
A larger window does not mean the model uses every part equally well. Three behaviors are common, though they vary by model.
- Dilution. When the window holds many irrelevant tool results, the useful facts are a small share of the text. The model may miss them or follow older, no-longer-relevant details.
- Position effects. Models often attend more reliably to text near the start and end of the input than to text buried in the middle.
- Stale facts. A file read at step 2 and edited at step 9 appears twice in the history, in two different versions. The model must work out which one is current, and it sometimes picks the wrong one.
So the goal is not to fill the window. The goal is to keep the text in it relevant.
Strategies for staying within budget
The next chapters on context management go deeper. Here is the overview, so you can see where each tool fits.
| Strategy | What it does | Main risk |
|---|---|---|
| Truncate output | Cut each tool result to a fixed length | The cut part may hold the answer |
| Search instead of read | Return matching lines, not whole files | A weak query finds nothing useful |
| Read ranges | Return only requested line numbers | The model must know where to look |
| Drop old results | Remove or stub out stale tool messages | The model loses details it needed |
| Summarize | Replace old history with a short summary | The summary may omit key facts |
| Delegate | Give a sub-task to a fresh context | Results come back only as a summary |
Truncation at the source
The simplest control sits inside the tools. The following tools each cut their output to a fixed length, so one result cannot fill the window.
import subprocess
from pathlib import Path
def read_file(path):
return Path(path).read_text()[:20000]
def run_command(command):
r = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
return (r.stdout + r.stderr)[-5000:]
TOOLS = {"read_file": read_file, "run_command": run_command}The two functions cut from different ends. read_file keeps the first 20,000 characters, because the start of a file usually has imports and definitions. run_command keeps the last 5,000 characters, because the end of a build or test log usually holds the failure summary. Choose the end to keep based on where the useful content tends to be.
A silent cut can mislead the model. If a file is longer than 20,000 characters, the model sees what looks like a complete file that happens to stop in the middle. A better tool says so:
def read_file(path, limit=20000):
text = Path(path).read_text()
if len(text) <= limit:
return text
return text[:limit] + f"\n[truncated: showed {limit} of {len(text)} characters]"With the marker, the model knows it can ask for a different part of the file.
Compaction
When history grows past the threshold, the harness compacts it. One common form keeps the system prompt and the most recent messages unchanged. It replaces the older middle with a summary written by a model call. The summary should record the task, decisions already made, files changed, and open problems.
Compaction has a cost. Summaries lose detail, and an error in a summary persists because the original text is gone. For this reason, many harnesses keep the full transcript on disk and only shrink what is sent to the model.
Edge cases
- A single oversized result. One tool result can exceed the entire window. Truncate at the tool, before the result enters the history, because compaction after the fact cannot help if the call is already rejected.
- Tool call and result pairs. Many APIs require every tool result to match an earlier tool call. When dropping old messages, remove a call and its result together, or the API may return an error.
- Reply space. Reserve room for the output. A window that is 99 percent full leaves almost nothing for the reply, which then cuts off mid-sentence.
- Estimate drift. Rough counts diverge from real counts as a session grows. Recalibrate against the provider's reported usage.
- Instructions pushed out. If a harness drops the oldest messages first, the original task statement can be the first thing to go. Keep the system prompt and the original task pinned.
Summary
The context window is the full input the model sees on one call. It holds instructions, tool definitions, the history, and room for the reply. Tool output is the largest source of growth, and the history is resent at every step. A harness therefore estimates the fill level, truncates results at the source, and compacts history before the limit is reached.
Exercise
An agent has a 100,000-token window and a threshold of 0.8. The system prompt and tool definitions take 6,000 tokens. The history holds 300,000 characters of messages. Using the four-characters-per-token rule, does needs_compaction (which counts only message content) return True? What is the more accurate view once the fixed text is included?
Show answer
The history is about 300,000 / 4 = 75,000 tokens. The threshold is 100,000 × 0.8 = 80,000, so 75,000 is not above it and the function returns False. Counting the 6,000 fixed tokens gives about 81,000, which is over the 80,000 threshold. The function misses the need to compact because it leaves out the system prompt and tool definitions.
Exercise
Why does run_command keep the last 5,000 characters of output while read_file keeps the first 20,000? What is one problem with cutting without telling the model?
Show answer
A command log usually ends with the failure summary or final result, so the tail is the most useful part. A file usually has its imports and main definitions near the top. A silent cut makes the output look complete, so the model may reason about a partial file as if it were the whole file. A truncation marker tells the model that more exists and lets it request another part.