Context engineering for agents that must stay reliable in production

Louis Poirier
Louis Poirier
November 24, 2026
16
min read

In tests published in 2025, 11 of 13 LLMs advertising at least 128K tokens fell below half their short-context score at 32K (NoLiMa). Context engineering decides what an AI agent reads before each model call: prompt, tool calls, memory and retrieved data. This introduction maps context window components, token costs, failure modes and the metrics that expose context rot.

What context engineering is and what goes into the context window

Context engineering defined: choosing what a model reads

Anthropic defines context engineering as the strategies for curating and maintaining the optimal set of tokens during LLM inference (2025). The context window is the finite space that language models read at inference time. Andrej Karpathy called filling it an art and science. Effective context engineering finds the smallest relevant context that helps an agent perform a task. Inputs include tool descriptions, conversation history, user input, the user query and retrieved data from external sources or vector databases through retrieval augmented generation (RAG). An LLM, like any language model, cannot use what it never receives. Context management is how you plan context retrieval and data quality.

Beyond the prompt: what the new discipline adds

Prompt engineering is the parent discipline. It shapes the wording of an instruction. Context engineering governs everything that enters the window at inference time, including parts that no person wrote by hand. The question typed by the user is one piece among many. The quality of each response now depends on how those pieces are selected, ordered and refreshed.

DimensionPrompt engineeringContext engineering
Unit of workOne instructionEverything sent per call
When it happensMostly before deploymentAt every step of a run
What can failAmbiguous wordingMissing, stale or excess information
How you check itOutput reviewRetrieval, grounding and cost metrics

Why agents, tools and long tasks changed the problem

An agent is a model that uses tools in a loop. This agentic pattern is common and its importance grows with every tool you add. Each turn adds tool calls, results, memories and reasoning to the next request. An agent’s context therefore grows on its own in most agent systems. In a long session the first instruction ends up far from the latest output. Teams that run multi-step agents report a heavy skew toward reading: Manus measured about 100 input tokens for each output token (July 2025). Time and money go into reading, which shapes every architecture decision. A memory layer and reasoning traces add to that bill.

Did you know?

Anthropic found that token usage alone explains 80% of performance variance on the BrowseComp evaluation. In its measurements an agent uses about 4 times more tokens than a chat (multi-agent research system, 2025).

System prompts, instructions and few-shot examples

The system prompt sets the role, the rules and the output format. Anthropic advises writing it at the right altitude: specific enough to guide behavior and flexible enough to act as strong heuristics (2025). Hardcoded if-else logic makes the agent brittle. Vague guidance gives it nothing to act on. Natural language is flexible so each term needs a clear meaning.

Few-shot examples still help. Choose a small group of diverse and canonical cases instead of a long list of edge rules. Each example should show the expected output format and the type of answer you require. Give each instruction block a clear heading so you can update it and test the change alone. Keep the focus on behavior that you can observe.

Tool descriptions and tool results

Every tool adds two kinds of context. Tool descriptions tell the LLM what it may call. Tool results bring back what happened. Both consume space. Anthropic names bloated tool sets with overlapping functions as one of the most common failure modes (2025). If an engineer cannot say which tool applies, the agent will not do better. These limitations matter because the model’s context fills with choices it cannot rank.

Building good tools is context work. Keep each tool specific and efficient. Require typed arguments. Return only the object fields the next step will require: a search tool that dumps whole pages fills the budget faster than any conversation.

Conversation history, memory and workflow state

Some context comes from the run itself:

  • the conversation history of the current session
  • the workflow state such as completed steps, open questions and files already read
  • long-term memory with facts and learned preferences that survive the session as memories

LangChain separates what the model sees for one call from what persists in state or in a store. That split matters. A fact that should last belongs in a memory with an owner and an update rule. Short-term memories end with the thread while long-term memories need a store that returns each record on request. It should not sit forever in the transcript where it costs money at every turn. Our guides give an introduction to the layers of AI memory and the read and write paths of agent memory in depth. Here memory is one source among several. Agent memories deserve the same care as customer records.

Retrieved data: documents, records and search results

Retrieval augmented generation (RAG) pulls passages from outside the training set and adds them to the request. The sources can be documents, product records, tickets or other unstructured data indexed in vector databases. A coding agent may read a GitHub repository while a sales agent reads a policy file. Search quality caps answer quality. A relevant passage that arrives buried among distractors helps less than a shorter list. Source quality counts first: duplicated or outdated records produce confident and wrong output. Update each file when the source changes. Track the source type and the date of every retrieved chunk so the agent can tell a contract from a forum post.

Context engineering techniques: select, order, compress, isolate and cache

Select: dense retrieval, hybrid search and reranking

LangChain groups the techniques into four families: write, select, compress and isolate. These strategies differ in effect and in cost. Selection comes first because it decides what competes for attention. Relevance is the filter. Dense retrieval matches meaning through neural embeddings. Keyword search such as BM25 catches exact names and codes. Hybrid search runs both. Reranking then scores the candidates against the query and keeps the best ones.

A vector store such as Chroma does not choose your chunks for you. Chunking shapes everything downstream. The format of a chunk matters as much as its length. Anthropic reported that adding context to each chunk before indexing cut top-20 retrieval failures by 35% with embeddings alone. The cut reached 49% with contextual BM25 and 67% with reranking on top (Contextual Retrieval, 2024). Measure the gain on your own corpus because these figures come from one series of tests. Retrieval augmented generation RAG is only as good as this first context retrieval step. A vector store keeps the embeddings while your pipeline owns the ranking logic.

Order the window: priority, position and eviction

Position changes the outcome. Liu and co-authors showed that performance is often highest when the key evidence sits at the start or the end of the input (Lost in the Middle, 2023). Good context management applies a clear eviction policy:

  1. Pin the instructions that must hold for the whole run.
  2. Place the current plan and the freshest evidence near the end.
  3. Drop raw tool results once their conclusion is recorded.
  4. Slide old turns out of the window after you summarize them into memories.

Attention is the scarce resource. Manus has its agent rewrite a task list as it works. That recitation pushes the global plan back into recent attention (2025).

Compress: summarization, compaction and note-taking

Compaction summarizes a conversation that nears the limit and restarts from that summary. Anthropic suggests tuning the compaction prompt on real traces: maximize recall first then improve precision (2025). One of the safest and lightest forms of compaction clears old tool results. Overly aggressive summarization loses details whose value shows up later.

Structured note-taking is the other option. The agent writes notes in a plain format to a file outside the window and reads them back when needed. Intermediate results and memories stay in that file between sessions. This agentic memory keeps interim decisions and long term goals visible without replaying the whole conversation history. Each term in a summary should earn its place. Claude Code keeps a to-do list this way according to Anthropic.

Expert tip:

Keep the raw trace in storage even after compaction. When an answer goes wrong you need to see what the summary dropped.

Isolate: sub-agents with clean context windows

Isolation gives each subtask its own clean context window. A lead agent keeps the plan while each helper reads only its own file. Sub-agents do the deep exploration and return a short summary, often 1,000 to 2,000 tokens in Anthropic’s description (2025). The lead never reads the noise.

Isolation costs more overall. In Anthropic’s measurements multi-agent systems use about 15 times more tokens than chats. Use it when the task splits into independent parts. Coordination between agents is a separate topic that our guide to AI agent orchestration covers. Check your agent harness too: it decides what each sub-agent receives.

Cache: stable prefixes, prompt caching and the KV cache

Caching rewards a stable prefix. A model that already processed the same opening text can reuse that work from the KV cache. Manus calls the KV-cache hit rate the most important metric for a production agent (2025). Prompt caching exposes the idea through the API. Anthropic’s documentation read in November 2026 states the following rules:

  • the default cache lifetime is 5 minutes with a paid 1-hour option
  • a 5-minute write costs 1.25 times the base price of the same input
  • a read costs 0.1 times that price on most models and 0.05 times on Claude Opus 5.5 and Claude Sonnet 5.5
  • each Claude model also sets a minimum prompt length for caching
  • the cache follows the order tools, system then messages

A change in tool definitions invalidates everything. A timestamp at the top of the system prompt breaks the cache for everything after the tool definitions at each call. Append new content at the end. Both rules cut inference time and cost.

Estimate your token budget and cost per call

A token budget assigns a share of the available space to each component. Begin from a measured trace. Count what instructions, tools, history, results, retrieved passages and memories provide. Then multiply by the number of turns in a typical session. The simulator below does that arithmetic with and without caching. Enter your own base price because list prices change. Treat the 32K marker as a prompt to run your own test. It is not a universal limit because behavior differs from one neural network to the next.

Interactive tool

What does one agent call cost?

Enter the tokens of each component. Compare a session with and without prompt caching.

6%
17%
23%
29%
23%
3%

35,000tokens per call
$0.0700per call, no cache
$1.40per session, no cache
$1.12per session, cached prefix (20% less)

Above 32,000 tokens. In NoLiMa tests published in 2025, 11 of 13 models fell below half their short-context score at this length. Test yours.

Input tokens only. Assumes a constant context size, a cached prefix made of the system prompt and tool definitions, a first call that writes the cache at 1.25 times the base price and later calls inside the cache lifetime. Multipliers and the default price come from Anthropic documentation read in November 2026. Providers also set a minimum prefix length.

Nothing you type leaves this page. Indicative tool by Kleio.

Context failure modes and the metrics that catch them

Context rot and lost in the middle: what to change in the pipeline

Context rot is the loss of accuracy as input grows. The challenge is common and often emergent: short tests do not reveal it. Chroma tested 18 models and found that performance degrades with input length in non-uniform ways, even on simple tasks (July 2025). The Chroma report is a useful introduction to the topic. In NoLiMa even GPT-4o fell from 99.3% to 69.7% at 32K tokens. Those models date from 2024 and 2025. Newer ones deserve their own test.

The fix lives in the pipeline and not in a larger neural network. Retrieve fewer and better passages. Rerank before you inject. Compact finished work. Isolate bulky exploration. Move the decisive evidence away from the middle. A bigger window raises the ceiling without telling the agent where to pay attention. Our AI memory article describes both effects in detail.

From failure to lever to metric

Every challenge needs a lever and a control metric that proves the lever worked. Use this matrix as a starting checklist for your agent.

FailurePublished evidenceLeverControl metric
Context rot18 models degrade with length (Chroma 2025)Compaction and isolationTask success by input length
Lost in the middleMid-context information is used less (Liu et al. 2023)Reordering and rerankingAccuracy by evidence position
Distracting passagesRelated but wrong text hurts (Chroma 2025)Hybrid search and rerankingContext precision
Missing evidence5.7% top-20 retrieval failures at baseline (Anthropic 2024)Contextual chunkingContext recall
Unsupported answerClaims absent from the context (Ragas)Grounding instruction and citation checkFaithfulness
Cost explosionAgents use about 4 times chat tokens (Anthropic 2025)Result clearing and token budgetTokens per task
Broken cacheTool changes invalidate the prefix (Anthropic docs)Stable prefix and tool maskingCache hit rate

A fixed list helps your team learn to diagnose failures. Read the table row by row during incident reviews. Name the failure first. Pick one lever. Then watch its metric across the same test set. Changing the LLM, the search step and the instructions together tells you nothing about the cause.

Faithfulness, context precision and context recall

The Ragas paper (2023) and its library give a shared vocabulary for answer quality:

  • Faithfulness is the share of claims in the response that the retrieved context supports.
  • Context precision checks whether relevant chunks rank above irrelevant ones.
  • Context recall is the share of claims in a reference answer that the retrieved text covers.

Recall needs a reference answer so you must write one for each test question. Those reference answers become a shared asset that support teams can update. Precision tells you whether search is noisy. Faithfulness tells you whether the model stayed within its source. Read the three together. A faithful response built on the wrong document is still wrong.

Trace every span and test strategies against each other

Log each model call as a span with the size of each component, the chunk identifiers, the tool calls and the cache hit. You can then replay a bad answer and see what the agent actually read. Without that trace, debugging turns into guesswork.

Compare strategies on the same tasks. Anthropic’s team started evaluating with about 20 queries that reflected real usage (2025). Run version A with full history and version B with compaction. Score both on success, cost, latency and faithfulness to see the impact. Keep the winner and add every new failure to the benchmark. You learn from this loop and each update starts with evidence.

Expert tip:

Version the context policy like code. A change in chunk size or eviction order can shift behavior as much as a model upgrade.

Putting context engineering into production

Frameworks and tools: LangChain, LangGraph, LlamaIndex, DSPy and Haystack

Official documentation read in November 2026 describes each tool in a distinct way:

  • LangChain documents context engineering as control over model context, tool context and life-cycle context.
  • LangGraph is a low-level runtime for long-running and stateful agents with persistence.
  • LlamaIndex offers a Python framework to build LLM-powered agents over your data with connectors and indexes.
  • DSPy replaces hand-written prompts with structured signatures that its optimizers can tune.
  • Haystack builds pipelines and agents from reusable components for retrieval and search.

None of them decides which information your business may expose. These technologies give you the plumbing. Your architecture choices matter more than the brand. Pick the one your team can debug. Check each GitHub repository and release history before you commit because these libraries change quickly. Reading a framework introduction takes an afternoon while a working evaluation set takes real effort. Vector databases and MCP servers complete the stack. The agent harness ties them to the loop that calls the model. Our guide to the AI agent platform covers the layers around them.

A rollout order from prototype to production

A prototype hides context problems because sessions stay short. Before you scale, follow this order:

  1. Write one task and its golden set of questions with reference answers.
  2. Record a trace and measure each component.
  3. Fix search until context recall and precision hold.
  4. Add compaction or notes for long sessions.
  5. Stabilize the prefix and turn on caching.
  6. Create alerts on cost per task and faithfulness.

Each step leaves a number that the next change must not degrade. This is effective context engineering in practice: small moves with proof. The same plan applies whether you need an agent to perform a task for a developer or for a buyer.

The enterprise context supply chain

In a large company the context of one answer crosses many tools: product catalog, documents, CRM, buyer history and business applications. Treat that path as a supply chain. Each stage removes a specific risk before the language model sees anything. Machine learning teams and data engineers share this work. The diagram below is a reference design that you can audit stage by stage.

The enterprise context supply chain

Seven stages between your systems and one model call.

  1. 1

    Source systems

    Product catalog, documents, CRM, buyer history, business applications

    Neutralises: unknown or ownerless data

  2. 2

    Access rights

    Permissions applied per user and per operation before any search

    Neutralises: exposure of restricted content

  3. 3

    Pseudonymisation

    Sensitive fields masked before an external model call

    Neutralises: personal data leaving your perimeter

  4. 4

    Structure

    Schema, business ontology, source and version on every record

    Neutralises: stale or ambiguous facts

  5. 5

    Selection under budget

    Hybrid search, reranking and compaction within the token budget

    Neutralises: noise, context rot and cost drift

  6. 6

    Injection

    Stable prefix first, fresh evidence near the end

    Neutralises: broken cache and buried evidence

  7. 7

    Trace

    One span per call: what entered, why and from which version

    Neutralises: answers nobody can explain

Reference design to audit your own pipeline. Not a product specification.

A context layer sits between those data sources and your agents. It holds the schema, the ownership and the access rules. Data engineering teams already own most of these assets. Context work reuses their data management practices and adds a cost constraint. Enterprise context also ages. Give every record a refresh date and an owner who can correct it.

Access rights, personal data and provenance

The question for a CIO is who may place content in front of the LLM. Apply permissions before search so a document the user cannot open never reaches the window. Runtime values such as user ID and permissions belong in configuration that the model cannot rewrite.

The GDPR principle of data minimisation (article 5(1)(c)) requires personal records to be limited to what the purpose needs. A context window is a processing step like any other. Identify sensitive fields such as an email address. Remove or pseudonymise them before any external model call. Keep the provenance of each passage: source, version and date. Your security team can then explain an answer and delete a record on request.

How Kleio applies context engineering to high-consideration purchases

A Knowledge Engine that structures data before the agent reads it

A buyer of a trip, a property or a car asks questions that span catalog, policy and personal history. Our position is that this is a data problem before it is a prompt problem. The Knowledge Engine keeps three purpose-built stores for product, document and memory records with a separate layer for configuration and governance. Our Triple Business Ontology describes the function, the industry and the client. Structure comes first so that each AI agent receives relevant context instead of a raw export. Kleio is an Agentic Commerce platform for complex sales. It is not a general framework for developers.

Evidence-weighted memory instead of a longer history

Replaying every past message is the expensive way to remember a buyer. Our Memory Store turns signals into observations, claims and then beliefs with a weight per source. A statement by the buyer weighs more than observed behavior. When sources disagree the belief becomes contested and the agent asks the user a question instead of guessing. Each belief links back to its evidence. The memories that reach the window are therefore short and explainable.

Governance, isolation and deployment in weeks

The platform is tenant-isolated and supports RBAC per operation with versioned configurations. Sensitive fields are pseudonymised before any call to an external LLM. SOC 2 and CCPA compliance frame the whole platform. We deploy in weeks rather than months because industry ontologies come pre-built. Your team keeps control of what each agent may read and can review how a configuration changed.

Context for complex, high-value sales

Bring one buying journey to a Kleio demo.

See how the Knowledge Engine structures your product, document and memory data before an AI agent reads it.

Frequently asked questions about context engineering

What is context engineering?

Context engineering is the practice of selecting, ordering and refreshing every token a model reads for a task. It covers instructions, tools, history, memory and retrieved passages. The goal is the smallest context that produces a correct result.

Is prompt engineering a component of context engineering?

Yes. Prompt engineering writes the instructions that sit inside the window. Context engineering also decides which tool results, documents and memories join them, in what order and at what token cost across the whole run.

What is context in artificial intelligence?

In artificial intelligence, context is whatever a program can use when it produces an output for a task. For a large language model it means the tokens in its window: instructions, conversation, retrieved passages and tool results.

Why is context engineering important?

Long inputs can lower accuracy and raise cost. Agents add content at every step. Kleio treats this as a data problem: its Knowledge Engine organizes products, documents and memories in three stores before an agent reads them.

How to implement context engineering?

Build a golden set, trace tokens per component then fix retrieval, compaction and caching in that order. In Kleio’s platform the work starts earlier with industry ontologies and versioned configurations that define what each agent receives.

What are the challenges in context engineering?

Context rot, stale records, conflicting sources, cost and permissions are the main ones. Kleio’s Memory Store handles conflicts openly: a disputed belief becomes contested and the agent asks the buyer a question instead of guessing.

What tools are used in context engineering?

Teams use frameworks such as LangGraph, LlamaIndex, DSPy or Haystack with vector databases, rerankers and evaluation libraries like Ragas. Kleio provides a platform layer for complex high-value sales with its Knowledge Engine and Agentic Orchestration.

What are the best practices for context engineering?

Keep the context small, put key evidence where the model uses it, cache a stable prefix and measure each change. Kleio adds governance: tenant isolation, role-based access per operation and pseudonymisation before any external model call.

Test