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.
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.
A more powerful LLM will fix the problem.
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:
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.
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:
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.
The prompt is just one of the elements context engineering assembles.
Prompt engineering is dead.
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.
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
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.
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.
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.
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.
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.
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.
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:
- System instructions and rules
- Tool definitions
- Memory and reference documents
- Recent history
- 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.
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.
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.
One common format: each source is exposed once and stays available to any compatible agent.
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.
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.
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:
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.
Context engineering use cases in the enterprise
A customer support agent that knows the customer’s history
A document search assistant to chat with your data
A coding agent that understands the whole codebase
Business document analysis in regulated industries
Context engineering best practices: the checklist
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.
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.
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.






