Context Engineering for AI Agents: Nine Components Across Three Layers

Xinye Yang · · 4 min read

TL;DR. Context engineering is not about fitting as much information as possible into a context window. It is about delivering the right information, at the right time, with the right level of detail, while balancing intelligence, latency, cost, and reliability. I break an agent's context management system into nine components across three layers: the foundations that make an agent functional, context budget management that prevents overflow, and advanced context and persistent memory management.


Having spent considerable time both building and using AI agents, including developing Context Compaction and Memory features at a scale of millions of users, I've come to appreciate how critical a well-designed context management system is to the success of an agent product.

Context Engineering is deceptively simple in principle, yet full of subtle engineering challenges in practice.

Why it is hard: three competing constraints

The nine components at a glance

I break down an agent's context management system into nine components across three layers.

LayerComponentWhat it is responsible for
1. FoundationsContext assemblyA deterministic ordering: stable content first, dynamic content last
Static contextSystem prompts, tool definitions and project instructions, kept compact
Conversation historyAn append-only record whose structure stays intact
2. Context budget managementTool output managementAn output budget per tool; oversized results offloaded to disk
Token accounting and budgetingAccurate token counts before each model request
Context compactionWhen to trigger, what to preserve, how to evaluate quality
3. Advanced context and persistent memoryOn-demand context loadingRetrieving information when it becomes relevant
Context isolationSubagents with isolated context windows
Persistent memoryKnowledge extracted, consolidated and pruned across sessions

Layer 1: The foundations, making an agent functional

1. Context assembly

Maintain a deterministic ordering: stable content first, dynamic content last (as illustrated in the figure below).

Layout of an agent's context window, from stable to volatile content A context window stacked top to bottom: system prompt and tool definitions; project instructions and long-term memory; conversation history and tool results; the current message. Content at the top is stable and cacheable, content at the bottom is volatile. Files, notes and subtasks live outside the window and exchange information with the conversation history. Context window System prompt, tool definitions Sent with every request, rarely changes Project instructions, long-term memory Loaded when the session starts Conversation history, tool results Append-only, grows fastest Current message Stable, cacheable Volatile Outside the window Files, notes, subtasks
Stable content sits at the top of the context window and stays cacheable; volatile content is appended at the bottom. Files, notes and subtasks live outside the window.

This is essential for prefix caching. Even a small change early in the context can invalidate the subsequent cached prefix.

Codex has documented several pitfalls, including adding or removing tools mid-session, switching models, changing working directories, and inconsistent tool ordering.

One mitigation is to preserve existing messages and append updates instead of retroactively modifying them, wherever the API architecture permits.

2. Static context

System prompts, tool definitions, and project instructions.

These are included in every request, so keeping them compact is essential. With a large tool ecosystem, tool definitions alone can consume a significant portion of the context window.

Claude Code addresses this through progressive disclosure: exposing lightweight tool information upfront and loading full definitions only when needed. Skills follow a similar design philosophy.

3. Conversation history

An append-only record of interactions.

History cannot be arbitrarily truncated. Structural integrity must be preserved, particularly the pairing between tool calls and their corresponding results.

Layer 2: Context budget management, preventing context overflow

4. Tool output management

One of the largest sources of context consumption, particularly when managing a diverse ecosystem of MCP servers.

This is also one of the most failure-prone areas in production. I once dealt with a Sev2 incident related to this, which made the lesson particularly memorable.

File reads and command outputs can quickly exhaust the context window. Each tool therefore needs an appropriate output budget.

A common approach is to offload oversized results to disk, retaining only a preview and a reference to the complete output in context.

5. Token accounting and budgeting

Accurately measure token consumption before each model request and surface meaningful usage information to users.

Conceptually straightforward, but inaccurate accounting can lead to surprisingly complex production failures.

6. Context compaction

The central questions are when to trigger compaction, what information to preserve, and how to evaluate its quality.

Compaction is inherently lossy. Earlier instructions may disappear, and omissions in generated summaries are often difficult to detect.

Certain critical information, such as project instructions, should therefore be explicitly preserved or reinjected after compaction.

Compaction also typically rewrites the context prefix, requiring the prompt cache to be rebuilt.

Layer 3: Advanced context and persistent memory management

7. On-demand context loading

Retrieve information when it becomes relevant rather than injecting everything upfront.

8. Context isolation

Delegate specialized tasks to subagents with isolated context windows, preventing intermediate reasoning and tool outputs from polluting the primary agent's context.

9. Persistent memory

Automatically extract, consolidate, and refine useful knowledge across sessions, while periodically pruning or decaying outdated and low-value memories.

Closing

Ultimately, Context Engineering is not about fitting as much information as possible into a context window.

It is about delivering the right information, at the right time, with the right level of detail, while balancing intelligence, latency, cost, and reliability.

A larger context window is not a substitute for a well-engineered context management system.

FAQ

What is context engineering for AI agents? Context engineering is the design of an agent's context management system. It is not about fitting as much information as possible into a context window. It is about delivering the right information, at the right time, with the right level of detail, while balancing intelligence, latency, cost and reliability.

Why is context engineering hard? Three constraints compete: context windows have finite capacity; context must be processed again with each model request, so longer contexts cost more; and adding more information can degrade model performance.

Why does the order of content in the context matter? Prefix caching depends on it. Keep a deterministic ordering with stable content first and dynamic content last, because even a small change early in the context can invalidate the cached prefix that follows. Where the API allows, preserve existing messages and append updates instead of modifying them retroactively.

Is context compaction lossless? No. Compaction is inherently lossy: earlier instructions may disappear, and omissions in generated summaries are hard to detect. Critical information such as project instructions should be explicitly preserved or reinjected after compaction. Compaction also typically rewrites the context prefix, so the prompt cache has to be rebuilt.

Does a larger context window remove the need for context management? No. A larger context window is not a substitute for a well-engineered context management system.

Further reading