Topic 5 of 5 · 4 min read
Managing context across loop turns
Goal: Choose what to keep, summarise or drop from a long agent history so the next turn still has the facts it needs.
Every turn re-sends the history, so a long loop must decide what to keep verbatim, what to summarise and what to drop, or it will hit the context window and lose track of its own task. The aim is the smallest history that still holds every fact the next step needs.
Check yourself · 1 of 3
In a long agent run, which part of the history is usually the safest to clear after several turns?
Why it matters
Tool results are the bulk of an agent's history: whole files, search pages, command output. They are useful for one or two turns and dead weight after that. Large histories also cost more per turn and give the model more noise to reason from. Anthropic's guidance on context engineering treats context as a limited resource to curate, not a log to append to.
Three techniques
- Clear old tool results. Replace the body of a tool result from 10 turns ago with a stub such as
[result cleared: read_file src/db.ts]. The model still sees that it read the file. Some APIs, including Claude's context editing, can do this automatically. - Compact. When the history nears the window, ask the model to summarise it, then start a new history with the summary. Keep the goal, decisions made, the current state and open questions.
- Take notes outside the window. The agent writes key facts to a file or a store, such as a plan or a TODO list, and re-reads them when needed.
What to keep, summarise, drop
- Keep verbatim: the original task, constraints the user gave, ids, file paths, exact error messages still being worked on, the current plan.
- Summarise: long reasoning, exploration that led to a decision, finished subtasks.
- Drop: raw output of finished steps, duplicate reads of the same file, successful but irrelevant results.
function trim(messages: Message[], keepLast = 6) {
return messages.map((m, i) =>
m.role === "tool" && i < messages.length - keepLast
? { ...m, content: "[cleared: " + m.toolName + "]" }
: m);
}
Before and after
Weak summary: "The agent explored the repo and found some issues." It lost the file, the line and the decision, so the next turn re-reads everything.
Better: "Task: fix the null crash in checkout. Found: crash at src/cart.ts:88 when coupon is undefined. Decided: guard in applyCoupon, not in callers. Done: edit made. Open: run tests; check CartSummary uses the same field."
What goes wrong
- Summaries that drop identifiers. Paths, ids and numbers are the facts the model cannot rebuild.
- Clearing a result still in use. The model asks for the same file again, wasting a turn.
- Compacting too late. Past the window the call fails, with no room left for the summary.
- Dropping the user's constraints. After compaction the agent forgets "do not touch the billing module".
Examples
A compaction prompt and its output
Summarise this session for the next turn. Keep: the task, user constraints, decisions with reasons, file paths and ids, current state, open questions. Drop raw tool output.
Output: Task: add CSV export to /reports. Constraint: no new dependencies. Decided: use the existing toCsv helper in src/lib/csv.ts. Done: route added in src/routes/reports.ts. Open: header row for empty reports.
Result clearing in practice
At turn 14 the history holds 11 full file reads. The loop replaces all but the last two with [cleared: read_file path]. The agent keeps the list of files it has seen, and the context drops sharply. If it needs a file again, it reads it again.
Key points
- Tool results dominate agent history and are rarely needed after a few turns.
- Clear old tool results, compact the history into a summary, or write notes outside the window.
- Keep the task, user constraints, ids, paths and the current plan exactly as written.
- A good summary carries decisions, current state and open questions, not a story of what happened.
- Compact before the window is full, and never drop standing constraints from the user.
Common mistakes
- Summarising into prose that omits file paths, ids and exact error text.
- Clearing every tool result, including the one the current step depends on.
- Waiting for a context-limit error before compacting.
- Forgetting to carry the user's standing constraints into the summary.
Check yourself · 2 of 3
Which compaction summary will serve the next turn best?
Check yourself · 3 of 3
After compaction, an agent edits the billing module although the user said at the start not to touch it. What most likely went wrong?
Practice items, not counted towards your mastery.
Start here
- ReAct: Synergizing Reasoning and Acting in Language Models (opens in a new tab)PaperFree
The paper that named the pattern of interleaving reasoning steps with actions and observations.
- Building effective agents (Anthropic) (opens in a new tab)ArticleFree
Describes agents as models using tools in a loop, and why to add stopping conditions and checkpoints.
- LLM Powered Autonomous Agents (Lilian Weng) (opens in a new tab)ArticleFree
A long survey of planning, memory and tool use, including ReAct-style loops and their failure modes.
More for this topic
- Effective context engineering for AI agents (Anthropic) (opens in a new tab)ArticleFree
Compaction, tool-result clearing and note-taking for agents whose history outgrows the context window.
- Context editing (Claude docs) (opens in a new tab)DocsFree
How automatic clearing of old tool results keeps long agent runs inside the context window.