How to design, build, and evaluate what your agent actually sees.
By Youssef Hosni
Published: 2026-09-12
URL: https://todatabeyond.substack.com/p/context-engineering-for-ai-agents-116
An AI agent can start with clear instructions and the right tools, yet struggle as a task progresses. Search results accumulate, tool calls return pages of data, and earlier assumptions remain in the conversation after new evidence has replaced them. At each step, the agent must work through this growing history to find what matters for its next decision. The reliability of that decision depends partly on how well the system manages the information it supplies to the model.
Context engineering is the practice of designing and managing that information. It determines what the agent sees at each step: which instructions remain active, which evidence is retrieved, where working state is stored, how history is compressed, and what gets delegated to a separate context. These choices shape the agent’s ability to use relevant evidence, maintain progress across sessions, and complete tasks within an acceptable cost and latency budget.
This guide takes you through the concepts, implementation, and evaluation of that process. We begin with the components of agent context, the ways context can fail, and four core operations: Write, Select, Compress, and Isolate.
We then build a research agent with the Claude Agent SDK, starting with a naive baseline and progressively adding persistent working state, selective retrieval, compression, and focused delegation. Finally, we evaluate those changes through instrumentation, stress tests, and ablations to understand which decisions help and what they cost.
The measurements also expose a trade-off: in the comparison presented here, the context-engineered agent reduced the payload reaching the lead model by 18%, but consumed 621% more tokens and cost 4.93 times as much. A smaller working context can introduce substantial overhead elsewhere in the system. Understanding that trade-off is part of the engineering work, and the evaluation section examines it directly.
By the end, you should be able to design an agent’s context pipeline, implement its core mechanisms, and measure whether the resulting architecture improves the dimensions that matter for your application.
All of the code and the captured measurement data behind every figure can be found in this GitHub Repo.
Get All My 9 Books With 60% Off
Table of Contents:
-
**Introduction
**1.1. What this guide covers
1.2. How the sections build on each other
1.3. What you should be able to do afterwards
-
Concepts, Failure Modes, and Core Strategies
2.1. What Context Engineering Is
2.2. Why Context Engineering Is Necessary
2.3. What Goes Into an Agent’s Context
2.4. How Context Fails
2.5. Write Context
2.6. Select Context
2.7. Compress Context
2.8. Isolate Context
2.9. Summary
-
Building a Production Agent with the Claude Agent SDK with Engineered Context
3.1. What We Are Building
3.2. Establishing the Naive Baseline
3.3. Write: Moving Working State Outside the Conversation
3.4. Select: Assembling a Bounded Working Set
3.5. Compress: Making Long Sessions Recoverable
3.6. Isolate: Delegating Focused Investigations
3.7. Isolating Heavy Tool Outputs in the Environment
3.8. Carrying Context Across Sessions
3.9. Assembling the Context-Engineered Agent
3.10. Comparing the Two Architectures
3.11. Summary
-
**Evaluating Context Engineering
**4.1. Why Outcome Success Is Not Enough
4.2. Instrumenting the Context Pipeline
4.3. Evaluating Write
4.4. Evaluating Select
4.5. Evaluating Compress
4.6. Evaluating Isolate
4.7. Stress-Testing the Four Failure Modes
4.8. Running Context Ablations
4.9. Building a Scorecard and Optimizing the Policy
4.10. From Naive to Engineered to Evaluated
-
**Conclusion
**5.1. What the measurements actually showed
5.2. What you can build now
5.3. Where to go next
Take the Context Engineering for AI Agents Course
If you prefer learning through guided code walkthroughs, my Context Engineering for AI Agents course covers these concepts in 8 self-paced lessons, with 2 hours and 12 minutes of video. We will build the research agent, implement the four context operations, and examine what the evaluation results reveal.
You’ll also get the 165-page technical book, slides, code repositories, and captured measurement data, with lifetime access and updates.
Context Engineering for AI Agents
1. Introduction
Context engineering is the discipline of controlling what information a language model sees at each step of an agent’s execution. Not what the application knows, and not what is available to it, but what actually reaches the model on the call being made right now. In a single-turn application that distinction barely matters, because the prompt and the context are close to the same thing. In an agent, they diverge immediately, and they keep diverging for as long as the run continues.
An agent accumulates. Over one task it may acquire instructions, a plan, retrieved documents, tool definitions, tool results, source metadata, intermediate claims, subagent reports, and every previous conversational turn. All of that competes for the same finite working memory, and every item that occupies space in it is an item the model must resolve against everything else. The engineering problem is deciding, repeatedly, which subset earns its place.
1.1. What this guide covers
The guide is organised in three sections that correspond to three distinct activities: understanding the problem, building boundaries that address it, and measuring whether those boundaries did their job.
Section 1 establishes the vocabulary. It defines context engineering, describes the four categories of information that enter an agent’s context, and sets out the four ways context degrades behaviour: poisoning, distraction, confusion, and clash. It then introduces the four operations used throughout the rest of the guide — write, select, compress, and isolate — and explains what each one is for, with published evidence for each.
Section 2 turns those four operations into code. It builds a technical research agent with the Claude Agent SDK twice: once as a naive baseline where everything accumulates in one conversation, and once as a context-engineered architecture where each operation owns a specific boundary. It ends by measuring both across three runs each and reporting the comparison, including how the engineered version performed worse.
Section 3 asks whether the information crossing those boundaries was the right information. It instruments the pipeline with context traces, builds labelled fixtures and deterministic graders for each of the four operations, stress-tests the four failure modes deliberately, runs ablations to establish which components actually contributed, and assembles the results into a scorecard that keeps the shape of the architecture it measures.
1.2. How the sections build on each other
The sections are cumulative and are best read in order. Section 2 assumes the vocabulary of Section 1: it refers to the four operations by name and expects the reader to recognise which failure mode a given boundary addresses. Section 3 evaluates the exact agent built in Section 2, reusing its configuration, its workspace layout, and its measurement layer.
That said, the three sections answer three questions that remain separable in practice. If you already have a working agent and want to know whether its context policy is sound, read Section 4 first, treating the earlier sections as reference. If you want the conceptual model without the implementation, Section 1 stands alone.
The running example throughout Sections 2 and 3 is a single deep-research agent, given one deliberately broad task: compare the main approaches for long-term memory in production AI agents and explain their trade-offs. The task was chosen because it requires papers, implementation documentation, repository evidence, and citation checks, which forces the agent to accumulate exactly the kinds of context this guide is about.
1.3. What you should be able to do afterwards
By the end, you should be able to look at a failing agent and identify which of the four failure modes is occurring; assign each of the four operations to a concrete boundary in your own codebase, with an owner and a testable invariant; instrument a run so that what the model received is recorded rather than inferred; and build a small labelled fixture that tells you whether a change to a retrieval or memory policy made the context better or merely smaller.
2. Concepts, Failure Modes, and Core Strategies
An agent can only reason over the information present in its context window. A document sitting in a database, a memory saved during a previous session, or the result of a tool call made twenty steps ago is invisible to the model unless the application deliberately places it there. Everything an agent appears to “know” is the product of a decision, made by code, about what to include on this particular call.
This section is about making those decisions explicitly. It defines what context engineering is, breaks down the categories of information that compete for space inside the window, examines the four characteristic ways that competition goes wrong, and introduces the four operations used to control it. Sections 2 and 3 implement and then measure those operations; this section establishes what they are for.
What this section covers
-
What context engineering means, and why a larger context window does not remove the need for it.
-
The four sources of context in an agent — instructions, knowledge, tool feedback, and state — and how each one grows.
-
Four failure modes: context poisoning, distraction, confusion, and clash, with documented evidence for each.
-
Four operations for controlling context: write, select, compress, and isolate, and the trade-off each one carries.
2.1. What Context Engineering Is
Context engineering is the art and science of filling the context window with the right information at each step of an agent’s trajectory. A useful mental model is to treat the language model as a processor and the context window as its working memory. The model computes over whatever is in that memory and cannot reach anything outside it. Everything else — files, databases, memories, tool catalogues, previous sessions — exists in storage until some part of the system loads it in.
The limitation that matters is that this working memory is finite, and that filling it does not improve results by itself. Irrelevant, duplicated, outdated, or poorly structured content makes it harder for the model to identify what actually bears on the current decision. The system therefore has to make a set of choices continuously: what should be added, what should be retrieved only when needed, what should be compressed, what should stay outside the window entirely, and what should be removed once it has stopped being useful.
Figure 1. General categories of context engineering: write, select, compress, and isolate, with the mechanisms belonging to each.
For an agent, these decisions recur at every step. The context needed to draw up a plan is different from the context needed to execute a tool call, inspect its result, recover from an error, or write a final answer. Context engineering is therefore not a single act of prompt design performed once, but a policy that runs for the length of the trajectory.
Key concept. Context engineering is the discipline of controlling what information a language model sees at each step of an agent’s execution — not what the system knows, and not what is available, but what actually enters the window on this call.
The framing is not unique to any one team. Cognition has described context engineering as effectively the primary job of engineers building AI agents, and the emphasis is consistent with what production work looks like in practice: comparatively little time spent on the wording of instructions, and a great deal spent on deciding which state is loaded, when, and in what form.
2.2. Why Context Engineering Is Necessary
In simple applications, assembling context is straightforward. A user supplies a prompt, the application prepends a system instruction, the model responds.
Once the application becomes an agent, the volume of potentially useful context grows quickly. Within a single task, an agent may accumulate instructions, conversation history, retrieved documents, tool definitions, tool outputs, plans, intermediate results, memories, errors, and observations from its environment. After a handful of steps, there is already far more available than the model needs for its next decision.
Figure 2. Context types commonly used in language model applications. Instructions, knowledge, and tools all funnel through one finite window.
The obvious response is to put everything in. Larger context windows appear to make that viable, and there is a persistent argument that retrieval is no longer necessary now that models accept a million tokens or more. That argument does not survive contact with a long-running agent, for four reasons.
First, capacity remains finite. The ceiling moves but does not disappear, and what an agent accumulates grows with the length of the trajectory. An agent performing extended reasoning can consume a very large window within hours, because reasoning traces are themselves context.
Second, models do not use every position in a long context equally well. The lost in the middle study examined how model performance varies with the position of relevant evidence inside a long input. Performance was strongest when the necessary information appeared at the beginning or the end of the context, and degraded when it sat in the middle — and the effect persisted in models built for long inputs. Capacity and usable capacity are different quantities.
Key concept. Lost in the middle. Placing relevant evidence inside a long context does not guarantee the model will use it. Retrieval accuracy depends measurably on where in the context the evidence sits, with material in the middle of a long input recovered least reliably.
Third, irrelevant information competes with useful information. Observations go stale, sources contradict one another, and a tool result of several thousand lines may matter for one of them. Fourth, cost and latency scale with what is resent. Every step of an agent re-transmits the accumulated context, so growth compounds across the trajectory rather than being paid once.
Takeaway. The objective is not to maximise context. It is to construct the smallest useful context that lets the model make the next decision correctly.
A practical corollary is that a large window is not permission to maintain a large history. Windows give capacity; context engineering decides how that capacity is spent.
2.3. What Goes Into an Agent’s Context
Most agent applications assemble context from four categories. Separating them is useful because each grows for different reasons and each is controlled by a different mechanism.
Figure 3. The four sources that contribute to an agent’s context and the difference between accumulating them and engineering them.
A. Instructions
Instructions define how the model should behave. They include system and developer prompts, task-specific instructions, policies and constraints, few-shot examples, output-format requirements, tool descriptions and schemas, and procedural memories such as a project instruction file. For agents, these matter doubly, because they shape both reasoning and action selection. Instructions tend to be stable within a run, which makes them easy to overlook as a source of context cost even though they are re-sent on every call.
B. Knowledge
Knowledge is the information the model reasons about, as opposed to the directions it follows. Retrieved documents, database records, search results, knowledge-base passages, organisational or user memory, domain facts, and text extracted from files all belong here.
Retrieval-augmented generation is the familiar example of context engineering at this layer. Rather than placing an entire knowledge base into the prompt, a retrieval system selects a small subset relevant to the current request and supplies only that. The generation step then reasons over the selected passages. The retrieval half of that pattern — deciding which passages enter the context — is what this guide is concerned with; the generation half is unchanged.
C. Tool Feedback
When an agent interacts with external systems, those systems produce new context. A search returns results, a file read returns contents, a test run returns output, a database query returns rows, code execution returns standard output and errors. These observations are frequently essential to deciding what to do next.
They are also the largest single source of unplanned context growth. A command may return five thousand lines when one error message is what matters. Context engineering therefore governs not only which tool is called but how much of its result remains available afterwards. Section 2 shows a tool whose implementation is three lines and whose return contract dominates the context for the rest of the run.
D. Agent State and History
Agents operate across many steps and need a representation of what has already happened: conversation history, the current plan, completed and pending tasks, intermediate results, previous decisions, execution state, scratchpad contents, and summaries of earlier phases.
Without persistent state, an agent rediscovers information it already had. Keeping the entire trajectory verbatim creates the opposite problem, in which the context becomes dominated by history. The engineering question is which parts of state should remain active, which should be summarised, and which should move outside the window entirely.
These four sources compete continuously for the same space and the same attention. Over a long trajectory, and without intervention, the context window becomes an append-only log of everything that has happened.
2.4. How Context Fails
Reaching the model’s token limit is only one possible failure, and not the most interesting one. Long-running agents become slower and more expensive as context grows, but the quality of the context can degrade behaviour well before the window is full.
LangChain groups the common failure modes into poisoning, distraction, confusion, and clash, following a taxonomy described by Drew Breunig. These matter more for agents than for single-turn applications because the output of one model call becomes part of the input to the next. Errors do not simply occur and pass; they persist and compound.
Figure 4. The four common context failure modes.
A. Context Poisoning
Context poisoning occurs when incorrect information enters the context and is subsequently treated as reliable.
Figure 5. Context poisoning. An incorrect conclusion is saved, then reused, and the error becomes self-reinforcing.
Suppose an agent concludes early in a run that a particular API endpoint does not exist, and records that conclusion in its plan. Several steps later, it reads its own state and acts on it. The original hallucination has become part of the agent’s working knowledge. The loop is: incorrect observation, saved state, future reasoning, incorrect action, and further context that appears to support the error.
Google DeepMind documented this behaviour while studying Gemini 2.5 Pro playing Pokémon. In some runs, incorrect information about the game state entered summaries and goals. Once those parts of the context were contaminated, the model could fixate on impossible objectives and pursue them repeatedly.
The same pattern appears in ordinary applications. A coding agent may misdiagnose the source of a bug and then interpret every later test failure through that diagnosis. A research agent may save an unsupported claim into its notes and later cite the note as evidence. A planning agent may mark a prerequisite as complete when it is not.
Key concept. Persistent context gives errors persistence. Once information moves from a tentative model output into memory, a summary, a plan, or state, later calls may no longer distinguish it from information that was actually verified.
B. Context Distraction
Context distraction occurs when accumulated history begins to dominate the model’s next decision, making it harder to synthesise a fresh strategy from the current task.
Figure 6. Context distraction. The current task signal is overshadowed by a long history of prior actions and observations.
Consider an agent that has attempted ten approaches to a problem. If every previous action, observation, failure, and explanation remains active, the model does not receive a clean problem at step eleven. It receives the problem together with a substantial record of its own past behaviour. That record can be useful, and it can also anchor the model to strategies it has already exhausted.
The Gemini Pokémon work again provides an observation. Although the model supported a context window well beyond 100,000 tokens, the researchers noted that once the agent’s context grew significantly past roughly that figure in that particular setup, it became more likely to repeat actions from its history than to form new plans. The report describes this as anecdotal rather than as a universal threshold, and the distinction matters: the effective limit depends on the model, the task, the structure of the context, and the kind of reasoning required.
This also separates two capabilities that are easy to conflate. A model may be entirely capable of finding a specific fact buried in a large document while still struggling to reason over a long trajectory containing plans, failed attempts, observations, and changing state. Long-context retrieval and long-horizon reasoning are not the same skill, and benchmarks for the first do not predict the second.
C. Context Confusion
Context confusion occurs when irrelevant or unnecessary context influences the model’s reasoning and leads it to a lower-quality response. Nothing in the context is wrong; there is simply too much that does not bear on the current decision.
Figure 7. Context confusion. Irrelevant material competes for attention with the material that matters.
Tool exposure is the clearest example. Suppose an agent has access to eighty tools and the current task requires three. A naive implementation places the descriptions and schemas of all eighty into every model call. The context technically contains everything the agent might need, and it also contains dozens of competing actions with no bearing on the task.
The cost is not only attention. Every tool definition carries a name, a description, an input schema, parameter descriptions, and usage notes, and all of it is re-sent on every request. In one consulting engagement, I reviewed an agent with roughly 136 tools whose definitions came to about 10,000 tokens per call. Ten calls consumed 100,000 tokens on tool definitions alone, before any actual work. The system was intended for interactive use, so that overhead appeared on every user turn.
The same problem arises with retrieved documents, memories, examples, and instructions. A retrieval system may return ten passages when two carry the evidence. A memory system may surface an old preference unrelated to the request. It is worth being precise about the claim: modern models can ignore irrelevant information to a degree. The engineering difficulty is that we cannot assume they will ignore the right things.
Tool-use benchmarks exist partly because this is a real capability rather than an assumption. Berkeley’s Function-Calling Leaderboard evaluates how reliably models select the appropriate function from a set of candidates, including cases with multiple plausible options and cases where no available function applies. Choosing correctly from a large tool surface is itself something models do with varying success.
Key concept. Available context and useful context are not the same thing. Every additional tool, document, example, memory, or instruction increases capability and also introduces another signal the model must resolve.
D. Context Clash
Context clash occurs when two pieces of active context directly contradict one another. It is confusion’s more damaging relative, because the competing items are not merely irrelevant.
Figure 8. Context clash. Older and newer versions of the same fact remain active simultaneously, and nothing marks which one supersedes the other.
Suppose the start of a trajectory records that the deployment environment is Python 3.10. Later, a tool inspects the production environment and reports Python 3.12. If both remain active with no indication that the newer observation supersedes the older one, the model receives two plausible and incompatible versions of reality, and the system has silently delegated the decision about which one wins.
Clashes arise between almost any pair of sources: an old instruction against a revised one, a memory against retrieved evidence, a previous tool result against the current one, saved state against the actual environment, or one document against another.
They also arise naturally in multi-turn interaction. Research from Microsoft and Salesforce examined what happens when the same information is revealed incrementally across a conversation rather than supplied in one complete prompt.
Across their tasks and tested models, performance fell by an average of 39% in the multi-turn setting. One contributing mechanism was that models attempted an answer early and then continued to rely on that attempt even after receiving information that undermined it.
This is directly relevant to agents, which rarely receive a fully specified task and execute it once. They gather evidence, call tools, revise plans, and learn things that invalidate earlier assumptions. Appending both versions leaves the model to arbitrate. A better system makes the relationship explicit: update the state, mark the older item as stale, preserve provenance, or remove superseded context.
Table 1, Context Failure Modes and the Operations That Address Them, summarises the four modes and the operation that primarily addresses each. The operations themselves are the subject of the rest of this section.
Table 1. Context Failure Modes and the Operations That Address Them
2.5. Write Context
Writing context means persisting useful information outside the model’s active window so that the agent can retrieve it when it becomes relevant again. The idea is straightforward: an agent should not have to keep every plan, observation, decision, and intermediate result inside the window merely because it might need them later. It can write them to external storage and keep only a lightweight reference — a filename, a memory key, an identifier, or a short summary — in active context.
This separates what the agent knows from what the model needs to see now. The distinction becomes important for long-running work. A coding agent may run for hours and generate thousands of lines of tool output; a research agent may inspect hundreds of sources. Retaining all of it in the window produces exactly the poisoning, distraction, confusion, and clash problems described above.
Anthropic describes a version of this as structured note-taking: agents periodically write notes to memory outside the context window and retrieve them later. Their examples include Claude Code maintaining a to-do list, and an agent maintaining a notes file to preserve state across many tool calls.
Writing context takes two forms, distinguished by lifetime: scratchpads scoped to the task currently being executed, and long-term memories that survive across tasks and sessions.
A. Scratchpads
A scratchpad is task-scoped external working memory. It holds information useful for completing the current trajectory without necessarily becoming permanent knowledge.
Figure 9. A scratchpad as external working memory. The agent writes what it will need later and retrieves only the part required for the current step.
A scratchpad typically contains the current plan and completed steps, intermediate findings, unresolved questions, important tool results, assumptions still awaiting verification, filenames or URLs discovered during the task, and a running summary of progress.
Consider a coding agent performing a repository migration. Rather than carrying every previous terminal output and file inspection, it maintains a plan file:
PLAN.md
Goal: migrate authentication to the new API
Completed:
- Located authentication middleware
- Updated token validation
- Migrated user service
Pending:
- Update integration tests
- Check refresh-token handling
Important:
- Auth middleware: src/auth/middleware.ts
- Old endpoint still used in tests/auth.integration.ts
The full execution history behind that state might run to tens of thousands of tokens. The scratchpad preserves what is needed to continue, at a cost of roughly ninety. Note what it does not contain: no copied conversation, no raw tool output, no narrative. Every line is a conclusion, a pointer, or an outstanding item.
Anthropic encountered the same requirement while building their multi-agent research system. The lead researcher creates a plan and saves it to memory so that it survives even if the active context is later truncated.
Their description is direct: the lead researcher begins by thinking through the approach and saving its plan to memory to persist the context. For very long trajectories, they report agents summarising completed phases, storing essential information externally, and retrieving it when needed.
A scratchpad does not require sophisticated infrastructure. Three implementations are common. The first is files: NOTES.md, PLAN.md, PROGRESS.md, with the agent given tools such as writenote(), readnote(), and update_plan(), deciding for itself when information should move between the window and the artifact.
The second is runtime state, where scratchpad contents live in the agent’s state object; LangGraph treats thread-scoped short-term memory this way and can persist it through checkpoints so a thread resumes later. The third is a dedicated memory store with keys, namespaces, and scopes, which becomes worthwhile once entries must be queried or versioned.
The important property is not the storage format. It is that the information does not have to occupy the model’s active context continuously.
B. Long-Term Memory
Scratchpads maintain continuity within a task. Some information remains useful after the task ends, and that is where long-term memory applies. A long-term memory system persists information across conversations, threads, or runs and retrieves it when relevant. LangGraph draws this distinction explicitly, separating thread-scoped short-term state from long-term memory stored across threads.
Figure 10. Long-term memory persisting across sessions. A fact written during one session is retrieved in a later session.
Suppose a coding agent learns during one session that a repository uses pytest rather than unittest, or an assistant learns that a user prefers technical explanations with runnable examples. These facts remain useful weeks later. Persisting them avoids rediscovering the same thing on every run.
An important development in agent memory is allowing the model to decide what is worth remembering: the agent inspects an interaction, extracts the durable information, and writes an updated memory. The update may happen during the interaction, on what is sometimes called the hot path, or asynchronously in the background afterwards. LangChain’s memory architecture supports both.
Earlier research explored the same pattern. The Reflexion work introduced agents that generate verbal reflections from task feedback and store them in an episodic memory buffer, retrieving those reflections on later attempts to improve decisions without changing model weights.
The Generative Agents work went further, maintaining a stream of an agent’s experiences, retrieving relevant memories dynamically, and periodically synthesising groups of experiences into higher-level reflections that influence later planning.
The shared shape is: raw experience, extraction or reflection, useful memory, external storage, retrieval when relevant. The goal is not to turn an entire conversation history into permanent memory, which would move the overload problem from the prompt into the memory store. The system has to decide what deserves to survive.
It is also useful to distinguish what is being remembered. Table 2 sets out the three categories in LangChain’s taxonomy.
Table 2. The three categories of long-term agent memory.
The distinction is practical rather than taxonomic: the type tells you when a memory should be retrieved. A coding agent may need a procedural memory before modifying a file, a support agent an episodic one when handling a familiar problem, and a personal assistant a semantic one about a user preference.
These mechanisms already ship in products. ChatGPT carries relevant information from previous conversations into later ones, maintaining and updating a synthesis of useful context, with saved-memory controls for explicit management.
Windsurf’s Cascade creates workspace-scoped memories during conversations and retrieves them later when it judges them relevant. Cursor provides persistent memory for its Automations, where agents read and write named memory entries across runs; for ordinary agent behaviour, its documentation emphasises persistent rules as reusable context.
Claude Code uses a project instruction file as a procedural memory loaded when its scope applies, a mechanism Section 2 uses directly.
Get all my 10 AI Courses with 60% off
C. The Risk in Writing Context
Moving information outside the window does not make it trustworthy. Writing a hallucination into long-term memory creates persistent context poisoning that outlives the session that produced it. Storing a new fact without replacing an outdated one creates a context clash for the next retrieval that surfaces both.
A write system therefore has to answer a set of questions that a simple append-to-memory design does not: what should be written, who or what produced it, whether it has been verified, how long it should live, whether it should replace an existing memory, and whether its scope is this task, this project, this user, or every future session.
Takeaway. Context writing and context retrieval are tightly coupled. Write selectively, record provenance and scope, and retrieve only the memories that bear on the current step. Section 3 measures exactly this, as write precision and write recall.
2.6. Select Context
Selecting context means pulling the right information into the window at the moment the agent needs it. Writing information outside the window solves half the problem; once plans, memories, documents, and tool definitions live elsewhere, the system needs a mechanism for deciding what comes back.
Loading everything that has been stored simply recreates the overload the writing was meant to avoid. Selection instead treats the active window as a limited working set and continuously chooses a subset according to the current task, the agent’s state, and the next action.
The operative word is relevant. Something can be useful to the agent overall without being useful for the current step. A database schema matters when constructing a query and not when writing the final explanation. A debugging note matters while investigating a failing test and not after it is resolved. A memory about a user’s preferred programming language matters for a coding task and not when the same user asks for a restaurant recommendation.
Figure 11. Selecting the active working set. Many available items become a few relevant items, and only those reach the window.
A. Selecting from a Scratchpad
How a scratchpad is read depends on how it is implemented. If it is file-backed or exposed through a tool, the agent can request information explicitly when it needs it — reading a plan file, reading a progress file, searching notes for a particular term. The scratchpad stays outside the window for most of the trajectory, and only the contents actually requested are added to the next call.
Anthropic describes this broader pattern as just-in-time context retrieval: agents retain lightweight references such as file paths and stored queries, then load the underlying information dynamically when required. Their memory tool follows the same model, with memory files persisting outside the active conversation and the model reading the relevant ones on demand rather than loading an entire memory directory into every window.
If the scratchpad lives in the application’s runtime state, the developer gains finer control. The complete state might contain a plan, completed steps, research notes, tool history, errors, and artifacts, but there is no requirement to expose that whole object to the model. At one step the model might receive the plan and the current error; at another, the research notes and the pending questions.
Key concept. The application’s state can be much larger than the model-visible state. That separation is what gives the developer deterministic control over which fields consume tokens at each step.
B. Selecting from Memory
Selecting long-term memories is harder because the store grows across sessions. Imagine an assistant that has recorded a preference for aisle seats, a primary language of Python, a preference for concise email, a particular cloud provider, and dozens of similar facts. All are valid. None should appear in every conversation.
Relevance is task-dependent. Debugging Python makes the language preference relevant; booking a flight makes the seat preference relevant; the rest should stay outside the window. Memory retrieval is therefore not simply a matter of finding what is semantically related to a query. The system must also judge whether a memory is appropriate, current, and useful for the task being performed.
That distinction matters because a retrieved memory can be factually correct and still be the wrong context. Simon Willison demonstrated the point at the AI Engineer World’s Fair: he asked ChatGPT to modify an image of his dog, and the system incorporated location information remembered from earlier interactions. The memory was not incorrect. It was retrieved into a context where the user had neither expected nor requested it.
Good memory selection therefore balances recall against precision. Embedding similarity is one useful signal, and practical systems also weigh recency, memory type, scope, importance, and relationships between stored items. The objective is not to retrieve as many potentially relevant memories as possible, but to retrieve the few that should influence the current decision.
C. Selecting Tools
Tools present the same problem. An agent with five tools can receive all five definitions without difficulty. Production agents may have access to dozens or hundreds of APIs, servers, database operations, and internal services.
Tool definitions consume context directly, and there is also a reasoning cost: many tools perform related operations, and their descriptions overlap, so as the catalogue grows, the model must distinguish between more candidate actions before it can choose.
The remedy is to separate the tools the agent can access from the tools currently shown to the model. The full catalogue stays outside the active context; a retrieval layer examines the current task, identifies a small number of relevant tools, and supplies only those definitions. This is retrieval applied to tool definitions rather than to documents.
Figure 12. Without selection, the full catalogue and knowledge base are pushed into the window. With selection, only the relevant items are shown.
Research on tool retrieval supports the approach at scale. RAG-MCP retrieves a small subset of available tools before the model performs selection; in its reported benchmark, this raised selection accuracy from 13.62% to 43.13% while substantially reducing prompt tokens.
The exact figures are specific to that benchmark, and the general result is that tool retrieval becomes valuable as catalogues grow. Section 3 measures this directly on a fifty-tool catalogue and finds that enabling the feature is not the same as the feature taking effect.
D. Selecting Knowledge
Knowledge retrieval is the most familiar form of selection because it is the foundation of retrieval-augmented generation. The underlying source may contain millions of tokens of documentation, source code, research papers, database records, or web content, and the model needs a small amount of it.
Indexing information and selecting context are different problems. A system may successfully index every file in a repository and still supply poor context if it retrieves the wrong functions for the current task.
A document retrieval system may have excellent coverage and still fail if the relevant passage is ranked below several superficially similar ones. Varun Mohan of Windsurf put the distinction concisely: indexing code is not context retrieval.
Code agents illustrate the scale problem well. A repository may hold thousands of files and millions of lines while a particular bug depends on three functions across two files.
Retrieval there tends to combine signals: semantic similarity identifies conceptually related code, lexical search finds exact identifiers and error messages, and repository structure, imports, recently edited files, and reranking contribute further. The number of techniques matters less than whether the system is optimised for finding the code that belongs in the window now.
The same principle applies outside code. A research agent should retrieve the evidence for the claim it is currently investigating rather than carrying every source collected so far. A support agent should retrieve the page relevant to the current problem rather than an entire manual.
Takeaway. Retrieval quality becomes context quality. Missing an important source leaves the model without evidence; retrieving too much creates confusion or distraction; retrieving stale material creates clash.
2.7. Compress Context
Compressing context means retaining only the tokens required to perform the task. Two mechanisms are in common use, and they differ in cost and in risk.
A. Summarization
Agent interactions can span hundreds of turns and include token-heavy tool calls. Summarization is the usual response. Claude Code runs an automatic compaction once a session passes 95% of the context window, summarising the full trajectory of interactions; the strategies used for this can be recursive or hierarchical.
Summarization can also be placed deliberately rather than left to trigger at a threshold. Post-processing token-heavy tool calls is a common case: a search tool returning thousands of tokens can be summarised before its result ever enters the trajectory. In one system I worked on, an agent issued database queries that could return very large result sets when only a few aggregate facts were needed. Inserting a summarising step between the query tool and the main agent kept the trajectory small without losing the answer.
Figure 13. Context summarization. A long trajectory is reduced to a goal, key decisions, important findings, and pending work, while the raw material is archived.
Cognition has described summarization at agent-to-agent boundaries to reduce tokens during knowledge handoff, using a fine-tuned model for the task, which indicates how much engineering can go into this step when specific events or decisions must survive.
A worked example: a research agent performs twenty web searches and accumulates thousands of tokens of results. Rather than carrying every result forward, the system summarises the completed phase into main findings, supporting sources, unresolved questions, and important contradictions. The raw results remain outside the active context while the compact summary continues with the agent.
The principal risk is information loss. A summary that is too aggressive may remove a decision or observation whose importance becomes apparent only later. Anthropic’s recommendation is to optimise compaction for recall first and make summaries more selective afterwards.
B. Trimming
Trimming removes context that is unlikely to remain useful, rather than rewriting it into a shorter form. It can usually be done with deterministic rules rather than another model call, which makes it free, predictable, and testable.
Figure 14. Context trimming. Old tool output and stale search results are removed, while the task, decisions, findings, and current state survive.
Typical rules remove old tool outputs, discard intermediate search results once their findings have been recorded, or retain only the most recent messages from a repetitive exchange. Anthropic specifically identifies old tool calls and results as good candidates for removal: once the useful information from a result has been incorporated into state, keeping the raw payload deep in the conversation adds little.
A concrete case is a coding agent running a test suite repeatedly. If five runs each produce two thousand lines of output, the agent does not need all ten thousand lines after the latest run. The application can retain the most recent result, the important error messages, and any recorded decisions while removing the older raw outputs.
In practice, the two techniques are used together, chosen per source. Tool outputs whose content matters get summarised; tool outputs whose conclusions have already been recorded get trimmed.
2.8. Isolate Context
Isolating context means splitting it so that unnecessary state never enters a particular model call. Where selection decides what to bring in, isolation arranges for some things never to be candidates.
A. Multi-Agent Isolation
The most common form is splitting work across subagents. Separation of concerns was a motivation for OpenAI’s Swarm library, in which a team of agents handles specific sub-tasks, each with its own tools, instructions, and context window.
Figure 15. Splitting context across multiple agents. A shared plan coordinates them; the context windows stay separate.
Anthropic’s multi-agent research system makes the case directly: many agents with isolated contexts outperformed a single agent, largely because each subagent’s window could be allocated to a narrower sub-task. Their description is that subagents operate in parallel with their own context windows, exploring different aspects of the question simultaneously.
There is a second benefit that is easy to overlook. A single agent that does everything is difficult to evaluate, because a failure cannot be localised. Splitting the work into specialists with defined inputs and outputs makes each boundary observable, which is a precondition for the evaluation work in Section 4.
The costs are real. Anthropic reports token use up to fifteen times that of chat for their multi-agent configuration. Sub-agent work needs careful prompt engineering to plan; coordination overhead is non-trivial, and specialists can produce incompatible terminology that the lead must reconcile. Model selection per subagent is a related lever: not every specialist needs the strongest available model, and matching model capability to sub-task is where much of the cost management in a multi-agent system happens.
B. Isolation Using Execution Environments
Most agents use tool-calling APIs that return structured arguments, which the runtime passes to a tool, and the tool’s output returns to the model. Hugging Face’s Deep Researcher takes a different approach with a code agent: the model emits code containing the desired tool calls, the code runs in a sandbox, and only selected values return to the model.
Figure 16. Sandboxes isolate context from the model. Large objects stay in the execution environment, and only return values cross back.
This is particularly effective for token-heavy objects. As Hugging Face put it, code agents allow better handling of state: an image, an audio file, or another large object can be assigned to a variable in the environment and used later without ever entering the model’s context.
C. State as a Context Boundary
An agent’s runtime state can isolate information from the model without discarding it. The distinction is between what the application knows and what the model sees. An agent may maintain a rich state object containing conversation history, plans, intermediate results, tool outputs, artifacts, counters, and errors, while only a subset of those fields is placed into context at each step.
Figure 17. Runtime state as a gate. The application holds everything; only selected fields are exposed to the model.
LangGraph treats state as mutable data that persists during a run and can hold conversation history, intermediate results, and values produced by tools or model calls. Nodes read and update this shared state while the application controls which values are used to construct model context, and a particular node can be sent a different state payload rather than the whole graph state.
Consider a coding agent that runs a test suite and receives five thousand lines of output. Rather than appending the entire result to every subsequent call, the runtime stores the raw output in state and the next call receives only the failing test names and the current error. If the complete output is needed later, the relevant state can be exposed again.
This differs from deleting or summarising. The data still exists, unchanged; it is simply outside the model-visible portion of state until it becomes useful.
Key concept. Keep the full execution state in the application and expose only the fields required for the model’s current decision. This gives deterministic control over context boundaries, without a summarisation step and without loss.
2.9. Summary
A larger context window does not remove the need for context engineering. Agents can access far more information than the model should process at any given moment, and accumulating everything eventually introduces noise, stale information, conflicts, higher cost, and weaker reasoning.
Four sources feed an agent’s context — instructions, knowledge, tool feedback, and state — and each grows for its own reasons. When their growth is unmanaged, four failure modes follow. Poisoning occurs when a wrong fact becomes working knowledge and compounds. Distraction occurs when accumulated history crowds out the current task. Confusion occurs when irrelevant material competes for attention. Clash occurs when contradictory items are both active with nothing marking which supersedes the other.
Four operations address them. Writing preserves useful information outside the window. Selection brings relevant information back at the moment it is needed. Compression reduces what must remain active, through summarisation or through deterministic trimming. Isolation keeps unnecessary information out of a particular call entirely, through subagents, execution environments, or state boundaries.
Each operation carries a cost. Writing requires deciding what deserves to persist, and writing the wrong thing creates durable poisoning. Selection requires a retrieval policy, and a poor one degrades context quality directly. Compression risks losing a detail whose importance appears later. Isolation multiplies token consumption and adds coordination overhead. None of these is free, and none should be adopted without knowing what it buys.
Section 2 implements all four against a single research agent and measures what each one costs.
Get All My 9 Books With 60% Off