Context Engineering for Production AI Agents

Compaction, tool-result clearing, persistent memory, and sub-agent isolation — the primitives that keep a long-running agent from degrading as its context window fills.

Yash Amin
12 min

The short answer

A long-running agent doesn't fail because its context window is too small — it fails because the window fills with low-signal tokens that crowd out the ones that matter. Context engineering is the discipline of deciding what stays, what gets summarized, and what gets moved out entirely, across the full lifetime of an agent's run, not just its first prompt. Anthropic now ships this as literal API primitives, not just prompting advice.

What Context Engineering Actually Is

Anthropic's own engineering team frames it as the successor discipline to prompt engineering: prompt engineering is writing and organizing instructions for optimal outcomes, while context engineering is the set of strategies for curating the optimal set of tokens during inference — including everything that lands in the context window outside the prompt itself. LangChain, independently, converges on the same framing. Both treat it as a per-session, inference-time concern, not a training-time one.

Context engineering includes:

  • System prompt and tool-definition design as they evolve during a long-running session, not just their initial authoring
  • Techniques that reduce or reorganize accumulated context: compaction, tool-result clearing, structured note-taking, just-in-time retrieval
  • Cross-session persistent memory — a file-backed store an agent reads and writes across separate conversations
  • Multi-agent context isolation — giving a sub-agent a clean, focused window and returning only a condensed result to the orchestrator

It does not include prompt wording and few-shot examples (a prerequisite skill, not the same discipline), model fine-tuning, or Retrieval-Augmented Generation as a whole system — RAG's retrieval step is one input to context engineering, not the discipline itself.

Why This Discipline Exists: Context Rot

The load-bearing fact behind every technique in this guide: longer context is not free accuracy. The original "Lost in the Middle" study (Liu et al., Stanford/UW) found model accuracy on multi-document QA and key-value retrieval is highest when relevant information sits at the start or end of the context, and degrades measurably when it's buried in the middle — even in models built for long context. Anthropic's current framing calls the general version of this context rot: as token count in the context window increases, a model's ability to accurately recall information from it decreases. A follow-up 2026 study on long-horizon search tasks confirmed the pattern holds under controlled, extreme context growth, not just in the original benchmark setting.

The goal of every primitive below is never "fit more in" — it's keeping the smallest set of high-signal tokens that gets the desired behavior.

0
named failure modes: poisoning, distraction, confusion, clash
0
performance drop when info is split across turns vs. given at once
0
tokens a sub-agent should return to its orchestrator, not its full context

Four Named Ways Context Fails

Independent researcher Drew Breunig's widely-cited analysis names four distinct ways long context degrades agent behavior, each with a documented example:

  • Context poisoning — a hallucination or error gets embedded in context and is repeatedly referenced, compounding. A Gemini agent playing Pokémon hallucinated game-state details into its own goals section, then pursued unreachable goals built on the false premise.
  • Context distraction — past roughly 100K tokens, the same agent showed a measured tendency to repeat prior actions from its own history instead of reasoning fresh.
  • Context confusion — superfluous information gets incorporated into responses it shouldn't influence. A quantized Llama 3.1 8B model failed a tool-use benchmark when given all 46 available tools, but succeeded when given only the 19 relevant ones.
  • Context clash — conflicting information introduced at different points causes the model to act on an early, later-contradicted assumption. A Microsoft/Salesforce study found a 39% performance drop when benchmark information was split across multiple turns instead of given all at once.

Every primitive below exists specifically to prevent poisoning and distraction by keeping stale or wrong tokens from persisting, and confusion or clash by keeping irrelevant or conflicting tokens out in the first place.

Compaction, Clearing, and Memory: Choosing the Right Primitive

These three mechanisms solve different bottlenecks and are meant to be composed, not chosen exclusively. Anthropic's own cookbook demonstrates stacking clearing and compaction in a single request, with memory integrated separately — the production pattern is diagnosing which bottleneck is actually active, not picking one primitive as a universal fix.

ProblemPrimitiveCostWhat's lost
Long dialogue nearing the window limitCompactionAn inference pass (summarization)Fine detail; high-level facts survive
Tool-result accumulation dominating tokensTool-result clearingNone — zero-inference server-side editNothing permanent; re-fetch if needed again
Knowledge that must persist across sessionsMemory toolTool-call overhead (file I/O)Nothing inherent — depends on note quality

Compaction takes a conversation nearing the window limit, summarizes its contents, and reinitiates a new window with the summary. It's lossy on obscure specifics — a poor fit for tasks where exact prior wording matters. Tool-result clearing removes bulky, re-fetchable tool results while preserving the record that the tool was called, freeing tokens with zero inference cost — the agent just has to re-call the tool if it later needs the cleared content. Structured note-taking writes to external, file-backed storage outside the context window and reads it back later; quality depends entirely on the agent's own note-taking discipline.

Sub-Agent Isolation

A fourth pattern operates at the architecture level rather than the single-agent level: give a specialized sub-agent a clean, narrow context window for one focused task, and have it return a condensed summary — Anthropic's own guidance is roughly 1,000-2,000 tokens — to the coordinating agent, rather than its full working context. Use this when a task needs deep, wide exploration (research, parallel search) that would otherwise flood the main agent's context. The failure mode is information loss at the summary boundary: whatever isn't captured in the returned summary is gone from the orchestrator's view.

Reference Architecture

A minimal context-engineered agent, layered by when each mechanism activates:

  • Baseline. Start with the smallest set of high-signal system prompt and tool definitions that gets the desired behavior, before any of the below is needed.
  • Just-in-time retrieval. Keep lightweight identifiers (file paths, IDs) in context and load actual data at the point of use, rather than pre-loading everything upfront.
  • Tool-result clearing (mid-session). As tool-result tokens accumulate, clear stale results while preserving the record of the call.
  • Compaction (approaching window limit). When the dialogue itself nears the context ceiling, summarize and reinitiate rather than truncating blindly.
  • Sub-agent isolation (wide/deep sub-tasks). For research or parallel-exploration sub-tasks, delegate to a sub-agent with its own clean context, folding back only a condensed summary.
  • Persistent memory (cross-session). For knowledge that must survive past this single conversation, write structured notes to external file-backed storage, read back at the next session's start.

Benchmarking Context-Engineered Agents

Needle-in-a-Haystack (NIAH) tests basic retrieval of one planted fact in a long context — simple and widely used, but NVIDIA's own RULER paper notes it's indicative of only a superficial form of long-context understanding. RULER expands NIAH with synthetic tasks across varied categories and configurable sequence length, and is the more comprehensive long-context evaluation of the two. Neither substitutes for testing your own agent: use compaction, clearing, and memory in combination on a real long-horizon task, and measure whether the specific facts that task actually depends on survive each compaction pass. A generic long-context benchmark score doesn't tell you whether your own agent's compaction prompt is dropping the details your task needs.

Compaction is lossy by design

Anthropic's own documentation states detail loss during compaction is expected, not an edge case. Test compaction against the specific facts your task depends on, not generic quality — and use custom instructions to protect specific high-value context from being cleared or summarized away.

For the specific production incidents that context mismanagement causes — silent quality drift, tool-calling errors compounding through a trajectory — see AI Agent Failure Modes in Production. The term for gradual context degradation appearing as silent drift rather than a hard failure is defined in the glossary as Agent Memory Decay.

Building a long-running agent?

Context management decisions made in week one determine whether an agent degrades gracefully or silently at month three. Get the architecture right from the start.

Frequently Asked Questions

Prompt engineering is writing and organizing instructions for a single, well-scoped request. Context engineering is the ongoing discipline of curating the full set of tokens an agent sees across a long-running session — system prompt, tool definitions, tool results, prior turns, and retrieved data — so the highest-signal information survives as that set grows. Prompt engineering is a prerequisite skill; context engineering is concerned with everything else in the token budget.
Compaction summarizes a conversation that's approaching its context-window limit and reinitiates a new window with that summary — it's a within-session technique that loses fine detail to save tokens. Memory is a file-backed store an agent reads and writes across separate sessions, so knowledge persists after the window resets entirely. Compaction manages one long conversation; memory carries facts between conversations.
Longer context isn't free accuracy. The 2023 "Lost in the Middle" study found model accuracy on multi-document retrieval is highest when relevant information sits at the start or end of the context and degrades when it's buried in the middle, even in models built for long context. Anthropic calls the general pattern "context rot": as token count rises, a model's ability to accurately recall and use that context falls.
Use tool-result clearing when tool calls — file reads, API responses — are the dominant source of token bloat, not the dialogue itself. It removes bulky, re-fetchable results while preserving the record that the tool was called, at zero inference cost. Use compaction when the conversation itself, not tool output, is what's approaching the window limit. In practice, production agents stack both rather than picking one.
No. Retrieval-Augmented Generation is one way to decide what enters an agent's context — LangChain frames it as one implementation of the "select" operation. Context engineering is the broader discipline covering what gets retrieved, what stays, what gets summarized, and what gets moved out entirely across an agent's full run, of which RAG's retrieval step is a single input.