Sub topic 1
The context window and its token budget
Prerequisites
This chapter assumes you have used a coding agent in a terminal or editor, and that you are comfortable with the command line and git. You should also know roughly what a token is: a chunk of text, often a short word or part of a word, that a language model reads and writes as a single unit. No other background is needed.
What the context window is
A language model does not remember earlier requests the way a person does. Each time the agent calls the model, it sends everything the model should know for that call, and the model produces a reply from that input alone. The context window is the maximum amount of text, measured in tokens, that the model can take in for one call. The input and the reply both count toward it.
Think of it as a fixed-size desk. Everything the agent needs to work on must fit on the desk at once. When the desk is full, something has to come off before anything new can go on.
Three consequences follow, and the rest of this tutorial builds on them:
- The window is a hard limit. The model cannot read past it.
- The window is shared. Instructions, files, command output, your messages, and the model's own replies all draw from one budget.
- The window is rebuilt on every call. A long session does not "store" history cheaply. The agent resends the accumulated conversation each turn, so a larger history costs more time and money per turn.
Tokens and the budget
A token is not a character or a word. Common English words are often one token. Rare words, identifiers, and symbols split into several. Code tends to use more tokens per line than prose, because of punctuation, indentation, and long names like parse_config_from_environment.
A rough rule for English prose is that one token is about four characters, or three-quarters of a word. Treat that as an estimate only. Different models use different tokenizers, so the same file can have a different token count in each.
The token budget is the window size minus what you have already spent. It is useful to split it into three parts:
| Part | What it covers | Who controls it |
|---|---|---|
| Fixed overhead | System prompt, tool definitions, persistent project instructions | Mostly the tool and your configuration |
| Accumulated history | Your messages, the model's replies, file contents, tool results | Grows with every turn |
| Reserved output space | Room for the model's next reply | Set by the model and tool settings |
Fixed overhead is paid before you type anything. If you connect many tools or write long instruction files, the budget available for actual work shrinks on every session, not just one.
Why the window is a budget, not a goal
It is tempting to treat a large window as permission to put everything in. Two things argue against that.
First, cost and speed. Because the history is resent each turn, a session that holds 150,000 tokens pays for processing those tokens on every call (some providers discount repeated prefixes, which a later chapter covers). Responses also tend to get slower as the input grows.
Second, quality. A model can technically accept a full window and still use it poorly. Details in the middle of a very long input are easier to overlook, and irrelevant material competes with relevant material for attention. The next chapters describe the symptoms. For now, remember that "fits in the window" and "works well in the window" are different conditions.
A worked budget example
Suppose a model has a 200,000-token window. You start a session in a medium-sized repository. The numbers below are illustrative, not measured from any particular tool.
| Item | Approximate tokens |
|---|---|
| System prompt and tool definitions | 12,000 |
| Project instruction file | 2,000 |
| Your first request | 300 |
| Reading three source files in full | 18,000 |
| First full test run output | 25,000 |
| Model replies and edits over ten turns | 20,000 |
| **Running total** | **77,300** |
After ten turns you have used about 39% of the window. The largest single items were not the conversation. They were the file reads and one unbounded test run. This is the usual pattern: tool results, not chat messages, dominate the budget.
You can check this reasoning on your own session by estimating the size of a file before you read it into the context:
# Estimate tokens for a file using the rough 4-characters-per-token rule
wc -c src/config.py | awk '{ printf "%d characters, about %d tokens\n", $1, $1 / 4 }'The result is a guess, but it is good enough to tell a 500-token file from a 20,000-token one.
The same estimate in Python, for use in a script that decides whether to read a file whole:
from pathlib import Path
def estimate_tokens(path, chars_per_token=4):
"""Return a rough token estimate for a text file."""
text = Path(path).read_text(encoding="utf-8", errors="replace")
return len(text) // chars_per_token
if __name__ == "__main__":
import sys
for name in sys.argv[1:]:
print(f"{name}: about {estimate_tokens(name)} tokens")Run it as python estimate_tokens.py src/config.py src/loader.py. If one file comes back at tens of thousands of tokens, that is a signal to read part of it instead of all of it.
How the budget changes over a session
The budget does not drain evenly. It drops in steps, each time a large file or output enters the history.
The loop on the left is the normal state of a session. The branch on the right is what the remaining chapters teach you to handle deliberately instead of by accident.
What happens when the window fills
Behavior at the limit depends on the tool. Common outcomes are:
- Automatic compaction. The tool asks the model to summarize the history and replaces the history with the summary. This keeps the session going but can drop details you needed.
- Truncation. The oldest messages are removed. Early instructions and decisions may vanish without notice.
- An error. The call is rejected because the input is too large, and you must reduce the context before continuing.
None of these is safe to rely on at the last moment. Automatic compaction in particular runs when space is scarce, so the summary is written under pressure and you have no say in what it keeps. Acting earlier, while there is still room, lets you choose what stays.
Edge cases
- Output space is reserved. A window of 200,000 tokens does not mean 200,000 tokens of input. Part of it must stay free for the reply, so usable input is somewhat smaller.
- Images and attachments cost tokens. A screenshot can use thousands of tokens. Count it like any other input.
- Tool definitions count. Each connected tool describes itself to the model in text. Many tools with long descriptions can use a large share of the window before you start.
- Resent history includes failed attempts. Dead ends, error traces, and rejected edits stay in the history and keep costing tokens unless you remove them.
- Token counts differ between models. Do not assume that a file measured for one model has the same size for another.
- Estimates drift for code. The four-characters rule is closer for prose. Minified code, long generated files, and non-English text can differ by a wide margin.
Practical habits to start with
You do not need the full routine yet. Three habits help immediately:
- Before reading a file, ask whether you need all of it. Prefer searching for the relevant lines.
- Cap the output of any command that could be long, for example with
head,tail, or a quiet flag. - Treat roughly half the window as a point to pause and decide, rather than waiting for the limit.
The half-way mark is a convention, not a rule from any vendor. Pick a threshold that suits your tool and your task, and stick to it.
Exercises
Exercise
A session uses a model with a 100,000-token window. Fixed overhead is 15,000 tokens. You have read two files of 12,000 tokens each and run one test command that printed 20,000 tokens. Ignoring chat messages, what fraction of the window is used, and which item contributed the most beyond the fixed overhead?
Show answer
Used tokens are 15,000 + 12,000 + 12,000 + 20,000 = 59,000, which is 59% of the window. Beyond the fixed overhead, the single largest item is the test output at 20,000 tokens. It is larger than either file read, and it could probably have been limited with a command such as pytest -x -q 2>&1 | tail -n 30.
Exercise
Explain why a long session gets slower and more expensive per turn even when your new messages are short.
Show answer
The agent resends the whole accumulated history to the model on every call, because the model keeps no memory between calls. A short new message is added to a large existing input, so each turn processes all of the earlier tokens again. Some providers reduce the cost of repeated prefixes, but the input is still large.
Exercise
Why is it a poor plan to let the tool compact automatically when the window is full?
Show answer
Automatic compaction runs when space is scarce and without your guidance, so the summary can leave out decisions or constraints you still need. Compacting earlier, while there is room, lets you tell the model what to keep and check the result.