Home » Blog » Context engineering: definition, techniques and best practices for reliable AI agents
context-engineering-ai-agents

Context engineering: definition, techniques and best practices for reliable AI agents

Reading time: 22 minTemps de lecture : 22 min

In short

Context engineering in 30 seconds

Context engineering is the practice of giving an LLM the right information, at the right time, in the right format: instructions, conversation history, memory, retrieved documents and tool results. It extends prompt engineering to the scale of a whole system. Its goal is to prevent the context failures that break AI agents in production. It relies on four families of techniques (write, select, compress, isolate) and is driven by measurement: accuracy, token cost and latency.

Context engineering has become a core skill for anyone building reliable AI agents with large language models. The pattern is familiar: an agent that shines in a demo starts hallucinating, ignoring its instructions or contradicting itself once it reaches production. Most of the time, the model is not the problem. The information it receives is: incomplete data, poorly chosen documents, an overloaded context window. This guide covers the techniques, architecture and best practices to select, structure and organize an LLM‘s context, so your AI applications gain accuracy, reliability and performance in production.

What is context engineering?

Context engineering definition

Context engineering is the discipline of designing everything a large language model (LLM) receives to complete a task: which information, at what moment and in what format.

An LLM never answers from the user query alone. Its output depends on everything in its context window: system prompt, conversation history, memory, documents fetched through retrieval-augmented generation (RAG) and the results of tool calls. Context engineering means managing these tokens to provide the right information, no more and no less. Instead of writing a single prompt, you design a system that assembles relevant context at every step, based on the user and the task at hand.

Why context engineering matters

Its importance comes down to one fact: the quality of an output depends less on the model than on the information it receives.

How does an LLM understand context?

An LLM is stateless: it keeps nothing from one request to the next. On each call, it only “knows” what sits in its context window, plus what it learned during training. Its reasoning relies on an attention mechanism that spreads a limited capacity across every token it receives. Anthropic calls this an attention budget: every extra token draws on it. The goal is therefore the smallest possible set of high-signal tokens.

?
Did you know?

An LLM is a CPU, its context is RAM. Andrej Karpathy compares the LLM to a processor and its context window to a computer’s RAM: a limited workspace that has to be filled with care.

From demo to production: why AI agents fail

In a demo, an agent handles a short request with clean data. In production, it chains dozens of tool calls, piles up a long history and pulls from heterogeneous sources. Every step adds noise. In Redis’s “The State of Context Engineering 2026” survey, 73% of IT and AI leaders say their agents fail more often because of broken context than because of the model.

Myth vs reality
The LLM is not the only lever
Myth

A more powerful LLM will fix the problem.

Reality

Without relevant context, even the best model produces wrong or incomplete outputs. Context management matters as much as model choice.

Accuracy, cost, latency, privacy: what’s at stake for enterprises

Poorly designed context has direct consequences for any enterprise:

Accuracy
Incomplete answers or hallucinations that erode user trust.
Cost
Every useless token is billed, on every request.
Latency
Overlong context slows processing and hurts the user experience.
Privacy
Sensitive data injected without control creates a leak risk and a governance issue.

Anatomy of a context window: what the model actually sees

The context window holds everything the LLM reads before answering. To make it concrete, take an HR assistant that answers employees’ questions about their paid leave.

Infographic
What a context window contains
System instructions
Source: Project team
Static
Examples (few-shot)
Source: Project team
Static
Tool definitions
Source: Connected tools (API, MCP)
Static
Long-term memory
Source: External storage
Dynamic
RAG documents
Source: Document base
Dynamic
Conversation history
Source: Current session
Dynamic
User query
Source: User
Dynamic
Output format
Source: Application
Static

Blue: static elements that rarely change. Pink: dynamic elements recomputed on every call.

System prompt

The system prompt sets the agent’s role, tone and rules: “You are the company’s HR assistant. Answer only from the documents provided and cite your sources.”

Few-shot examples

A few well-chosen examples show the expected behavior better than long instructions: two sample questions with their ideal answers, for instance. This few-shot approach also sets the tone and level of detail.

User query

The user query (or user input) is the request at a given moment, often short and ambiguous: “How many days of leave do I have left?” On its own, this message is not enough to answer.

Conversation history and short-term memory

Previous exchanges in the session form short-term memory. Thanks to them, the assistant understands “And for next year?” without the employee rephrasing. But the history grows with every turn.

Long-term memory

Stored outside the LLM and re-injected when needed, long-term memory keeps durable information across sessions: the employee’s department, status and preferred format.

Documents retrieved through RAG

Retrieval-augmented generation (RAG) fetches the relevant passages from a document base, here the company leave agreement. The LLM then grounds its answer in verifiable sources.

Tool definitions and results

Each tool describes a possible action, such as querying the HR software. Its result is added to the context, like a leave balance updated in real time.

Expected output format

A structured output, such as a JSON schema, defines the shape of the result so an application can use it directly:

response.json
{
  “remaining_days”: 12,
  “source”: “Leave agreement, article 4”
}

Static vs dynamic context

System instructions, examples and tool definitions are static: they rarely change. The query, history, documents and tool results are dynamic: they are recomputed on every call.

Context engineering vs prompt engineering, RAG and fine-tuning

These approaches don’t compete: they act at different levels to improve what an LLM produces.

What is the difference between context engineering and prompt engineering?

Prompt engineering focuses on how an instruction is worded: word choice, few-shot examples, requested reasoning steps. Context engineering covers the model’s entire information environment, of which the prompt is only one part. One optimizes a message; the other designs a system. Prompt engineering becomes one of its components: an evolution rather than a break.

Context engineering: the whole information environment
Prompt (prompt engineering)System instructionsFew-shot examplesHistoryMemoryRAG documentsTool resultsOutput format

The prompt is just one of the elements context engineering assembles.

Myth vs reality
Prompt engineering isn’t dead
Myth

Prompt engineering is dead.

Reality

Writing good instructions is still essential. But a perfect instruction can’t make up for incomplete or poorly organized context.

What is the difference between RAG and context engineering?

RAG is a retrieval technique. It searches a document base for relevant passages, usually with embeddings, then injects them into the context. It answers one question: which documents should the model see? Context engineering also decides their order, volume and format, and how they fit with the history and tools.

Query
The user question
Search
Embeddings and filters
Passages
The most relevant ones
Assembly
Order, volume, format
Answer
Generated by the LLM

RAG covers finding passages; assembling the context, in pink, is context engineering.

Context engineering vs fine-tuning: change the context, not the model

Fine-tuning changes the LLM’s parameters through additional training. It remains useful to enforce a style, a format or very specific domain vocabulary. For knowledge that changes, working on the context is better: faster, cheaper and easier to update.

What is the difference between context engineering and harness engineering?

Harness engineering designs the agent’s execution environment: decision loop, available tools, guardrails, error handling. Context engineering focuses on what goes into the LLM at each call. The two are complementary: the harness produces the context, and context engineering optimizes it.

Comparison table

CriterionPrompt engineeringContext engineeringRAGFine-tuning
GoalWrite a clear instructionProvide the right information at every stepGround answers in documentsAdapt the model’s behavior
What changesThe prompt textThe whole contextThe injected documentsThe model’s parameters
CostLowModerateModerateHigh
Time to implementImmediateShort to mediumMediumLong
Best forOne-off requestsAI agents in productionQuestions over a document baseVery specific style or format

Context failures: when more information makes answers worse

Poorly filled context doesn’t always cause a visible error. It degrades results gradually. Six failure modes stand out, following Drew Breunig’s typology, now a reference. Several studies published in 2026, including Dhara and Sheth’s, confirm that the latest models remain exposed.

Context rot
Quality drops as the conversation grows
→ Summarize the history
Lost in the middle
The middle of the context gets less attention
→ Put key information first or last
Context poisoning
An error gets reused as a fact
→ Validate before storing
Context distraction
The agent repeats past actions
→ Compress past exchanges
Context confusion
Too many tools or irrelevant details
→ Provide only what is needed
Context clash
Sources contradict each other
→ Date and discard outdated content

The six context failure modes: symptom and fix.

Context rot: context that wears out as it grows

Symptom: Quality drops as the conversation gets longer. Typical case: After fifty exchanges, the assistant forgets a rule given at the start. Fix: Summarize the history and restart from a lighter base.

Lost in the middle

Symptom: The LLM uses the beginning and end of its input well but neglects the middle. First identified in 2023, this bias has weakened considerably in recent models without disappearing. Typical case: The decisive clause, buried in the middle of a long document, is ignored. Fix: Place critical information at the start or end of the window.

Context poisoning: one error contaminates the rest

Symptom: A hallucination enters the history, and the agent then reuses it as fact. Typical case: A wrong case number, noted once, reappears at every following step. Fix: Validate information before storing it.

Context distraction: the model gets lost in its history

Symptom: The agent repeats past actions instead of reasoning about the current task. Typical case: Faced with a very long history, it replays an old approach that no longer fits. Fix: Compress past exchanges.

Context confusion: too many tools, too much irrelevant information

Symptom: Superfluous elements steer the output in the wrong direction. Typical case: With forty tools available, the agent calls the wrong one. Fix: Provide only the tools and documents needed for the current step.

Context clash: contradictory information

Symptom: Two sources in the window contradict each other. Typical case: The old and new versions of a procedure are retrieved together. Fix: Date your documents and discard outdated versions.

Is a bigger context window enough?

No. Frontier LLMs now accept around one million tokens, and some open-source models, such as Llama 4 Scout, advertise up to ten million. Their attention capacity is still limited. More room doesn’t guarantee better reading: filtering remains essential.

Key figure

Up to 30 times more misses. In a study published in May 2026 (Martin and Roger), Claude Opus 4.6, GPT-5.4 and Gemini 3.1 missed a risky action 2 to 30 times more often when it occurred after 800,000 tokens of normal activity.

Key context engineering techniques

The LangChain team, which publishes open source frameworks, groups context management techniques into four families: write, select, compress and isolate. Three optimization levers complete them: tools, ordering and caching.

Write
Store what must be remembered outside the window
Select
Retrieve only relevant information
Compress
Summarize to free up space
Isolate
Split work across sub-agents

The four families of context engineering techniques.

Write: external memory and structured note-taking

The principle: store what needs to be remembered outside the LLM (goals, decisions, completed steps), then read it back when needed. This working memory survives even when the history is cleared. Claude Code, for example, relies on note files.

agent-notes.md
Goal: compare 3 supplier contracts
Done: contracts A and B reviewed
Next: contract C, then summary

Select: semantic search, filtering and relevance scoring

Keep only the data most useful for the question at hand. Semantic search, based on embeddings, finds passages close to the query. Metadata filters (date, author, source type) narrow the results, then a relevance score ranks passages against the conversation context.

Expert tip

Chunking beats model choice. At Kairntech, in our document RAG projects, we see that the quality of document chunking and metadata matters more than the choice of model. A well-chunked, well-described passage is a passage that gets found.

Retrieve upfront or on demand: agentic search

Upfront retrieval loads documents before calling the LLM. Agentic search lets the system fetch information itself, “just in time”, from a document base or the web, as the next step requires. As Anthropic describes it, the agent keeps lightweight references (file paths, links, stored queries) and loads the content only when it needs it.

Compress: summarization and compaction

When the token limit gets close, the history is summarized: decisions made, open questions and errors to avoid are kept. Compaction frees up space without losing the thread of reasoning.

Isolate: sub-agent architectures

A complex task is split across several sub-agents, each with its own workspace. Each one explores a lead and only returns a summary to the orchestrator.

Orchestrator
Receives summaries only
↓ task↑ summary
Sub-agent 1
Its own context window
↓ task↑ summary
Sub-agent 2
Its own context window
↓ task↑ summary
Sub-agent 3
Its own context window

Each sub-agent explores one lead in its own window and only returns a summary.

Manage the agent’s tools dynamically

Exposing every available function makes each call heavier. It’s better to load only the tools useful for the current step: fewer descriptions to read, fewer tokens consumed and fewer wrong calls.

Order and structure information in layers

A stable order helps the LLM prioritize:

  1. System instructions and rules
  2. Tool definitions
  3. Memory and reference documents
  4. Recent history
  5. User query, last

Cut costs and latency with prompt caching

Prompt caching avoids reprocessing, on every call, the part of the context that doesn’t change. With Anthropic and on the latest OpenAI models, a cached token costs up to ten times less, and responses arrive faster.

Pro tip

Stable first, variable last. Put stable elements (instructions, tools, reference documents) at the beginning and variable elements at the end. Caching applies to the shared beginning of requests: the longer it is, the bigger the savings.

Context engineering tools and frameworks

No single tool does context engineering on its own: each one handles a link in the chain.

ToolRole in the chainWhen to use it
LangChainAssemble prompts, tools and sourcesPrototype an LLM application quickly
LangGraphOrchestrate agents with persistent stateMulti-step or multi-agent workflows
Vendor agent SDKsBuild an agent with one LLM provider’s componentsProjects centered on a single provider
LlamaIndexIndex and query documentsRAG over a large document base
Vector databaseStore and search embeddingsSemantic search at scale
Knowledge graphConnect entities and relationshipsHighly structured business data
MCP serverExpose a source or tool to the agentConnect internal systems

Orchestration frameworks and SDKs: LangChain, LangGraph, LlamaIndex and vendor SDKs

LangChain provides the building blocks: connectors, prompt management and tool calls. LangGraph, from the same team, orchestrates agents as a graph and keeps a state between steps. Both are on actively maintained 1.x versions; only the older 0.x versions reach end of support in December 2026. LlamaIndex specializes in ingesting and querying documents. Since 2025, LLM providers have also shipped their own agent SDKs: OpenAI’s Agents SDK, Anthropic’s Claude Agent SDK and Google’s Agent Development Kit. They are lighter, but tie your project to one ecosystem. None of these tools defines a context strategy for you.

Storage building blocks: vector databases, knowledge graphs and memory

Three types of storage feed the context window:

  • Vector databases: they store embeddings and power semantic search.
  • Knowledge graphs: they connect business entities (customer, contract, product) to provide structured context.
  • Persistent memory: preferences and durable facts, kept outside the LLM from one session to the next.

A growing number of enterprises bring these building blocks together in a shared context layer, so every agent draws on the same governed sources.

The Model Context Protocol (MCP): connecting agents to their sources

The Model Context Protocol (MCP) standardizes how an agent connects to its sources. Managed since December 2025 by the Agentic AI Foundation under the Linux Foundation, it is supported by ChatGPT, Gemini, Microsoft Copilot and Claude. Its July 2026 specification made it stateless, which makes it easier to deploy at scale. Each MCP server exposes a tool or data source (CRM, document management, GitHub repository) in a common format: a connector written once works with any compatible client.

AI agent (MCP client)
↕
MODEL CONTEXT PROTOCOL
↕
CRM
MCP server
Document management
MCP server
Database
MCP server
GitHub repository
MCP server

One common format: each source is exposed once and stays available to any compatible agent.

Note

Frameworks orchestrate, they don’t decide. Choosing which information to provide remains a design decision, specific to each use case. No tool makes it for you.

How to implement context engineering, step by step

An effective approach follows five steps, from analyzing the need to continuous improvement.

1
Define
the task and information
2
Prepare
your sources
3
Design
the pipeline
4
Measure
quality
5
Iterate
with feedback

The five steps of a context engineering approach.

Step 1: define the task and the information it needs

Before writing any code, describe clearly what the agent must produce. Three questions guide the analysis:

  • Which information is essential to handle the request?
  • Where does it live, and how often does it change?
  • In what format will the output be used?

Step 2: prepare your sources (document quality, chunking, metadata)

Your context will never be better than your sources. Clean your documents, chunk them along their structure (headings, sections, tables) and enrich each passage with metadata: date, author, type, confidentiality level.

Common mistakes

What sabotages a corpus. Indexing everything without sorting, ignoring tables and scanned PDFs, forgetting to re-index after an update: three mistakes that hurt relevance at the source.

Step 3: design the context pipeline

The pipeline sets, for each call, which sources to query, how many passages to keep, in what order to assemble them and when to compress the history. Document these rules: they form your application’s context strategy.

Step 4: measure context quality

Four metrics are enough to steer evaluation:

MetricWhat it measuresHow to track it
AccuracyShare of correct outputsA reference question set validated by domain experts
Faithfulness to sourcesClaims backed by a provided documentCitation checks, automated LLM-as-judge evaluation
Token usageVolume sent on each callCall logs
LatencyTime between query and outputProcessing-time monitoring in production

Step 5: iterate with continuous evaluation and feedback loops

Collect user feedback (votes, corrections), analyze failures and adjust the pipeline. Every change in sources or usage calls for a new evaluation.

Before and after: same prompt, two contexts

Take a legal assistant asked about a client contract.

Question asked: “What is the termination notice period in the Acme contract?”
Without context
What the LLM receives
The question alone
Output
“Notice periods usually range from one to three months.” Generic and unverifiable.
With structured context
What the LLM receives
The question, the Acme contract retrieved through RAG and a citation instruction
Output
“Three months, per article 12 of the contract.” Accurate and sourced.

Context engineering use cases in the enterprise

A customer support agent that knows the customer’s history

NeedAnswer quickly and correctly.
Context providedCustomer record, past tickets and the support knowledge base.
BenefitFewer escalations and more consistent support across channels.

A document search assistant to chat with your data

NeedFind information scattered across thousands of files.
Context providedPassages retrieved through RAG, filtered by access rights and date.
BenefitSourced answers, without manual digging.

A coding agent that understands the whole codebase

NeedChange code without breaking what already works.
Context providedRelevant files, project conventions and team standards, Git history.
BenefitSuggestions consistent with the codebase.

Business document analysis in regulated industries

NeedAnalyze contracts, reports or compliance files.
Context providedUp-to-date reference texts and citation instructions.
BenefitTraceable analysis that compliance teams can audit.

Context engineering best practices: the checklist

Checklist
Is your context ready for production?

Before putting an agent into production, check every item:

  • Goal and output format defined before choosing sources
  • Only the information needed for the current step is provided
  • Documents chunked along their structure and enriched with metadata
  • Stable elements first, user query last
  • History summarized before the window fills up
  • Number of exposed tools kept to the strict minimum
  • Long searches delegated to sub-agents
  • Sources cited in every output
  • Accuracy, cost and latency measured after every change
  • A complete, up-to-date register of approved sources

Challenges and the future of context engineering

Securing the context: prompt injection and sensitive data

An agent should only retrieve data the user is allowed to see. Access control therefore becomes a central security and governance issue.

Watch out

Data is not an order. A retrieved document or web page can contain malicious instructions (prompt injection). Treat it as data, never as instructions.

Toward automated and multimodal context engineering

Next-generation systems will build their own context: choosing sources, compressing and forgetting automatically. They will also bring in images, audio and video, with the same need to filter.

How we put context engineering into practice at Kairntech

Conversational RAG enriched with metadata and linked to its sources

Our assistants run on a customized conversational RAG. Every passage is enriched with metadata, and every answer links back to its source documents, which users can open.

On-premise deployment to keep control of context and data

We deploy our platform on-premise, with locally run LLMs, single sign-on (SSO) and a secured REST API. Your data and your context stay within your infrastructure.

A low-code environment so domain experts can build their own pipelines

Our low-code environment provides ready-to-use NLP techniques and leaves you free to choose your LLM. Domain experts experiment with and adjust their pipelines without writing code.

Continuous quality evaluation to keep our assistants reliable

We build in quality evaluation, feedback loops and, when needed, fine-tuning, so our context-aware assistants stay reliable over time.

Key advantage

End-to-end control. With Kairntech, you keep control of your context and data, with clear governance and no dependence on a single LLM provider.

Want more reliable AI assistants? Book a demo or download our white paper.

Context engineering glossary

TermMeaning
Context windowThe maximum amount of text an LLM reads in one call.
TokenThe unit of text an LLM processes and bills.
Context rotContext wear: quality drops as context grows.
CompactionSummarizing the history to free up space.
MemoryInformation kept outside the LLM and re-injected when needed.
RAGRetrieval-augmented generation: answering from retrieved documents.
EmbeddingA numerical representation of text, used for semantic search.
MCPStandard protocol connecting agents, tools and sources.
Sub-agentA secondary agent handling an isolated task.

Context engineering FAQ

What is a context engineer?

A context engineer designs the context of AI applications: sources, retrieval pipelines and assembly rules. The role combines software development, data management and LLM evaluation skills.

What is context engineering in agentic AI?

It is the management of context for an agent that chains several steps and tools. At every call, you decide what to keep, summarize or discard.

Is context engineering only for developers?

No. Organizing documents, writing instructions or choosing sources is also work for domain experts. Short training is enough to learn the basics, and low-code platforms open design to non-technical profiles.

How does ChatGPT maintain context?

It sends the conversation history back to the LLM with every message. Across sessions, two mechanisms add to this: saved memories, which users can view and delete, and references to past chats. Each can be turned off in the personalization settings.

Is ChatGPT a RAG model?

No. ChatGPT is an assistant built on an LLM. It does apply RAG-like logic when it searches the web or queries files provided by the user.

Is RAG a part of NLP?

Yes. RAG belongs to natural language processing (NLP): it combines information retrieval and text generation, in the service of generative AI.

Share thisPartager

Related posts