What Is Context Engineering? The Skill Replacing Prompt Engineering
November 18, 2026 · 12 min read

For a few years, getting good results from AI meant writing clever prompts. That still matters, but anyone building AI agents in 2027 has discovered a bigger problem: the prompt is only a small part of what the model sees. Instructions, tool definitions, retrieved documents, earlier messages, tool results and saved memories all compete for space in the model's limited working memory. Managing that space well is now the skill that separates reliable AI products from frustrating ones.
That skill is called context engineering. This guide explains what it is, how it differs from prompt engineering, why context is a scarce resource, the four core strategies teams use, a code example of a context budget, how it applies to coding agents and how to measure whether your context is working.
What Is Context Engineering?
Context engineering is the practice of deciding what information goes into a model's context window at each step, and in what form, so the model has exactly what it needs to succeed and as little as possible of what it does not.
Anthropic's engineering team, in its widely shared guide to effective context engineering for AI agents, describes it as curating and maintaining the best set of tokens during inference, including everything outside the prompt itself. It frames the goal as finding the smallest set of high-signal tokens that makes the desired outcome most likely, and it calls context engineering the natural progression of prompt engineering.
The term took off in June 2025, when Shopify's chief executive Tobi Lütke and AI researcher Andrej Karpathy both argued it described the real work better than "prompt engineering". Simon Willison predicted the term would stick because the popular meaning of prompt engineering had drifted towards typing tricks into a chatbot. It did stick, and in October 2026 Gartner named AI context platforms one of its top strategic technology trends for 2027.
Context Engineering vs Prompt Engineering
| Prompt engineering | Context engineering | |
|---|---|---|
| Focus | The wording of instructions | Everything the model sees at each step |
| Scope | Usually one request | Whole tasks, many turns and many tool calls |
| Main inputs | System prompt, examples, user message | Prompts plus tools, retrieved data, memory, history and state |
| Typical work | Rewriting, adding examples, setting format | Retrieval, summarising, pruning, memory design, splitting work across agents |
| Who does it | Anyone using AI | Mostly engineers building AI systems |
Prompt engineering has not disappeared. It is now one part of context engineering, and our prompt engineering guide covers the techniques that still matter.
Why Context Is a Finite Resource
Modern models accept huge inputs, often hundreds of thousands of tokens. It is tempting to pour everything in and let the model sort it out. That rarely works, for three reasons.
Performance degrades as context grows. In July 2025, Chroma published research on what it calls context rot. Testing 18 leading models, it found that performance becomes increasingly unreliable as input length grows, even on simple tasks, and that distracting, similar-looking information makes things worse.
Position matters. The well-known Lost in the Middle study found that models use information at the beginning and end of a long context more reliably than information buried in the middle.
Every token costs money and time. Bigger contexts mean slower responses and higher bills, especially for agents that call the model dozens of times per task.
Getting context right pays off. Gartner predicts that by 2027, organisations that prioritise semantics in AI-ready data will increase agentic AI accuracy by up to 80% and reduce costs by up to 60%.
The Building Blocks of an Agent's Context
- System instructions: the agent's role, goals, rules and output format.
- Tool definitions: names, descriptions and input schemas for every tool, often connected through the Model Context Protocol. Each tool costs tokens on every call, even when unused.
- Examples: a few demonstrations of good behaviour.
- Retrieved knowledge: documents, records and search results brought in for the current step, typically through retrieval-augmented generation.
- Conversation history: earlier messages from the user and the model.
- Tool results: outputs from searches, API calls and code execution, which can be large.
- Memory and state: notes, plans and facts saved from earlier steps or sessions.
Context engineering means managing all of these together, not just polishing the first one.
The Four Core Strategies: Write, Select, Compress and Isolate
LangChain's analysis of popular agents grouped context engineering techniques into four strategies, and the framework has become the standard way to think about the problem.
1. Write: save context outside the window
Agents write plans, notes and intermediate results to files, databases or memory stores instead of keeping everything in the conversation. They read back only what they need later. A coding agent that keeps a to-do list in a file can work for hours without losing track.
2. Select: bring in only what is relevant
Retrieve the few documents, records or tools that matter for the current step rather than loading everything. Techniques include semantic search, keyword search, filtering by metadata and loading tools on demand. Our guide on how to build a RAG app covers retrieval in depth.
3. Compress: keep the meaning, drop the bulk
Summarise long conversations, trim verbose tool output, replace raw data with key facts and remove results that are no longer needed. Many agents automatically compact their history when the window fills up.
4. Isolate: split context between agents or environments
Give subtasks to separate agents with their own clean context windows, then pass back only short summaries. This is the main reason multi-agent systems work well for broad research tasks. Sandboxes can also hold large objects, such as datasets, outside the model's context.
Example: A Context Budget in JavaScript
This simplified function applies the select and compress strategies. It ranks documents by relevance, skips weak matches, stops before the budget runs out and summarises older conversation turns. Running it includes the refund policy and shipping FAQ, drops the irrelevant careers page and the oversized product catalogue, and keeps the total to about 650 tokens out of a 2,000-token budget:
// Assemble an agent's context inside a token budget: select, then compress.
const estimateTokens = (text) => Math.ceil(text.length / 4); // about 4 characters per token in English
// Stand-in for a model call that writes a short summary of older messages.
function summarise(turns) {
return `customer asked about order ${turns[0].text.match(/A-\d+/)[0]} and a late delivery`;
}
function buildContext({ system, task, documents, history, budget }) {
const parts = [system, `Task: ${task}`];
let used = estimateTokens(parts.join("\n\n"));
// Select: most relevant documents first, skip weak matches, stop at 60% of the budget.
const included = [];
for (const doc of [...documents].sort((a, b) => b.score - a.score)) {
const cost = estimateTokens(doc.text);
if (doc.score < 0.5 || used + cost > budget * 0.6) continue;
parts.push(`<document source="${doc.source}">\n${doc.text}\n</document>`);
included.push(doc.source);
used += cost;
}
// Compress: keep the last four turns word for word and summarise anything older.
const recent = history.slice(-4);
const older = history.length - recent.length;
if (older > 0) parts.push(`Summary of ${older} earlier messages: ${summarise(history.slice(0, older))}`);
for (const turn of recent) parts.push(`${turn.role}: ${turn.text}`);
const prompt = parts.join("\n\n");
return { prompt, included, tokens: estimateTokens(prompt) };
}
const documents = [
{ source: "refund-policy.md", score: 0.92, text: "Refunds are allowed within 30 days of delivery. ".repeat(20) },
{ source: "shipping-faq.md", score: 0.81, text: "Late deliveries over 5 days qualify for a shipping refund. ".repeat(20) },
{ source: "careers-page.md", score: 0.12, text: "We are hiring engineers. ".repeat(20) },
{ source: "full-product-catalogue.md", score: 0.55, text: "Product details. ".repeat(4000) },
];
const history = [
{ role: "user", text: "Hi, my order A-1042 has not arrived." },
{ role: "assistant", text: "Sorry to hear that. Let me check." },
{ role: "user", text: "It was due last Monday." },
{ role: "assistant", text: "I can see it is delayed by 6 days." },
{ role: "user", text: "Can I get my shipping cost back?" },
{ role: "assistant", text: "Let me check the policy for you." },
];
const result = buildContext({
system: "You are a support agent. Answer using only the documents provided.",
task: "Decide whether the customer qualifies for a shipping refund.",
documents,
history,
budget: 2000,
});
console.log("Included:", result.included.join(", "));
console.log("Estimated tokens:", result.tokens);
Real systems use a proper tokenizer and a model to write summaries, but the principle is the same: decide deliberately what earns a place in the window.
Context Engineering for Coding Agents
Coding agents show context engineering at its most practical:
- Project instructions: a short AGENTS.md file tells every agent your commands and conventions. Research from ETH Zurich found that bloated, auto-generated files can lower success rates and raise costs by more than 20%, so brevity matters.
- Just-in-time file reading: rather than loading a whole codebase, good agents search and open files as needed.
- Skills with progressive disclosure: the Agent Skills open standard, released by Anthropic in December 2025, loads only each skill's name and description at first and pulls in full instructions and reference files when a task needs them.
- Lean tools: fewer, well-described tools with compact outputs. If you build your own tools, our tutorial on how to build an MCP server explains how to keep results small.
Common Context Failures
Drew Breunig named four failure patterns that LangChain and others now use widely:
- Context poisoning: a hallucination or error enters the context and gets repeated as if it were fact.
- Context distraction: so much history builds up that the model leans on it instead of reasoning freshly.
- Context confusion: irrelevant information, often too many tools, leads to wrong choices.
- Context clash: new information contradicts earlier content, and the model gets stuck between them.
Context also has a security side. Anything placed in the context can influence the model, including malicious instructions hidden in documents or web pages. Separating trusted instructions from untrusted data is part of good context engineering.
How to Measure Whether Your Context Is Working
- Task success rate: run a fixed set of real tasks and track how many succeed after each context change.
- Tokens and cost per task: watch for growth that does not improve results.
- Retrieval quality: check whether the right documents appear in the context, and how much irrelevant material comes with them.
- Latency: measure time per step, since larger contexts slow responses.
- Trace reviews: read real agent traces to see what the model actually saw when it made a wrong decision.
Better context often reduces costs as well as improving accuracy, which matters when you plan budgets. Our breakdown of AI app development costs shows how model usage affects running costs.
How to Learn Context Engineering
If you already build software, you have most of the foundations. Focus on retrieval and search, summarisation, state and memory design, evaluation and observability, plus a working knowledge of how models handle long inputs. Build a small agent, log everything it sees and iterate on its context with a fixed test set. Our guide to agentic AI is a good starting point if agents are new to you.
A Quick Context Engineering Checklist
- Every instruction in the system prompt is specific, current and necessary.
- The agent sees only the tools it needs for this task, each with a clear description.
- Retrieval returns a small number of highly relevant items, with sources attached.
- Large tool results are filtered, paginated or summarised before they reach the model.
- Long conversations are compacted, and important state is written to files or memory.
- Untrusted content is clearly separated from trusted instructions.
- A fixed evaluation set runs after every change to prompts, tools or retrieval.
Frequently Asked Questions
Who coined the term context engineering?
It spread in June 2025 when Shopify's Tobi Lütke and Andrej Karpathy both promoted it as a better description than prompt engineering. Several builders had used similar language before, and Anthropic and LangChain helped define the practice.
Is context engineering just RAG?
No. Retrieval-augmented generation is one technique within the select strategy. Context engineering also covers instructions, tools, memory, history, summarisation and splitting work between agents.
Do bigger context windows remove the need for context engineering?
No. Research on context rot shows that performance becomes less reliable as inputs grow, and larger contexts cost more and run slower. Bigger windows give you more room, not permission to fill it.
What is context rot?
Context rot is the decline in a model's reliability as its input gets longer, even on simple tasks. Chroma's 2025 research found the effect across all 18 models it tested.
What tools help with context engineering?
Vector and keyword search, agent frameworks with memory and summarisation features, tracing and evaluation tools, and standards such as MCP and Agent Skills all help you control what enters the context.
Is context engineering a real job skill?
Yes. It is now a core skill for AI engineers and anyone building agents, often listed alongside retrieval, evaluation and agent design in job descriptions.
Engineer the Context, Not Just the Prompt
Context engineering is where most of the quality, cost and reliability of an AI system is decided. Keep the context small and relevant, write state outside the window, compress what you keep and isolate big subtasks. Then measure everything. If you want help designing agents that stay accurate and affordable as they scale, contact our team to discuss your project.
