Sub topic 2
The context window as working space
This chapter assumes you can write basic Python, have called a chat-style LLM API, and know that an agent is an LLM running in a loop with tools. The previous chapter explained that each model call is stateless. This chapter looks at the one place where the model can see anything: the context window.
What the context window is
The context window is the maximum amount of text, measured in tokens, that a model can read and write in a single call. A token is a chunk of text, often a short word or part of a word. In English, one token averages about four characters, but this varies by language, by code, and by tokenizer.
Everything the model knows about your situation must fit in this window. If a fact is not in the prompt and not in the model's trained weights, the model cannot use it. For this reason the window works like a desk. The model can only work with what is on the desk, and the desk has a fixed size.
Two properties follow from this:
- The window is shared between input and output. The model's reply also consumes tokens from the same limit, or from a separate output cap on some APIs.
- The window is rebuilt on every call. Nothing in it persists unless your code puts it back.
What competes for space
In a simple chatbot, the window holds a system prompt and a conversation. In an agent, many more things compete for the same space.
| Component | What it contains | How it grows |
|---|---|---|
| System prompt | Role, rules, output format | Fixed, but often long |
| Tool definitions | Names, descriptions, and JSON schemas for each tool | Grows with each tool you add |
| Retrieved memories | Facts pulled from long-term storage | Grows with the number of results (k) |
| Conversation history | Earlier user and assistant messages | Grows every turn |
| Tool calls and results | Arguments sent and data returned | Can grow fast, such as a large search result |
| Current user input | The newest message | Varies |
| Reserved output | Room for the model's reply | Set by you |
Tool results are the most common cause of surprise. One call that returns a 20,000-token web page can fill an entire window in a single step. Agents run in a loop, so these results accumulate across iterations.
A budget you can compute
Treat the window as a budget and compute it before each call. The rule is simple: the sum of all input parts plus the reserved output must not exceed the limit.
CONTEXT_LIMIT = 8000
RESERVED_OUTPUT = 1000
def count_tokens(text):
# Rough estimate: about 4 characters per token for English text.
return max(1, len(text) // 4)
def budget_report(parts, limit, reserved_output):
"""Print the token cost of each prompt part and return the tokens left."""
usage = {name: count_tokens(text) for name, text in parts.items()}
for name, tokens in usage.items():
print(f"{name:<14}{tokens:>6}")
total = sum(usage.values())
remaining = limit - reserved_output - total
print(f"{'input total':<14}{total:>6}")
print(f"{'remaining':<14}{remaining:>6}")
return remaining
parts = {
"system": "You are a support agent. " * 20,
"tools": "search(query: string) -> list of results. " * 60,
"memories": "- The user prefers short answers.\n" * 10,
"history": "user: hello\nassistant: hi, how can I help?\n" * 80,
"tool results": "A long document about refunds. " * 200,
}
left = budget_report(parts, CONTEXT_LIMIT, RESERVED_OUTPUT)
if left < 0:
print(f"Over budget by {-left} tokens: trim or summarize before calling the model.")The count_tokens function here is a stand-in. For a real budget, use the tokenizer that matches your model. Different models tokenize the same text differently, so a count from one tokenizer can be wrong for another. Keep a safety margin of around 5 to 10 percent.
The next diagram shows how a window of 8,000 tokens might be divided in a typical agent call.
In this example, history takes the largest share, and tool definitions take more than the system prompt. Only the free space and the history can be adjusted turn by turn. The rest is mostly fixed by your design.
Why a bigger window does not remove the problem
Modern models offer windows of hundreds of thousands of tokens or more. It is tempting to put everything in and skip memory design. This approach has costs.
- Cost. Providers usually charge per input token, and you resend the whole window on every call. A 100,000-token history costs that much again on each loop iteration.
- Latency. Longer inputs take longer to process before the first output token appears.
- Accuracy. Models often use information at the start and end of a long prompt more reliably than information in the middle. This is sometimes called the "lost in the middle" effect. Long prompts also contain more distracting, irrelevant text that can pull the answer off course.
- Hard limits. Even the largest window ends somewhere. An agent that runs for days will pass it.
- No persistence. A big window still disappears when the session ends. It does not give the agent memory between sessions.
Common errors
Forgetting the output reservation. If the input fills the whole window, the reply has no room. Depending on the API, you get an error or a reply cut off mid-sentence. Always subtract the output budget first.
Counting characters or words instead of tokens. The word-count stand-in in the Topic Spine's trimming example is fine for demonstration. In production, a code-heavy or non-English prompt can have far more tokens than words. Counting words will let you go over the limit.
Ignoring tool definitions. They are sent on every call, but developers often leave them out of the budget. Fifteen tools with detailed schemas can use thousands of tokens before the conversation starts.
Letting tool results pile up. Each loop iteration adds the tool's output to the history. Truncate or summarize large results before appending them, and keep only what the next step needs.
Trusting position to be neutral. If a critical instruction sits in the middle of a long prompt, the model may follow it less reliably. Put rules in the system prompt, and put the most relevant retrieved facts close to the user's question.
Mixing up limits. Some providers publish one limit for input plus output and a smaller limit for output alone. Check which applies to your model, and plan for the stricter one.
The window as the meeting point of both memories
The window is where short-term and long-term memory meet. Short-term memory is the conversation held inside the window. Long-term memory lives outside the model and reaches the model only if code retrieves a piece and places it in the window. Whatever is selected, it competes with everything else in the table above.
This changes how you think about memory design. The question is not "how do I store more?" but "what is the smallest set of information that lets the model do this step well?" The chapters that follow give you tools for that selection: trimming and summarizing the buffer, and writing, retrieving, and ranking stored memories.
Summary of the working model
- The model sees only the current window, so you rebuild it on every call.
- The window holds input and output together, so you reserve output room first.
- Many components compete for the space, and tool definitions and tool results are easy to overlook.
- Bigger windows cost more, run slower, and can lower accuracy, so budget even when the limit seems generous.
- Memory design is the practice of choosing what enters the window.
Exercise
An agent has an 8,000-token window and reserves 1,000 tokens for output. Its system prompt uses 500 tokens, its tool definitions use 1,500, and retrieved memories use 500. The user's new message is 100 tokens. How many tokens of conversation history and tool results can it include? Then explain what happens if a tool returns a 6,000-token document in the next step.
Show answer
Input budget is 8,000 - 1,000 = 7,000 tokens. Fixed parts use 500 + 1,500 + 500 + 100 = 2,600 tokens, leaving 4,400 tokens for history and tool results. A 6,000-token document does not fit, because it exceeds 4,400 even if the history is empty. The agent must truncate or summarize the document, or fetch it in smaller pieces, before adding it to the prompt. Otherwise the call fails, the reply is cut short, or the framework silently drops other content.
Exercise
Your agent works well for 20 turns and then starts ignoring a formatting rule that you wrote in the middle of a long prompt. Give two likely causes and one fix for each.
Show answer
Cause one: the rule sits in the middle of a long prompt where the model attends to it less reliably. Fix: move the rule into the system prompt at the start, or repeat it near the end of the prompt. Cause two: a framework or your own trimming code dropped the message containing the rule when the history grew past the budget. Fix: keep the rule in a protected system message that trimming never removes, and log the final prompt to confirm it is still present.