Papa Programmer
Lesson 08 of 20

Context window optimisation

8 min read

Optional

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.

  1. 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.
  2. 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.
  3. Summarise the old history. Replace the oldest steps with a short summary that a model writes. Keep the most recent steps word for word.
  4. 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.

python
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.

Cut noise firstTrim tool output and drop finished detail before you reach for a summary.
Summarise the old, keep the newCompress early steps and keep the latest ones word for word.
Pin the goalNever trim the user's goal or the rules, even when the window is full.

Your reading position is saved

0%

0 of 20 complete

Contents

Learning tools