Sub topic 12
Keeping the context under control
This chapter assumes you have read the agent loop chapter. You should be comfortable with the messages list, tool results appended as role: "tool" messages, and the MAX_STEPS budget.
Why the context grows
In classic RAG the prompt is built once. In an agent loop, every step appends the model's tool call and the tool's result to messages. The whole list is sent again on the next step. Four searches that each return 4 passages of 1,200 characters add about 19,000 characters of passages before the model writes anything.
Growth causes three problems:
- Cost and latency. You pay for the full history on every call, so total input tokens grow roughly with the square of the number of steps.
- Limit overflow. A long loop can exceed the model's context window and fail.
- Lower quality. Relevant facts get buried among stale or irrelevant passages, and the model attends to them less reliably.
Limit what enters the context
The cheapest control is at the tool boundary. The search_docs function already clamps top_k and truncates each passage to 1,200 characters. Keep those caps, and consider skipping passages whose id the model has already seen in this run.
Compact what is already there
Old tool results matter less than recent ones. The model has usually extracted what it needed and moved on. Before each model call, shrink older results but keep their passage ids, so citations still work.
import json
def shrink_result(content, max_chars):
data = json.loads(content)
if isinstance(data, list):
data = [{"id": p["id"], "text": p["text"][:max_chars]} for p in data]
return json.dumps(data)
def compact_history(messages, keep_last=2, max_chars=200):
# Return a copy in which all but the newest `keep_last` tool results are shortened.
tool_idx = [i for i, m in enumerate(messages) if m["role"] == "tool"]
old = set(tool_idx[:max(len(tool_idx) - keep_last, 0)])
out = []
for i, m in enumerate(messages):
if i in old:
m = {**m, "content": shrink_result(m["content"], max_chars)}
out.append(m)
return out
history = [
{"role": "user", "content": "How do I rotate keys?"},
{"role": "tool", "tool_call_id": "1", "content": json.dumps([{"id": "kb-7", "text": "x" * 1000}])},
{"role": "tool", "tool_call_id": "2", "content": json.dumps([{"id": "kb-9", "text": "y" * 1000}])},
{"role": "tool", "tool_call_id": "3", "content": json.dumps([{"id": "kb-2", "text": "z" * 1000}])},
]
compacted = compact_history(history, keep_last=1)
print([len(m["content"]) for m in compacted])In run_agent, call call_model(compact_history(messages), tool_specs). Keep the full messages list unchanged, so you can log it for debugging and evaluation.
Other options
| Technique | What it does | Main risk |
|---|---|---|
| Truncate old results | Cuts passage text, keeps ids | May drop the sentence you later need |
| Summarize history | Replaces old steps with a short model-written summary | Extra model call, and the summary can lose or distort facts |
| Keep a notes list | The model records findings, and raw passages are dropped | Notes are only as accurate as the model's reading |
| Smaller `top_k` | Fewer passages per search | Lower recall on a single query |
Common errors
- Compacting the newest result, so the model never sees the evidence it just fetched.
- Mutating the stored history, which makes failed runs impossible to replay.
- Summarizing without keeping ids, which breaks grounding.
Exercise
A run uses 5 steps, and each search returns 4 passages of 1,200 characters. Using compact_history with keep_last=2 and max_chars=200, roughly how many passage characters does the model see at step 5, assuming 4 tool results exist by then?
Show answer
Four results exist. The newest 2 stay full, which is 2 × 4 × 1,200 = 9,600 characters. The older 2 are cut to 200 characters per passage, which is 2 × 4 × 200 = 1,600 characters. The total is about 11,200 characters, compared with 19,200 uncompacted.