Sub topic 2
The Context Window as a Shared Budget
What this chapter assumes
You can read short Python programs, you have used an AI coding agent, and you know that a large language model reads and writes tokens. The previous chapter covered what a token is and why counts differ between models. This chapter covers the limit on how many tokens a model can handle at once, and what shares that limit.
What the context window is
The context window is the maximum number of tokens a model can work with in one request. The model sees only what is inside the window. It has no memory of anything outside it. If the agent needs the model to know something, that text must be in the window on that turn.
Providers publish the window size for each model. Sizes range from tens of thousands to over a million tokens, and they change as models are released. This chapter uses placeholder numbers. Take real values from your provider's documentation.
A bigger window does not mean you should fill it. The window sets what is possible. The price and the quality of the answer depend on how much you actually put in it.
Everything draws from one pool
Most people think of the window as "the conversation". In a coding agent, many things share it:
- System prompt. The agent's instructions, rules, and project guidance files. This is sent on every request.
- Tool definitions. The name, description, and parameter schema of every tool the agent can call. Each tool you enable adds tokens, even if the model never calls it.
- Conversation history. Your messages, the model's earlier replies, and its earlier tool calls.
- Tool results. File contents, search output, test logs, and command output. In a coding agent these are usually the largest part of the history.
- Reserved output. Room for the reply the model is about to write.
- Reasoning tokens. If the model "thinks" before answering, those tokens usually count as output and use the same room.
The first four items are input. The last two are output. Together, input and output must fit inside the window.
The numbers in the chart are in thousands of tokens. This turn has only 24,000 tokens free. That is the most any new tool result can use before something has to give.
Computing the remaining budget
You can reason about the window with simple arithmetic. The function below subtracts the known parts from the window, then checks whether a new piece of text fits.
def remaining(window, parts, reserved_output):
"""Tokens still free in the window for new input."""
return window - sum(parts.values()) - reserved_output
def fits(new_tokens, free_tokens):
return new_tokens <= free_tokens
# Placeholder sizes, not real model limits.
parts = {
"system_prompt": 4_000,
"tool_definitions": 6_000,
"history": 150_000,
}
free = remaining(200_000, parts, reserved_output=16_000)
print(free) # 24000
print(fits(30_000, free)) # False: a 30k-token file read does not fit
print(fits(8_000, free)) # TrueTwo details matter here. The first is that reserved_output is part of the budget even though the model has not written it yet. If you fill the window to the brim with input, the model has no room to answer. The second is that the system prompt and tool definitions are paid for before the work starts. A setup with 10,000 tokens of fixed overhead on a 200,000-token window has already used 5% of the pool on every turn.
Input limit, output limit and window size
Three numbers are easy to confuse.
| Number | What it limits | Typical behavior |
|---|---|---|
| Context window | Input plus output in one request | The request is rejected, or older content is dropped, when exceeded |
| Maximum output tokens | The length of one reply | The reply is cut off mid-sentence when exceeded |
| Your own output cap (for example a `max_tokens` setting) | The reply length you allow | The same cut-off, at a lower value than the model maximum |
The maximum output is usually much smaller than the window. A model with a 200,000-token window may allow only a few tens of thousands of tokens in one reply. Providers differ on how they count reasoning tokens against these limits, so read your provider's documentation before you rely on a number.
A reply that hits the output cap is a common failure when an agent writes a large file in one tool call. The text stops partway, the tool call is malformed, and the agent has to retry. The retry costs another full turn.
A rough way to estimate size
You often need a quick token estimate before reading a file. English text and source code average roughly three to four characters per token, but the exact count depends on the tokenizer and the content. Minified code, long identifiers, and non-English text can tokenize much worse.
def rough_tokens(text, chars_per_token=3.5):
"""Rough estimate only. Use the provider's token counter for real numbers."""
return int(len(text) / chars_per_token) + 1
source = "def add(a, b):\n return a + b\n"
print(rough_tokens(source)) # 10Use an estimate to decide whether to read a whole file or just part of it. Do not use it for billing. For billing, use the counts the API reports back, which a later chapter covers.
What happens when the window fills
A coding agent that runs long enough will approach the limit. There are three common outcomes, and which one you get depends on the agent.
- The request fails. The API returns an error saying the prompt is too long. The agent stops or has to recover.
- Old content is dropped. The agent removes the oldest messages. The model then loses early instructions or decisions, and it may redo work or contradict itself.
- The history is compacted. The agent asks a model to summarize earlier turns and replaces them with the summary. This keeps the thread alive but loses detail, and the summarizing call itself costs tokens.
None of these is free. The best fix is to not fill the window in the first place, which a later chapter on context management covers.
Why the budget is also a cost
The window is a size limit, but every token in it is also something you pay for. Each turn of an agent loop sends the whole context as input. A context that holds 150,000 tokens of history is billed as 150,000 input tokens on that turn, and again on the next turn, with a little more added. The next chapters cover how input and output tokens are priced and how an agent loop multiplies this effect. For now, keep one idea: a token that stays in the window is paid for repeatedly.
This changes how you judge a large tool result. A 20,000-token log dump costs its tokens once when the tool returns it. It then sits in the history and is resent on every later turn. If the agent runs 15 more turns, that single dump is billed about 16 times. Cutting it to a 500-token excerpt saves most of that.
Common errors
- Counting only the conversation. The system prompt and tool definitions are also in the window. Teams that add many tools or long rule files find their usable window is smaller than expected.
- Forgetting reserved output. A request that fits as input can still fail or truncate because no room was left for the reply.
- Assuming a bigger window fixes everything. It delays the limit and raises the per-turn cost. It does not remove either problem.
- Treating the character estimate as exact. It can be off by a large factor for unusual content.
- Ignoring tool results. In a coding session, file reads and command output usually outweigh the chat text by a wide margin.
Check your understanding
Exercise
A model has a 100,000-token window. The system prompt uses 3,000 tokens, tool definitions use 7,000, and the history is 70,000. You reserve 10,000 for output. How many tokens are free, and can the agent read a file estimated at 12,000 tokens?
Show answer
Free tokens are 100,000 - (3,000 + 7,000 + 70,000) - 10,000 = 10,000. The 12,000-token file does not fit. The agent should read only part of it, or old content must be removed or compacted first.
Exercise
An agent receives a 20,000-token log in turn 5 and the session runs to turn 20 with no compaction. Roughly how many times is that log sent as input, and why does that matter for cost?
Show answer
It is sent on turns 5 through 20, which is 16 times. Each turn resends the whole context, so the log is billed as input on every turn after it appears. Trimming it to a short excerpt saves tokens on all 16 turns.