llm.guideChapter 20Context Engineering for Long-Running Agents

Context Engineering for Long-Running Agents

Compaction, sub-agents, just-in-time retrieval and context rot.

Part 5: Agents. 9 sections, about 15 minutes.

040K80K1102030405060tokens in the context windowstep of the agent’s runkeep everything: 110Kclear old tool resultscompact at 40K
040K80K1102030405060tokens in the context windowstep of the agent’s run110Kclear resultscompact
The context window over a 60-step run, under three policies. Left alone, it grows without limit. The two managed lines are the subject of this chapter.

Prompt engineering asks what to say to a model. Context engineering asks a wider question: of everything that could be in the window at this step, what should be? For a single request the two are nearly the same. For an agent that runs for an hour, adding to its own context at every step, the second question decides whether the run finishes at all.

The numbers in this chapter come from a cost model of a 60-step run, with every assumption stated, using the caching prices from section 11.6. The practices follow Anthropic’s published guidance on the subject, which is the clearest account available.

20.1A finite budget

Context is working memory, and every token spends some of it.

A context window has a hard limit, and section 2.6 treated it as a budget in that sense. For agents a second sense matters more. Attention relates every token to every other, so the number of relationships grows with the square of the length. A model has a limited capacity to keep them all straight. Each token added to the window draws on that capacity, whether or not it is useful.

The practical statement of the goal is Anthropic’s: find the smallest set of high-signal tokens that makes the desired outcome most likely. That turns context into something to be curated at every step, and it covers more than the prompt:

  • the system prompt and tool definitions, which are present at every step;
  • the transcript: the model’s own messages, its tool calls and their results;
  • documents, notes and memories brought in from outside;
  • and, just as much, what is deliberately left out.

Common take“The model has a million-token window, so context isn’t a constraint.”

Sharper take“The window is a ceiling. The budget that matters is attention, and it is spent by every token I put in, useful or not. I aim for the smallest context that does the job.”

20.2Context rot

Quality decays as the window fills, well before it is full.

The evidence that more context can be worse has accumulated from several directions.

  • Position matters. The “lost in the middle” experiments of 2023 showed that models use information best when it sits at the start or the end of a long context and worst when it sits in the middle (section 2.4).
  • Length matters by itself. A 2025 study of eighteen models found accuracy falling as input grew, even on simple tasks and even when the needed information was present. The effect has been named context rot.
  • Distractors matter. Text that is related to the task and irrelevant to the answer pulls responses off course, the same distractor effect seen in retrieval (section 15.7).
0%25%50%75%100%1K2K4K8K16K32Kaccuracytokens of contextGPT-4oLlama 3.3 70BGemini 1.5 ProGPT-4o mini
0%25%50%75%100%1K2K4K8K16K32Kaccuracytokens of context
  • GPT-4o
  • Llama 3.3 70B
  • Gemini 1.5 Pro
  • GPT-4o mini
Figure 20.1 Published measurements from NoLiMa (Modarressi and colleagues, ICML 2025), a test that hides one fact in long irrelevant text and asks about it in words that do not appear in the fact. Every model loses accuracy as the context grows, long before its advertised limit of 128,000 tokens or more.

For an agent the three combine badly. Its context grows at every step. The goal and the plan, stated at the beginning, drift toward the middle. And the transcript fills with tool results that mattered once: old search results, files already read, errors already fixed. This is the mechanism behind the goal drift of section 18.4.

Common take“Give the agent everything. More context can only help.”

Sharper take“Past a point, more context makes a model worse at using any of it. For a long run I treat the size of the window as a quality metric, not only a cost.”

20.3What fills the window

Mostly tool results.

To make the discussion concrete, take a model of a typical run: a fixed prefix of 6,000 tokens for the system prompt and tools, and 60 steps. At each step the model writes about 250 tokens, a short thought and a tool call. Each tool result is about 700 tokens, and every sixth is a large one of 6,000: a file, a page, a long search result. After forty steps the window holds:

  • system prompt and tool definitions: 6,000 tokens, 8%
  • the model’s own messages and tool calls: 10,000 tokens, 13%
  • tool results: 59,800 tokens, 79%
Figure 20.2 What the context holds after 40 steps of the modeled run: 75,800 tokens in all.

The model’s own words are a small share. The fixed prefix is smaller still. Four fifths of the window is tool output, and most of it has already served its purpose. That is where the leverage is, and it suggests an order of attack:

Common take“Our system prompt is too long. Let’s trim it to save context.”

Sharper take“After forty steps the system prompt is under a tenth of the window and tool results are four fifths. I measure what fills the context before deciding what to cut.”

20.4Clearing and compaction

Shrink the transcript without losing the thread.

There are two standard ways to cut a transcript down while a run continues.

  • Clearing tool results. Replace the content of old tool results with a short placeholder, keeping the record that the call was made. It is cheap, needs no model call, and is safe when the agent can fetch the content again.
  • Compaction. When the context passes a threshold, have a model summarize the history, and continue from the summary plus the most recent steps. It removes far more, costs a model call, and is lossy: what the summary omits is gone.

The figure at the top of the chapter shows both applied to the modeled run, with old results cleared every ten steps, or the history compacted at 40,000 tokens. The table adds the cost, in units of one ordinary input token.

PolicyLargest contextInput cost without cachingInput cost with cachingEdits to the transcript
Keep everything109,750 tokens3.55 million0.55 million0
Clear old tool results every 10 steps45,000 tokens1.76 million0.46 million6
Compact when the context passes 40,000 tokens39,950 tokens1.70 million0.43 million3

Two things stand out. First, managing the context cuts the largest window from about 110,000 tokens to between 40,000 and 45,000, which is the quality argument of section 20.2. Second, look at what it does to cost. Without prompt caching, either policy halves the bill. With caching, the saving is only about a fifth. Cached tokens are already cheap to re-read, and every edit to the transcript changes the prefix, so everything after the edit has to be written to the cache again (section 11.6).

That has a design consequence. Edit the transcript in batches, not at every step. Clearing one result per step would break the cache on every call. Clearing every ten steps breaks it six times in this run.

Compaction’s risk is in what the summary drops. A good one keeps decisions and their reasons, unresolved problems, the current state of the work, and identifiers such as file paths that let detail be fetched again. A poor one keeps a pleasant narrative and loses the one constraint that mattered. Tune the summarizing prompt on real traces: first for missing nothing important, then for brevity.

Full transcript26,000 tokensResults cleared13,400 tokensCompacted7,500 tokenssystem prompt and goal (accent), full steps (blue), cleared results (grey), summary (yellow)
Figure 20.3 Illustrative sizes drawn to scale: 30 steps of about 800 tokens after a 2,000-token system prompt. Clearing keeps the record of every call; compaction keeps only what the summary says.

Common take“We summarize the conversation every few turns to save tokens.”

Sharper take“With caching, frequent edits can cost more than they save, because each one invalidates the cached prefix. I clear or compact in batches, mainly to keep the window small enough for the model to think well, and I check what the summaries lose.”

20.5Notes and memory files

Write state outside the window so that it survives.

Compaction decides after the fact what to keep. Structured note-taking decides in advance. The agent is given a place outside the context, a file or a small store, and writes its important state there as it works: the plan and what has been ticked off, decisions made, things learned about the environment, open questions. After a compaction, or in a later session, it reads the notes back.

NOTES.md
Goal        migrate the billing module to the new tax API
Done        1 inventory of call sites (14 files, list in sites.txt)
            2 adapter written and unit-tested
Now         3 update call sites, 6 of 14 finished
Decisions   keep the old rounding rule (see ticket 4411)
Watch out   tests in /legacy need the TZ variable set

Notes are what turn a context reset from a loss into a routine event. They also carry work across sessions, which the transcript cannot. A to-do list that the agent maintains is the simplest form, and it does two jobs: it is a record, and re-reading it puts the goal back at the end of the context where attention is strongest.

The caution from section 18.5 applies with full force. Notes are read back later as trusted context. An error written into them recurs, and text copied into them from an untrusted source can carry instructions (Chapter 26). Keep notes short and structured, and let the agent write facts it has verified, not everything it has seen.

Common take“The agent forgets what it was doing after a long session.”

Sharper take“I give it a notes file: goal, progress, decisions, hazards. It updates the file as it works and rereads it after any reset. State that matters shouldn’t live only in a transcript that I’m going to trim.”

20.6Just-in-time retrieval

Keep references, and load the content when it is needed.

There are two ways to give an agent information. Load it up front, as Chapter 15’s pipeline does, or give the agent the means to find it and let it look when the need arises.

Up frontJust in time
What is in the contextThe content itselfReferences: file paths, links, saved queries, identifiers
SpeedFast: one stepSlower: the agent spends steps exploring
Context usedAll of it, relevant or notOnly what turned out to be needed
FreshnessAs of when it was loaded or indexedAs of now
FitsSmall, stable material that is nearly always relevantLarge or changing collections

A reference costs a few tokens and stands for thousands. People work the same way: nobody memorizes a codebase; they know where things are. The names and structure of what is referenced carry information too. A file called test_billing.py in a tests folder tells the agent a good deal before it opens anything.

Most good systems are hybrids. A small amount that is always needed, such as project conventions and key facts, is loaded at the start. Everything else is reachable through tools: search, list, read. Coding agents are the clearest example, with a short instructions file loaded at the outset and the rest of the repository explored on demand.

Common take“We load the relevant documentation into the context at the start, to be safe.”

Sharper take“I load the little that is always needed and give the agent tools to find the rest. A file path costs ten tokens, and the file costs five thousand, most of them never used.”

20.7Sub-agents

Spend tokens in a separate window and bring back a summary.

Lead agentplan, notes, summariesSub-agentsearch the docsSub-agentread the codeSub-agentcheck the logssolid: a taskdashed: a summaryeach sub-agent works in its own context window
Figure 20.4 Context isolation. Each sub-agent may read tens of thousands of tokens to do its piece of work. Only its conclusions return to the lead agent’s window.

Some work is expensive in context and cheap to report: searching a large codebase for where something is used, reading ten documents to answer one question. A sub-agent does that work in its own window and returns a short summary. The lead agent’s context receives the conclusion and never sees the search.

This is the one benefit of multi-agent systems that section 19.9 called decisive, and it is a context-engineering technique before it is an architecture. It also allows parallel work when the pieces are independent.

The costs come from the same place as the benefit. The sub-agent knows only what its task description tells it, so a vague brief produces a confident answer to the wrong question. The lead agent sees only the summary, so detail that turns out to matter later is gone. And total token use goes up, since several windows are filled where one was before. Write the brief as you would for a contractor: the goal, what is already known, what to return and in what form.

Common take“We use sub-agents so that each one can be an expert in its area.”

Sharper take“I use a sub-agent when a piece of work would flood the main context and its result can be stated briefly. What I’m buying is a clean window for the lead agent, and what I’m paying is a lossy handoff in both directions.”

20.8Skills and progressive disclosure

Instructions that load only when they are relevant.

An agent that can do many kinds of task needs many sets of instructions: how to write a report in the house format, how to run the deployment checklist, how to fill in a particular form. Putting all of them in the system prompt spends context on every step for procedures that are rarely used.

A skill packages one such procedure as a folder: a short description, the full instructions, and any scripts or reference files. Only the description, a line or two, is in the context from the start. When a task matches it, the agent reads the full instructions, and further files only if they are needed.

LevelWhat is loadedWhen
1Name and one-line description of every skillAlways
2The full instructions of one skillWhen the task matches its description
3Its scripts, templates and reference filesWhen the instructions call for them

The principle is progressive disclosure, and it is the same idea as just-in-time retrieval applied to instructions. It also applies to tools: a long tool list can be replaced by a search over tools, with definitions loaded as they are needed.

The weak point is the first level. The agent decides whether to open a skill from its description alone, so a description has to say plainly what the skill is for and when to use it, as a tool description does (section 18.2).

1 Name and descriptionevery skill, always loadeda line or two each2 Full instructionsone skill, when the task matcheshundreds to a few thousand tokens3 Bundled filesscripts, templates, referencesread only if a step needs themThe width is how many skills each level touches, not their size.
Figure 20.5 Progressive disclosure. The agent pays a line of context per skill up front and the full cost only for the skill it uses.

Common take“Our system prompt has every procedure the agent might need, about 30,000 tokens.”

Sharper take“I keep a line per procedure in the context and load the full text only when a task calls for it. Thirty thousand tokens on every step is paid in attention whether a procedure is used or not.”

20.9Measuring it

Long-horizon evaluation, and a trace of what was in the window.

Every technique in this chapter trades something away, so each needs measuring. Short test cases will not do it: a context policy has no effect on a five-step task.

What to measureHow
Task success against lengthRun tasks of increasing length and plot success against the number of steps. A policy that works lifts the right-hand end of the curve
Context size per stepLog tokens in the window at every step, split by kind, as in section 20.3
What a compaction lostAfter each compaction, ask questions whose answers were in the dropped history, and score the answers
Repeated workCount tool calls that repeat an earlier call. A rise after a policy change means needed context was removed
Cache hit rateCached tokens as a share of input. A fall means the policy edits the prefix too often
Cost and time per completed taskPer success, not per attempt

The debugging tool is a trace that records, for each step, exactly what the window contained (Chapter 24). When a long run goes wrong, the first question is the one from section 15.9, adapted: was the information the agent needed still in its context at the step where it failed? If it was cleared, summarized away or never noted, the failure is a context-policy bug, and no change of model will fix it.

Common take“We tested the agent on our evaluation set and it passed.”

Sharper take“Were any of those tasks long enough for the context policy to act? I test at the lengths we expect in production, plot success against steps, and keep a trace of what was in the window at each one.”

Key takeaways

  • Context engineering is choosing what is in the window at each step: the smallest set of high-signal tokens that makes the right outcome likely.
  • Quality decays as the window fills, well before the limit. Position, length and distractors all contribute.
  • In a modeled 40-step run, tool results were about four fifths of the window. Start there.
  • Clearing old tool results is cheap and safe when content can be re-fetched. Compaction removes more and is lossy.
  • Managing context cut the largest window from about 110,000 tokens to under 45,000. It halved cost without caching and saved only about a fifth with it.
  • Every edit to the transcript invalidates the cached prefix after it, so edit in batches.
  • Notes outside the window carry the goal, progress and decisions across resets and sessions.
  • Keep references in the context and load content when it is needed.
  • A sub-agent buys a clean window for the lead agent at the price of a lossy handoff.
  • Skills load instructions in three levels: a description always, the body on a match, files on demand.
  • Evaluate at production lengths, and trace what was in the window at each step.

Check your understanding

  1. A coding agent does well on tasks of about fifteen steps. On tasks of sixty steps it starts repeating searches it has already done, and around step forty it loses track of the original request. Explain the mechanism and propose a context policy.

    Answer outline

    The window has grown large and is dominated by old tool results. The original request and the plan are now far back, where the model attends least, and performance falls with length in any case. Repeated searches suggest either that the earlier results are buried, or that a clearing or summarizing step removed them without a note. Policy: return less from tools; clear stale results in batches; compact at a threshold with a summary that keeps decisions, state and file paths; have the agent keep a notes file with the goal and progress and reread it after each reset; move broad searches into sub-agents. Measure success against task length, repeated calls, and context size per step.

  2. To reduce cost, a teammate changes the agent to remove each tool result from the transcript as soon as the next step has used it. The token count per request falls by 40%, and the bill goes up. Explain.

    Answer outline

    Prompt caching bills a cached prefix at a small fraction of the normal price, and the cache matches an exact prefix. Removing a result at every step changes the transcript on every call, so everything after the change has to be written to the cache again, at a premium, where it was previously read cheaply. Fewer tokens at a higher price each came to more. Fix: edit in batches, for example clearing old results every ten steps or at a size threshold, so that most calls still extend a cached prefix, and confirm with the cache-read share of input tokens.

  3. Your research agent delegates searches to sub-agents. Reviewers find that its reports are fluent and sometimes answer a slightly different question from the one asked. Where would you look, and what would you change?

    Answer outline

    Look at the handoffs. Read the task descriptions the lead agent wrote for its sub-agents: a brief that omits the user’s real question, constraints or what is already known produces accurate answers to the wrong question. Then read the summaries coming back for detail the lead agent needed and never received. Changes: a brief template with the goal, the context, what to return and in what form; have sub-agents return sources and key quotations as well as conclusions; and keep the user’s original question pinned in the lead agent’s context so that the final report can be checked against it.

Further reading

  • Anthropic, “Effective context engineering for AI agents” (2025): the source of this chapter’s framing, with compaction, note-taking and sub-agents described from practice.
  • Maarten Grootendorst and Jay Alammar, An Illustrated Guide to AI Agents: the chapters on memory and context.
  • Liu et al. (2023), “Lost in the Middle: How Language Models Use Long Contexts”: the experiments behind section 20.2.

↑↓ to move↵ to openesc to close