Home / Insights / AI Agents and Automation

AI Agents and Automation

Context Engineering for AI Agents: Giving Models the Right Information at the Right Time

Most agent failures are context failures: the model did not see the right information, saw too much, or trusted the wrong source. This guide explains context engineering, the main techniques, a worked token budget, and how to test and secure what your agent sees.

TopicsAI Agents and AutomationGenerative AI and LLMsAI and Machine Learning

Key takeaways

  • Context engineering is the design of everything a model sees at each step: instructions, examples, tools, retrieved data, history and memory.
  • More context is not better. Models have a limited attention budget, and recall degrades as context grows; aim for the smallest set of high-signal information.
  • Core techniques are just-in-time retrieval, compaction of long histories, structured notes outside the context window, sub-agents with clean contexts, and well-designed tools.
  • Set a token budget per step, measure what each component contributes, and test changes against an evaluation set.
  • Treat retrieved and tool-provided content as untrusted data; context is also an attack surface.

When an AI agent makes a poor decision, the instinct is to blame the model or rewrite the prompt. More often the problem is context: the agent did not have a key fact, had too many irrelevant documents, carried a stale assumption from twenty steps earlier, or misread which tool to use. Context engineering is the discipline of getting this right.

Anthropic’s engineering team described context engineering in September 2025 as the natural progression of prompt engineering: managing the whole set of tokens a model sees at inference time, with the goal of finding the smallest possible set of high-signal tokens that make the desired outcome likely. This guide turns that idea into practical design steps.

What counts as context

ComponentExamplesTypical problems
———
InstructionsRole, goals, constraints, output format, escalation rulesToo vague, too rigid or contradictory
ExamplesRepresentative input and output pairsToo many edge cases; examples that conflict with instructions
Tool definitionsNames, descriptions, parametersOverlapping tools, unclear descriptions, too many tools
Retrieved knowledgeDocuments, records, search resultsIrrelevant passages, stale versions, missing key facts
Conversation and task historyPrevious turns, tool results, intermediate notesBloat, outdated information carried forward
MemoryStored preferences or facts about a user or projectWrong scope, poisoned entries, stale facts

Each component competes for the model’s limited attention.

Why agents need it more than chatbots

A chatbot answers one question with one context. An agent works over many steps, and each step adds tool results and reasoning to its context. Three problems follow:

  • Accumulation. After 30 tool calls, most of the context is old tool output, much of it irrelevant to the current step.
  • Drift. Early assumptions persist even when later evidence contradicts them.
  • Cascading errors. A misunderstood fact at step three leads to wrong actions at steps four to ten.

Anthropic describes the underlying constraint as an attention budget: every token draws on the model’s finite ability to focus, and recall tends to degrade as context grows — what it calls context rot.

Techniques that work

Right-altitude instructions

Instructions should be specific enough to guide behaviour but not hard-code brittle logic. State the goal, constraints, priorities and when to stop or escalate. Replace long lists of rules with a few principles and a small set of diverse examples.

Explicit over implicit

Agents cannot infer unwritten business rules. If refunds above a limit need approval, say so — and enforce it in the tool as well. If “urgent” means a response within four hours, define it.

Just-in-time retrieval

Rather than loading every possibly relevant document upfront, give the agent lightweight references — record IDs, file paths, search tools — and let it fetch what it needs when it needs it. Combine with a small amount of preloaded context for information almost every task needs.

Compaction

When history grows long, summarise it: keep decisions, open questions and key facts; drop raw tool outputs that have served their purpose. Clearing old tool results is often the easiest win.

Structured notes outside the context

For long tasks, let the agent write notes to a file or store — a plan, progress, findings — and read them back when needed. This preserves important information without keeping everything in the active context.

Isolated sub-agents

Delegate focused subtasks to sub-agents with clean contexts. They explore, then return a short summary to the main agent. This keeps the main context focused, at the cost of more model calls.

Tool design

Tools are part of context. Keep them few, distinct and self-explanatory. Return only the fields needed, in compact form. A search tool that returns 50 full documents wastes context; one that returns ten ranked snippets with IDs lets the agent fetch details selectively.

A worked token budget

Consider a support investigation agent with these components at a typical step:

ComponentBefore (tokens)After (tokens)Change
————
System instructions4,5001,800Rewritten as principles plus three examples
Tool definitions (24 tools)6,2002,100Reduced to 8 tools with clearer descriptions
Retrieved documents18,0004,000Top passages only, with IDs to fetch more
Raw tool results from earlier steps22,0003,000Old results cleared; key facts kept in a summary
Conversation and notes3,5002,500Rolling summary plus structured notes
Total per step54,20013,400About 75% less

Illustrative figures for a hypothetical agent. Every change was tested against the same evaluation set before adoption.

The point is not the exact numbers but the method: measure each component, change one thing at a time and confirm on an evaluation set that task success holds or improves. In many systems, success rises as noise falls.

Worked example: diagnosing a failing agent

A hypothetical agent that prepares supplier onboarding packs fails on about a third of evaluation tasks. The team logs full context for 30 failed runs and classifies the causes:

CauseShare of failuresFix
———
Key policy section not retrieved37%Re-chunk policies by heading; add keyword search alongside semantic search
Chose the wrong one of two similar tools23%Merge two lookup tools into one with a clear type parameter
Acted on a stale value from an earlier tool call20%Clear old tool results; re-fetch values before writing
Instructions conflicted with an example10%Rewrite the example to match current policy
Genuine reasoning error10%Add a validation step for the final pack

Illustrative figures. Most failures were context problems, not model limitations.

After the first three fixes, re-running the evaluation set shows which changes helped. Fixing context first is usually cheaper than switching to a larger model, and the improvements carry over when you do upgrade.

Tool descriptions are context too

A vague tool description forces the model to guess. Compare:

Before:  name: get_data  description: Gets data about a supplier. After:  name: get_supplier_profile  description: Returns the registered name, tax ID, onboarding status    and assigned category manager for ONE supplier. Use when you    have a supplier_id. Does not return contracts or bank details;    use get_supplier_contracts for contract terms.  parameters:    supplier_id: string, required, format SUP-000000

A per-step context checklist

  • Does the agent know the current goal and what “done” means?
  • Does it have the facts this step needs, and nothing it clearly does not?
  • Are tool results from earlier steps still relevant, or should they be summarised or cleared?
  • Is any retrieved content older than the systems of record allow?
  • Is untrusted content clearly separated from instructions?
  • Is the total within the budget set for this step?

Measuring context quality

  • Task success rate on a fixed evaluation set — the primary measure.
  • Retrieval precision and recall: did the agent see the facts it needed, and how much irrelevant material?
  • Tokens per step and per task, by component.
  • Steps to completion: better context often means fewer wasted actions.
  • Failure analysis: for each failed task, record whether the cause was missing, wrong, stale or excessive context, or a genuine reasoning error.

Context is an attack surface

Anything that enters context can influence the agent. Documents, web pages, emails and tool results may contain instructions written by an attacker. Mitigations:

  • Mark retrieved and tool content clearly as data, separate from instructions.
  • Never let retrieved content add tools, change permissions or alter goals.
  • Enforce permissions in tools, not only in instructions.
  • Filter retrieval by the user’s access rights so the agent never sees data the user should not.
  • Validate memory before writing it, and record its source.

These map to OWASP’s LLM risks, notably prompt injection (LLM01), sensitive information disclosure (LLM02) and vector and embedding weaknesses (LLM08).

Common pitfalls

  • Adding every document “just in case”.
  • Keeping every tool result for the whole task.
  • Writing instructions that contradict the examples.
  • Giving the agent many similar tools with overlapping descriptions.
  • Storing memories without scope, source or expiry.
  • Changing several context components at once and not knowing which change helped.

Frequently asked questions

Is context engineering just prompt engineering with a new name?

It includes prompt writing, but covers much more: retrieval, tools, history management, memory and the overall token budget across many steps.

Do larger context windows remove the need for it?

No. Larger windows allow more information, but attention is still limited and cost and latency rise with every token. Curation remains important.

How do we start improving context for an existing agent?

Log the full context for a sample of failed tasks, classify the causes, then fix the largest category first, measuring against an evaluation set.

Should every agent use sub-agents?

No. Sub-agents help with broad exploratory tasks but add cost and complexity. Use them when a single context becomes the bottleneck.

Sources and methodology

Facts in this article were checked against the sources below on 6 November 2026. Directory data (ratings, review counts, rate bands and team sizes) changes over time and is shown as published on the date accessed. Illustrative examples are labelled as such and are not quotes.

  1. Anthropic Engineering: Effective context engineering for AI agents (29 September 2025) — accessed 6 November 2026. Definition; attention budget and context rot; just-in-time retrieval; compaction; structured note-taking; sub-agent architectures; tool design
  2. OWASP: Top 10 for LLM Applications 2025 — accessed 6 November 2026. LLM01, LLM02 and LLM08

Is your agent unreliable on real tasks?

Share examples of where it goes wrong. We will help you diagnose context problems, redesign instructions, tools and retrieval, and measure the improvement.