Context window optimisation
8 min read
Why the window fills
Picture an agent that fixes a failing test. It reads a file of 600 lines, runs the tests and prints 300 lines of output. It reads a second file and runs the tests again. After ten steps, the history holds thousands of lines, and most of them no longer matter.
A full Context windowThe maximum number of tokens a model can process in its context. Depending on the model, the limit can include the answer as well as the input. causes three problems. The call costs more, the reply is slower, and the model is more likely to miss an important line. A model that misses a fact may fill the gap with a guess, which is how an AI hallucinationAn answer that sounds confident but is false. The model wrote text that fits the pattern instead of text that is true. starts.
Four ways to keep it small
Try these in order. The first is the cheapest, and the last is the most work.
- Trim tool output. Return only what the next step needs. A search tool should send back the top five snippets, not the entire page. A test tool should send the failing lines, not the whole log.
- Drop what is finished. Once a sub-task is done, its detail rarely helps again. Remove old tool results and keep one line that says what happened.
- Summarise the old history. Replace the oldest steps with a short summary that a model writes. Keep the most recent steps word for word.
- Retrieve instead of carry. Store large material outside the prompt and look it up when needed. This is the idea behind retrieval, from the previous Lesson.
Fit the history to a budget
The sketch below keeps the system message, keeps the newest messages and drops the oldest ones until the history fits.
def tokens(message):
return len(message["content"]) // 4
def fit(messages, budget):
system, rest = messages[0], messages[1:]
kept = []
used = tokens(system)
for message in reversed(rest):
if used + tokens(message) > budget:
break
kept.append(message)
used += tokens(message)
return [system, *reversed(kept)]
history = [{"role": "system", "content": "Rules."}] + [
{"role": "user", "content": f"step {n} " + "x" * 400} for n in range(10)
]
print(len(fit(history, budget=300)))It prints 3. The system message and the two newest steps fit in 300 tokens, and the older eight are dropped. A real version would summarise those eight instead of deleting them.
Where to put things
What you keep also depends on where you place it. Rules belong at the start, because they apply to everything. The goal and the latest result belong at the end, close to where the model starts to write. If a fact must not be missed, repeat it near the end.
Two mistakes are common. The first is trimming blindly, such as cutting the oldest messages without noticing that one of them holds the user's original goal. Pin the goal so that it never gets trimmed. The second is summarising too early. A summary loses detail, so wait until the window is genuinely under pressure.
What do you try first?
An agent's history is full of 300-line test logs. Only the three failing lines matter.
Trimming tool output is the cheapest fix, so try it before summaries or bigger models.
What must you protect?
You cut the oldest messages to fit the budget, and the agent forgets what it was asked to do.
Blind trimming can drop the original goal. Keep the goal and the rules, whatever else goes.
When should you summarise?
The window is half empty and the task has run for five steps.
Summarising too early throws away detail you may need. Compress when the window genuinely fills.
Your reading position is saved
0 of 20 complete
Lesson complete
Context window optimisation
Up next