Skip to content

Effective context engineering for AI agents

Skip →MemGPT
main track #5corefundamentalblogrubric 10/122025 · Anthropic Engineering blog · ~25 min

Prithvi Rajasekaran, Ethan Dixon, Carly Ryan, Jeremy Hadfield

Status

TL;DR. Context is the set of tokens the model sees when it samples; context engineering is choosing those tokens at every step of an agent’s loop, not just writing a good prompt once. Because models get worse as context grows (“context rot”), the essay’s guiding principle is to find the smallest possible set of high-signal tokens for the outcome you want. It applies this to system prompts, tools and examples; argues for “just in time” retrieval through lightweight identifiers; and gives three techniques for tasks longer than one window: compaction, structured note-taking and sub-agents.

Why it matters now. For a search agent, the context window is the working memory, and most of it is filled by tool results: search result lists and fetched documents. An agent on BrowseComp-Plus can fill a 128k window in a few dozen steps. Every choice here is an IR choice in disguise: how much of each document to show, whether to keep raw results or summaries, when to re-retrieve rather than remember. RL-trained search agents (ReSum, context folding) now learn parts of this policy instead of hand-designing it.

Context engineering: what enters the window at each step, and three ways to keep long-horizon work inside it Left: the context window at one inference step, holding the system prompt at the right altitude, a small set of non-overlapping tools, a few canonical examples, the message history, and data loaded just in time. Outside the window, files, a database and the web are reached through lightweight identifiers such as paths, stored queries and links, which tools resolve into tokens only when needed. Right: three techniques for tasks longer than one window. Compaction summarises the history near the limit and restarts with the summary plus recently used files; clearing old tool results is the lightest form. Structured notes are written to a file outside the window and read back after a reset. Sub-agents explore with their own clean windows of tens of thousands of tokens and return condensed summaries of about one to two thousand tokens to a lead agent. A bar at the bottom shows recall falling gradually, not abruptly, as the number of tokens grows. The smallest set of high-signal tokens, step after step Context window at step t system prompt at the right altitude few tools, no overlapping roles a few diverse, canonical examples message history: thoughts, calls, tool results (grows every step) data loaded just in time via glob, grep, head, search, fetch outside: files, databases, the web, held as identifiers (paths, queries, links) and resolved only when needed When the task outlasts one window Compaction summarise near the limit, restart with summary + recent files. Lightest: drop old tool output Structured notes agent writes NOTES.md or a to-do list outside the window and reads it back after a reset Sub-agents each explores in its own clean window, using tens of k tokens; returns ~1–2k to the lead context rot: recall declines as tokens grow few tokens many tokens a gradient, not a cliff
Original sketch. What goes into the window at one step, and the essay's three techniques for work that outlasts one window.

Problem. An agent running in a loop generates more potentially relevant tokens than fit, and accuracy drops as the window fills. At each step, which tokens should be in the window?

Why context is finite (the essay’s argument). Needle-in-a-haystack style studies find context rot: recall from the window falls as the number of tokens grows. The essay explains this with an “attention budget”: full attention relates every token to every other, n2n^2 pairs for nn tokens; long sequences are rarer in training data; and position-interpolation tricks that extend windows lose some positional precision. Its conclusion is a gradient, not a cliff: models still work at long context but are less precise. Treat this as a useful framing, not a derivation; the n2n^2 is a compute cost, and the evidence is empirical.

Anatomy of good context.

  • System prompt at the “right altitude”. Between brittle if-else logic hard-coded in the prompt and vague guidance that assumes shared context. Start with a minimal prompt on the best model, then add instructions and examples only for failure modes you observe. Minimal does not mean short.
  • Tools. Self-contained, robust to error, clear in purpose, with little overlap. A common failure is a bloated tool set: if a human engineer cannot say which tool to use, the agent cannot either.
  • Examples. A few diverse, canonical examples instead of a long list of edge-case rules.

Just-in-time retrieval. Many applications retrieve with embeddings before inference. The essay sees agents shifting to loading context at run time: the agent holds lightweight identifiers (file paths, stored queries, links) and uses tools to pull in only what it needs. The metadata itself guides the search (a file’s folder, name and timestamp hint at its purpose), so the agent can discover relevant context step by step (progressive disclosure). The trade-off is speed: exploring at run time is slower than reading precomputed data, and a poorly guided agent wastes context on dead ends. Claude Code uses a hybrid: CLAUDE.md files go into context up front, and glob and grep fetch files just in time, which also avoids stale indexes.

Long-horizon techniques.

  1. Compaction. Near the limit, summarise the conversation and restart with the summary. In Claude Code the model keeps architectural decisions, unresolved bugs and implementation details, drops redundant tool output, and continues with the summary plus the five most recently accessed files. Tune the compaction prompt for recall first, then precision. The lightest form is tool-result clearing: a raw result deep in the history rarely needs to be seen again.
  2. Structured note-taking. The agent writes notes outside the window (a to-do list, a NOTES.md file, a memory tool) and reads them back later. The essay’s example is Claude playing Pokémon, which keeps tallies and maps across thousands of game steps and resumes from its notes after context resets.
  3. Sub-agents. Each sub-agent explores in a clean window, possibly using tens of thousands of tokens, and returns a condensed summary of often 1,000–2,000 tokens. The lead agent keeps the plan and synthesises.

Which to use depends on the task: compaction for long back-and-forth, notes for iterative work with clear milestones, sub-agents for complex research where parallel exploration pays off.

Worked budget (illustrative, not from the essay). A search agent with a 128k window spends 8k on system prompt and tools, then 0.5k0.5\text{k} of reasoning and a 3k3\text{k} result per step:

steps≈128−83.5≈34.\text{steps} \approx \frac{128 - 8}{3.5} \approx 34.

Clearing all but the last 3 results (older ones become 100-token stubs) makes each step cost about 0.6k0.6\text{k} on top of a constant 9k9\text{k}, so about (120−9)/0.6≈185(120-9)/0.6 \approx 185 steps. Sub-agents that each spend 40k and return 1.5k compress their exploration about 27×27\times. The price of clearing: a dropped result can only come back if the agent kept its identifier and re-fetches it.

Before (prompt engineering, pre-inference RAG)Context engineering
What is designedOne prompt, written onceThe whole window, re-curated every step
How data gets inTop-k chunks inserted before inferenceIdentifiers in context, data pulled in by tools when needed
Long tasksWait for a bigger windowCompaction, notes, sub-agents
What did not changeThe window size and the model; nothing here makes attention better
EvidenceProduct experience (Claude Code, Pokémon agent) and the external context-rot study; no controlled ablations in the essay

The essay reports design experience rather than measured results. The concrete, vendor-reported details are:

  • Claude Code compaction keeps a model-written summary plus the five most recently accessed files.
  • Sub-agents typically return 1,000–2,000 tokens after exploring with tens of thousands of tokens or more. The essay points to the multi-agent research system for a “substantial improvement” over single agents on internal research tasks.
  • Claude playing Pokémon keeps precise tallies over thousands of steps and continues from its own notes after context resets (a qualitative demonstration).
  • A file-based memory tool was released in public beta with the Sonnet 4.5 launch, and tool-result clearing is offered as a Claude Developer Platform feature.
  • No ablations. The essay does not measure how much each technique helps or what it costs. Whether compaction, notes or sub-agents win depends on the task, and each team must test it.
  • The mechanism is assumed. The attention-budget argument explains context rot plausibly but is not tested here; see the context rot page for the evidence it relies on.
  • Compaction is lossy in a way that is hard to see. The essay itself warns that a detail whose importance shows up only later is exactly what aggressive compaction drops.
  • Hand-designed vs. learned. Every policy here is written by engineers. Open question: can RL learn when to compact, what to write in notes and when to delegate, and does a learned policy transfer across tasks?

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    A search agent has a 128k-token window. System prompt and tool definitions use 8k. Each step adds 0.5k tokens of reasoning and a 3k-token search result. How many steps fit before the window is full? Now apply tool-result clearing that keeps the last 3 results raw and replaces older ones with a 100-token stub, and recompute. Finally, the lead agent instead delegates to sub-agents that each use about 40k tokens and return a 1.5k-token summary; with 20k reserved for the lead's own reasoning, how many sub-agent reports fit, and what is the compression ratio per sub-agent?

    What a strong answer covers
    • Without clearing: (128 − 8) / 3.5 ≈ 34 steps.
    • With clearing, the last 3 raw results take a constant 9k and each step otherwise costs 0.5k + 0.1k = 0.6k, so about (120 − 9) / 0.6 ≈ 185 steps, roughly 5× more.
    • Sub-agents: (120 − 20) / 1.5 ≈ 66 reports, each a 40k / 1.5k ≈ 27× compression of the exploration behind it.
    • The cost of clearing is that a stub cannot be re-read; the agent must re-run the search or keep a document id to fetch it again.
    • Compression helps only if the summaries keep what later steps need, which is exactly what the essay's recall-first tuning of compaction prompts aims at.
  2. Mechanism

    Explain how "just in time" context differs from pre-inference embedding retrieval: what the agent holds in its window, how the data gets in, what role file names, folder structure and timestamps play, and what the essay says this approach costs. Use Claude Code's hybrid of CLAUDE.md plus glob and grep as the example.

    What a strong answer covers
    • Pre-inference retrieval embeds the query and inserts top-k chunks before the model starts; the model cannot change what it got.
    • Just-in-time agents hold lightweight identifiers (file paths, stored queries, links) and call tools to load only the data they decide they need, at the step they need it.
    • Metadata is signal: a test_utils.py file inside tests/ means something different from one in src/core_logic/; names, folders and timestamps guide exploration, which enables progressive disclosure.
    • Claude Code loads CLAUDE.md up front (fast, always relevant) and uses glob and grep at run time, which avoids stale indexes.
    • The essay names the costs: exploration is slower than reading precomputed data, and without good tools and heuristics the agent wastes context on dead ends.
  3. Critique

    The essay motivates context engineering with an "attention budget": n tokens give n² pairwise relationships, training data has fewer long sequences, and position interpolation degrades position understanding. Critique this argument. Which parts are mechanism, which are analogy, and what experiment would actually show that adding irrelevant tokens hurts an agent?

    What a strong answer covers
    • n² is the cost of full attention, not a proof that quality falls with length; attention weights are normalised per query, so more tokens do not literally deplete a fixed budget.
    • The training-distribution argument (fewer long sequences) is plausible but not measured in the essay; the empirical support it cites is the external context-rot study.
    • The essay itself calls the effect a gradient rather than a cliff, and says some models degrade more gently than others.
    • A direct test: fix the task and the relevant evidence, add increasing amounts of irrelevant or distracting tool output, and measure accuracy, holding position of the evidence constant and varying it separately.
    • For agents, also measure behaviour (wrong tool choices, repeated searches), not just final answer accuracy.
  4. What if…

    The essay recommends tuning a compaction prompt first for recall (capture everything relevant from the trace) and then for precision (drop superfluous content). Design an evaluation that measures what compaction loses for a long-running research agent, and the ablations that compare tool-result clearing, full summarisation and structured notes.

    What a strong answer covers
    • Collect long agent traces, compact them at fixed points, and ask probe questions whose answers appear only in the compacted part of the trace (for example, which documents were already rejected and why).
    • Recall of compaction is the share of probes still answerable from the summary; precision is the share of summary tokens that support some needed probe or later action.
    • Downstream measure: resume the agent from each compacted state and compare task success, repeated searches and tokens to an uncompacted run with a larger window.
    • Arms: no compaction (truncation), tool-result clearing only, full summarisation, notes file only, and notes plus summarisation, at the same token budget.
    • The essay's warning to test for: details whose importance shows up only later are the ones aggressive compaction drops.
  5. Design

    Design the context policy for a deep-research agent working over the fixed BrowseComp-Plus corpus with a search tool and a get-document tool. Decide what is loaded up front, what is held only as identifiers, which long-horizon technique (compaction, notes, sub-agents) you use and when, and how you would check that the policy, not just more tool calls, explains any gain.

    What a strong answer covers
    • Up front: the question, a short tool guide and a few canonical example trajectories; no pre-retrieved documents beyond, at most, an initial search.
    • Identifiers: keep document ids and short snippets in the history, and fetch full documents only when a candidate needs checking.
    • Notes: a running list of the question's constraints, candidate answers and which documents verified or rejected each one, which survives compaction.
    • Sub-agents for independent sub-questions (one per constraint or candidate), each returning a short verified finding with document ids.
    • Compare policies at matched token and call budgets and report evidence recall against the corpus qrels, not just answer accuracy.
  6. Connect

    Recast the essay's techniques in IR terms. Map just-in-time loading, progressive disclosure, compaction and sub-agents to familiar retrieval ideas, and say for each where the analogy breaks because the consumer is an LLM with a finite window rather than a human reading a result page.

    What a strong answer covers
    • Just-in-time loading resembles lazy, pull-based retrieval on demand, versus pushing a fixed top-k into the prompt as classic RAG does.
    • Progressive disclosure resembles a search engine results page: snippets and metadata first, the full document only on a click.
    • Compaction resembles query-focused or extractive summarisation of a session; unlike a human, the agent cannot re-read what was dropped unless an identifier was kept.
    • Sub-agents resemble distributed or federated search with result merging, where each shard returns a compressed answer rather than a ranked list.
    • The analogy breaks on the reader: a human can skim and ignore noise cheaply, while for an LLM every token in the window can lower accuracy and adds cost.

Done with this page?

Status