Effective context engineering for AI agents
Anthropic argues that context engineering is the natural successor to prompt engineering. Instead of only writing better instructions, engineers must curate the full set of tokens an LLM sees during inference, because models have a finite "attention budget" that degrades as context grows. As agents run longer, they need strategies such as just-in-time retrieval, compaction, structured note-taking, and sub-agent architectures to keep that context small and high-signal. ## From Prompt Engineering to Context Engineering - Prompt engineering focuses on writing and organizing instructions, particularly system prompts. - Context engineering covers everything that lands in the context window during inference: system prompts, tools, external data, message history, and more. - Agents that run in loops generate new information every turn, so context must be continually curated and refined. ## Why Context Is a Finite Resource - **Context rot:** As the token count grows, a model's ability to accurately recall information from its context declines. This happens across all models, though degradation rates vary. - **Architectural limits:** Transformers let every token attend to every other token, creating n² pairwise relationships, which stretches attention thin as context grows. - **Training skew:** Models see shorter sequences more often in training, so they have less experience with long-range dependencies. - **Gradual degradation:** Techniques like position encoding interpolation extend context length with some loss in positional precision. The result is a performance gradient, not a hard cliff. ## Anatomy of Effective Context - **System prompts:** Aim for the "right altitude," between brittle hardcoded logic and vague high-level guidance. Organize sections with XML tags or Markdown headers, and start with a minimal prompt, then add instructions based on observed failures. - **Tools:** Keep tool sets minimal and non-overlapping, since a human who can't pick the right tool can't expect an agent to either. Tools should return token-efficient output and have clear, unambiguous parameters. - **Examples:** Curate a small set of diverse, canonical few-shot examples instead of listing every edge case in the prompt. ## Retrieval: From Pre-Loading to Just-in-Time Context - Anthropic defines an agent simply as "LLMs autonomously using tools in a loop." - Embedding-based retrieval before inference is common, but agents increasingly use "just-in-time" retrieval. They keep lightweight identifiers such as file paths, stored queries, or links, and load data on demand with tools. - Claude Code analyzes large databases by writing targeted queries and using commands like `head` and `tail`, without loading full datasets into context. - Metadata such as folder names, file names, and timestamps helps agents infer purpose and relevance. A `test_utils.py` in `tests/` means something different from one in `src/core_logic/`. - **Progressive disclosure:** Agents build understanding incrementally, with each step informing the next. - **Trade-offs:** Runtime exploration is slower and needs good tool design and heuristics, or agents can waste context on dead ends. - **Hybrid approach:** Claude Code drops `CLAUDE.md` files into context up front and uses `glob` and `grep` for on-demand retrieval. Less dynamic domains like legal or finance may suit this hybrid model well. ## Context Engineering for Long-Horizon Tasks Tasks like large migrations or extended research exceed the context window, so Anthropic recommends three techniques. Waiting for bigger windows isn't enough, since context pollution and relevance problems persist at every size. ### Compaction - Summarize a conversation nearing the context limit and start a new window with the summary. - Claude Code preserves architectural decisions, unresolved bugs, and implementation details, discards redundant tool outputs, and keeps the five most recently accessed files. - Tune the compaction prompt first for recall, then for precision. - **Tool result clearing** is a light-touch form of compaction: once a tool result is deep in history, the raw output is often no longer needed. ### Structured Note-Taking - The agent writes persistent notes outside the context window and reloads them later, such as a to-do list or a `NOTES.md` file. - Claude playing Pokémon tracked training progress over thousands of steps, mapped explored regions, and kept combat notes, then resumed multi-hour sequences after context resets. - The memory tool, released in public beta with Sonnet 4.5, supports file-based storage for knowledge that persists across sessions. ### Sub-agent Architectures - A lead agent coordinates a high-level plan while specialized sub-agents handle focused tasks in clean context windows. - Each sub-agent may use tens of thousands of tokens but returns a condensed summary, often 1,000–2,000 tokens. - This pattern substantially outperformed single-agent systems on complex research tasks. ### Choosing an Approach - **Compaction:** Extensive back-and-forth conversations. - **Note-taking:** Iterative development with clear milestones. - **Multi-agent architectures:** Complex research where parallel exploration pays off. ## Conclusion The guiding principle is to find the smallest set of high-signal tokens that makes the desired outcome most likely. Anthropic expects smarter models to need less prescriptive engineering, but treating context as a finite resource will stay central to building reliable agents. Its advice is to "do the simplest thing that works."