Sub topic 12
Keeping the Context Under Control
This chapter assumes you have read the agent loop chapter. You should know that call_model receives the whole messages list on every step, and that tool results are appended to that list. It also assumes you can read basic Python.
Why the context grows
An agent loop does not remember anything between model calls. Each call sends the full conversation again: the system prompt, the question, every assistant turn, and every tool result so far. Cost, latency and the risk of hitting the model's context window all grow with that list.
Retrieved passages are the main cause. Suppose each search_docs call returns four passages of up to 1,200 characters. That is roughly 1,200 tokens per call. After five steps, the early results have been re-sent up to five times.
| Step | New tool result (tokens) | Total sent to the model (tokens) |
|---|---|---|
| 1 | 1,200 | about 1,400 |
| 2 | 1,200 | about 2,700 |
| 3 | 1,200 | about 4,000 |
| 4 | 1,200 | about 5,300 |
| 5 | 1,200 | about 6,600 |
The numbers are illustrative. The pattern is what matters: input size grows linearly per step, so total tokens processed across the run grow roughly with the square of the number of steps.
Long contexts also hurt quality. Models tend to use information in the middle of a long prompt less reliably than information near the start or end. Irrelevant passages from a failed query can distract the model from the useful ones.
Where to cut
You have four levers, listed from cheapest to most involved:
- Limit what each tool call returns.
- Avoid returning the same passage twice.
- Replace old tool results with short stubs.
- Summarize or keep notes, and drop the raw text.
Apply them in that order. Each one adds code and a way to lose information, so stop when the context fits your budget.
Lever 1: cap each result
The search_docs function from the retrieval chapter already clamps top_k to 8 and cuts each passage to 1,200 characters. This sets a ceiling of about 9,600 characters, or 2,400 tokens, per call. Treat these limits as part of your context budget, and choose them from your chunk sizes. Cutting a passage mid-sentence can remove the sentence that answers the question. If your chunks are 800 characters, a 1,200-character cap does nothing. If they are 3,000, it silently discards most of each chunk.
Lever 2: skip passages the model has already seen
Agents often repeat themselves. A rewritten query frequently returns the same top passages as the original. Track the ids you have returned in a run and filter them out.
Do not return an empty list when everything was filtered. The model may read an empty list as "nothing exists on this topic" and give up. Say explicitly that the passages were already shown.
def make_deduping_search(search_fn):
"""Wrap search_fn(query, top_k) -> [{"id": str, "text": str}].
Create one wrapper per question, so the seen-set starts empty each run.
"""
seen = set()
def search(query, top_k=4):
fresh, repeated = [], []
for chunk in search_fn(query, top_k):
if chunk["id"] in seen:
repeated.append(chunk["id"])
else:
seen.add(chunk["id"])
fresh.append(chunk)
return {"passages": fresh, "already_seen": repeated}
return searchBecause seen lives in a closure, a wrapper shared across users or questions would leak state between them. Build a new one per run.
Lever 3: replace old results with stubs
Once the model has read a passage and recorded what it learned in its own reasoning or an intermediate message, the full text is often dead weight. You can replace older tool results with a stub that keeps the ids. The model can still cite them, and it can search again if it needs the text.
import json
def estimate_tokens(messages):
# Rough rule: about 4 characters per token for English text.
return sum(len(m.get("content") or "") for m in messages) // 4
def _ids_from(content):
try:
data = json.loads(content)
except (TypeError, ValueError):
return []
if isinstance(data, dict):
data = data.get("passages", []) + [
{"id": i} for i in data.get("already_seen", [])
]
if not isinstance(data, list):
return []
return [c["id"] for c in data if isinstance(c, dict) and "id" in c]
def compact(messages, keep_recent=2):
"""Return a copy where all but the newest tool results become stubs."""
tool_positions = [i for i, m in enumerate(messages) if m["role"] == "tool"]
to_stub = set(tool_positions[:-keep_recent]) if keep_recent else set(tool_positions)
out = []
for i, m in enumerate(messages):
if i in to_stub:
stub = {
"note": "Older result removed to save space. Search again if you need the text.",
"passage_ids": _ids_from(m["content"]),
}
m = {**m, "content": json.dumps(stub)}
out.append(m)
return out
if __name__ == "__main__":
big = json.dumps({"passages": [{"id": "a1", "text": "x" * 1200}], "already_seen": []})
history = [
{"role": "user", "content": "What is the rate limit?"},
{"role": "tool", "tool_call_id": "1", "content": big},
{"role": "tool", "tool_call_id": "2", "content": big},
{"role": "tool", "tool_call_id": "3", "content": big},
]
print(estimate_tokens(history), "->", estimate_tokens(compact(history)))In your loop, call compact(messages) and pass the result to call_model, but keep appending to the original messages list. That way you never lose the raw record, which you will want for logging and evaluation.
Compaction replaces content and keeps every message. This matters: most provider APIs require each assistant tool call to be followed by a matching tool result. If you delete a tool message but keep the assistant message that requested it, the next request may be rejected.
Lever 4: summaries and notes
If runs are long, stubs are not enough, because the model loses the facts it found. Two options help:
- Rolling summary. After N steps, ask a model to turn the older messages into a short summary of findings, open questions and cited ids. Replace those messages with one summary message. This costs an extra model call and can introduce errors, so check summaries in your evaluation set.
- Scratchpad tool. Give the agent a
save_note(text)tool. Notes live outside the message history and are re-injected in a compact block each step. The model decides what is worth keeping. This costs one extra tool call, and it relies on the model using the tool.
Both options trade fidelity for space. Citations are the main casualty. If a summary drops passage ids, the final answer cannot cite them. Require ids in the summary format.
Common errors
- Counting only the latest call. Budget for the total sent across the run, not the size of one result.
- Compacting the newest results. The model needs the last passages in full to answer. Keep the most recent ones intact.
- Mutating the original list. Compact a copy so logs and evaluations see the true history.
- Stubs without ids. Without ids, the model cannot cite or re-fetch a passage.
- Sharing dedupe state between questions. This hides passages from later users.
- Trusting a fixed character-per-token ratio. The 4-to-1 estimate is rough and fails for code and for many non-English languages. Use your provider's tokenizer or reported usage for hard limits.
Exercise
An agent runs six steps. Each tool result is 1,000 tokens, and the system prompt plus question is 200 tokens. Ignoring assistant text, how many input tokens does the model receive at step 6 with no compaction? How many with compact(messages, keep_recent=2) if each stub is about 30 tokens?
Show answer
With no compaction, step 6 receives 200 + 5 × 1,000 = 5,200 tokens, because five tool results exist before the sixth call. With compaction and keep_recent=2, the two newest results stay in full (2,000 tokens) and the other three become stubs (3 × 30 = 90 tokens), so the total is about 200 + 2,000 + 90 = 2,290 tokens.