AI Engineering

Context Engineering for Long‑Horizon Agents

A field playbook for managing the context window across long-running, multi-turn agents — what breaks, why, and the levers that actually work.

Working notes on managing the context window for agents that run for many turns. The focus is on the substance: what the problem actually is, what works in production, and the best practices to apply. Metrics are kept as reported in the underlying research.

Topics we will cover

1What context engineering is (and is not)

Prompt engineering is about how to write good instructions — mostly the system prompt. Context engineering is broader: it owns the entire token lifecycle of a multi-turn agent, from the first system-prompt token to the last compacted summary. In practice it means curating and maintaining the optimal set of tokens available to the model during inference, including everything that lands in the window beyond the prompt itself.

The right mental model is to think in context: consider the full state the model sees at each step and what behavior that state is likely to produce — not just whether the system prompt reads well. Operationally that covers which retrieved documents to include and when to drop them, which tool outputs to keep versus clear, when to summarize a growing history, how to route subtasks to isolated subagents, and how to keep persistent notes outside the window.

Why it matters: production agents fail at the context layer far more often than at the prompt-writing layer. Agents are not one-shot chatbots — they run for hundreds of turns and accumulate tool outputs. The canonical components that belong in the window are: task description, few-shot examples, retrieved knowledge (RAG), relevant multimodal data, tools, state, history, and compaction.

What it is not — common misconceptions

2The empirical evidence: “context rot”

The core finding is that model performance degrades as the input token count grows, across every major model tested. Larger context windows move where the degradation starts; they do not remove it. This was shown by extending the classic Needle-in-a-Haystack test — which only checks direct lexical matching — with semantic matching and a conversational QA evaluation, to separate context-length effects from raw task difficulty.

Why it happens is architectural:

Retrieval correctness for a large 405B-class model started falling around the 32k-token mark, and earlier for smaller models. Smaller models hit their distraction ceiling well before their window is full.

Key insight: supporting a 1M-token window does not mean you should fill it. Raw context length is a poor proxy for usable context. The engineering problem is not getting tokens in — it is keeping only the right tokens at every step.

3Failure taxonomy: four ways agents break

Under context pressure, long-horizon agents fail in four distinct ways. Each maps to a primary fix and has its own detection signal.

Failure mode When it occurs Primary fix Detection signal
Context Poisoning A hallucination enters the context and compounds across turns Compress — evict stale/wrong context Agent pursues impossible or irrelevant goals; loops escalate
Context Distraction Long context makes the model over-rely on history instead of reasoning (onset ~100k tokens) Compress — summarize message history Agent repeats past actions instead of adapting; low novelty
Context Confusion Too many tools or docs overwhelm the model (one 8B model failed with 46 tools, succeeded with 19) Select — just-in-time tool/doc loading Wrong tool called; irrelevant doc cited
Context Clash Conflicting info accumulates across turns; multi-turn “sharding” caused an avg 39% drop (one frontier model: 98.1 → 64.1) Isolate — subagent partitioning; Write — structured notes Contradictory answers across calls; hedging increases

Two notes. Poisoning and distraction often appear in the same agent — they are two expressions of the same root cause: unmanaged context accumulation. And context clash is not a small-model problem; it hits frontier models too. When prompt information is spread across multi-turn exchanges (exactly how agents operate), accuracy can drop sharply versus the same information given in one shot.

4The four levers: Write, Select, Compress, Isolate

These levers are layered, not competing — most production agents need all four running at different points in the context lifecycle.

Best practice: don't stop at compaction (the most visible lever). Compaction alone reduces token spend and distraction but does nothing for confusion (too many tools → use Select) or clash (multi-turn accumulation → use Isolate/Write).

5Compaction, in depth

Compaction is the primary lever for long-horizon runs — hundreds of turns, hours of wall-clock time, or workflows that would otherwise exhaust the window. Reported effectiveness is strong: in a 100-turn web-search evaluation, context editing reduced token consumption by ~84% while enabling completion of workflows that would otherwise fail from context exhaustion. Context editing alone gave a ~29% performance lift; combined with a memory tool it reached ~39%.

The real question is not whether to compact, but what to preserve. Off-the-shelf summarization does not reliably keep key decisions for long-running tasks — a fine-tuned compaction model is more reliable in production.

Preserve

  • Architectural decisions — which approach was chosen and why, so resolved tradeoffs are not re-litigated.
  • Unresolved bugs and blockers — the current state, not the full diagnosis history.
  • Implementation context — what was built, tested, and the state it was left in.
  • Current objectives and sub-goals for this run.

Discard

  • Raw tool outputs already processed — once the signal is extracted, the full output is noise.
  • Dead-end reasoning traces — note them as “tried X, failed because Y” instead of keeping them in full.
  • Redundant confirmations and status checks that did not change behavior.

On triggers: a practical auto-compact threshold is ~95% of context-window usage. For programmatic pipelines, prefer an automatic context-editing mechanism that clears stale tool calls/results (finer control) over the manual, product-layer auto-compact meant for interactive sessions.

6Token budget by agent type

Recommended ceilings per component slot, assuming a 200k total budget at steady state. The ratios are more stable than the absolute numbers — scale proportionally for other window sizes.

Agent type System prompt Tool defs RAG / docs Message history Compaction strategy
Research (breadth-first) ~2k–4k ~5k (RAG-selected) ~30k per subagent ~10k condensed Isolate to subagents; return 1k–2k summary each
Coding (file-heavy) ~4k–8k ~3k (glob/grep JIT) ~40k (files on demand) ~20k before compact Auto-compact at 95%; keep decisions + open bugs
Customer support ~3k–5k ~4k (select per intent) ~15k (KB chunks) ~8k rolling window Rolling summarize + persist customer state outside window
Data analysis (tool-heavy) ~2k–3k ~8k (schema + tool defs) ~20k (query results) ~15k before compact Clear raw query results once extracted; compress to findings
Long-running automation (hours+) ~3k–5k ~4k (JIT select) ~10k (rolling) ~8k structured notes Fine-tuned compaction model; checkpoint to storage every N steps

Steady-state rule of thumb for a 200k budget: system prompt ~3k, tool defs ~5k, RAG ~20k (the largest variable slot — size it to the task), message history ~12k (compress before it grows past ~15k), and keep ~160k of headroom for output and tool responses. Filling the window is itself the failure mode.

7Multi-agent architecture: isolation as strategy

In a detailed research-agent case study, token usage explained ~80% of performance variance on a browsing benchmark, with tool-call count and model choice as the other two factors. Translation: context management is the primary performance lever, not model selection.

How it works: give each subagent its own isolated window; subagents return condensed summaries (~1k–2k tokens) to the lead rather than their full context. The lead accumulates distilled insights, not raw trails — which prevents context clash from parallel workstreams merging into one confused window.

Spawning 3–5 subagents in parallel (versus sequentially) reportedly cut research time by up to ~90% on complex queries. And tool descriptions are themselves a context lever: rewriting flawed descriptions cut task-completion time by ~40% for later agents. Poorly written descriptions waste tokens explaining themselves and confuse the model — auditing them is a high-ROI, low-effort win.

8System-prompt “altitude”: the Goldilocks zone

Two failure modes bracket the optimal range:

Best practices: structure prompts for scannability with distinct sections (XML tags or Markdown headers for background, instructions, tool guidance, output description) — this helps both model comprehension and token efficiency. The guiding principle for every context component is the smallest set of high-signal tokens that maximizes the likelihood of the desired outcome. Agent prompts are not chatbot prompts: chatbot prompts tend to be exhaustive to handle diverse one-shot queries, whereas agent system prompts should be concise and defer to dynamically-selected context for specifics. Think “guide a sustained, tool-using process,” not “answer every possible question.”


Key takeaways

← Back to Coding