When engineering teams deploy AI Agents to execute multi-step workflows such as record reconciliation, customer support escalation, or automated code repair over 20 to 40 tool calls, a common assumption is that a multi-hundred-thousand-token context window solves memory management on its own. In production, the opposite happens: stuffing raw conversation history into every turn causes the agent to lose track of early constraints, repeat failed actions, and inflate inference bills.
The underlying bottleneck is rarely raw window capacity; it is the signal-to-noise ratio inside each model call. Moving from naive transcript appending to disciplined AI architecture consulting is the core discipline of Context Engineering: controlling exactly what enters, stays in, gets compacted, or is evicted from the active prompt at every step.
In its engineering guide "Building effective agents," Anthropic characterizes an agent as a loop in which an LLM iteratively invokes tools, inspects environmental feedback, and decides the next action. Once that loop stretches past a couple dozen steps, three failure modes compound simultaneously:
- Attention dilution from stale payloads: A single SQL query, API response, or webpage DOM capture can inject tens of thousands of tokens into the thread even though the agent only needed three fields. After several turns, historical tool output consumes more than 80% of the prompt, pushing system rules and acceptance criteria away from the model's sharpest attention focus.
- Quadratic token growth and rising latency: Purely append-only histories force the model to re-read every prior step on every subsequent turn. Total input tokens scale quadratically with step count, driving up both cost and time-to-first-token.
- Context pollution from abandoned branches: Dead-end hypotheses, stack traces, or malformed tool arguments from step 5 remain visible at step 25 unless pruned, nudging the model to re-evaluate paths it already disproved.
A four-layer architecture for agent memory and context
Rather than treating the messages array as a single monolithic store, engineers should partition agent context into four distinct layers aligned with Anthropic's Prompt Caching mechanics. Prompt caching reduces read costs and latency by caching a stable prefix at the start of a request, provided that everything ahead of the cache breakpoint remains byte-for-byte identical across turns.
| Context layer | Mutability profile | Storage and placement | Management strategy over 20+ turns |
|---|
| 1. Static Prefix (System & Tools) | Fixed for the session | Prompt head with cache breakpoint | Never inject timestamps, counters, or mutable state here |
| 2. Persistent Structured State | Controlled updates | External JSON store or database | Inject only active progress, verified IDs, and hard invariants |
| 3. Ephemeral Scratchpad | Short-lived per step | Local loop working notes | Retain only current-step reasoning; clear on phase transitions |
| 4. Tool Observations | Decays after 1-2 turns | Full raw logs saved to disk/DB | Keep verbatim for latest turn; mask older outputs into compact pointers |
Respecting layer order is essential for cache hits. Dynamic state updates and trimmed observations must always be appended near the tail of the prompt. Inserting a step counter or rolling status block inside the system prompt on every turn invalidates the prefix cache and forces full reprocessing on every call.
Compacting history, trimming tools, and preserving constraints
Keeping a long-running agent sharp across dozens of turns requires three concrete mechanisms implemented in the orchestration layer outside the model:
- 01Filter bulky tool outputs at the boundary: Never return a 5,000-line log file or unpaginated JSON payload directly into conversation history. Wrap tools to project only relevant fields, cap row counts, and persist full payloads to an external artifact path so the model receives a concise summary plus a retrieval handle.
- 02Apply observation masking to older turns: Once a tool response is 3 to 5 turns behind the active step, its raw payload rarely helps immediate reasoning. The orchestrator can replace verbose JSON from earlier
tool_result blocks with a compact breadcrumb such as "Read config.ts; recorded 2 type mismatches at line 42", keeping the tool_use and tool_result pairing structurally valid while freeing thousands of tokens. - 03Use schema-driven compaction instead of freeform summaries: When prompt usage crosses a defined threshold (such as 60% of the session token budget), trigger a structured compaction pass rather than asking the model for an open-ended prose recap. Require fixed fields: original user objective, non-negotiable constraints, confirmed facts with exact identifiers (record IDs, file paths, error codes), completed milestones, and remaining open tasks.
- 04Reset context across major workflow phases: For complex workflows split into distinct stages such as investigation, planning, and execution, avoid carrying the entire exploratory transcript forward. Emit a clean handoff specification into persistent state and start the execution phase with a fresh context window anchored to that specification.
Scope, caveats, and honest limitations
The agent loop principles and tool-interface discipline referenced here draw from Anthropic Engineering's "Building effective agents," while prefix-stability requirements reflect Anthropic's official "Prompt caching" documentation. The four-layer separation, budget-based compaction thresholds, and observation-masking patterns represent ToanKhonTech's engineering practices from building production agent pipelines.
Exact step thresholds (such as 20+ turns) and token savings vary significantly depending on tool verbosity, task branching complexity, and each provider's prompt-caching minimum token lengths and TTL rules. Furthermore, any lossy compaction carries a risk of dropping edge-case details if relied upon as the sole source of truth. Critical identifiers, ledger balances, and workflow checkpoints must always live in deterministic external state outside the LLM context window and be validated by application code before irreversible actions execute.