SysArt
Book a briefing
SysArt

Guide

What is context engineering?

Context engineering decides what a language model sees each time it is called: instructions, retrieved documents, tools, memory and conversation history. This guide covers what research shows about long contexts, the techniques that keep context small and relevant, and how to secure, measure and govern it on infrastructure you control.

Last reviewed by SysArt AI Architecture Team11 min readHow we review

In short

Context engineering decides what a language model sees at each call: instructions, retrieved documents, tool definitions and results, memory and conversation history, all within a limited context window. Because research shows that models use long inputs unreliably, and every token costs memory and time, the goal is the smallest relevant, permitted and traceable context that completes the task.

DefinitionContext engineering is the design and operation of everything a language model receives at inference time, including instructions, retrieved documents, tool definitions, tool results, memory and conversation history, selected, ordered and trimmed to fit a limited context window.

Key takeaways

  • Context engineering covers everything a model sees at each call: instructions, retrieved documents, tool definitions and results, memory and conversation history. Prompt engineering, the wording of instructions, is one part of it.
  • More context is not automatically better: studies show that models use information in the middle of long inputs less reliably, and that accuracy can fall as inputs grow even when the right information is present.
  • On your own servers, every token in context costs GPU memory and processing time, because the key-value cache grows with context length and with the number of concurrent requests.
  • Treat context as a security boundary: retrieve only what the user may see, handle retrieved text and tool results as untrusted data, and pass the least data the task needs.
  • Record what the model saw for each answer or action, and put prompts, tool definitions and retrieval settings under change control, with an evaluation set as the release gate.

What is context engineering?

Context engineering is the work of deciding what a language model sees each time it is called, and in what form.

Anthropic’s engineering team defines context as the set of tokens included when sampling from a large language model, and context engineering as the strategies for curating and maintaining the optimal set of tokens during inference. A token is the unit of text a model reads and writes, often a word or part of a word. The context window is the maximum number of tokens a model can handle in one call, including its output.

In an enterprise application, the context can hold six kinds of information:

  • Instructions: the system prompt, policies and examples.
  • Retrieved documents: passages found by search, as in retrieval-augmented generation.
  • Tool definitions: the names, descriptions and parameters of the tools the model may call.
  • Tool results: what those tools returned.
  • Memory: notes and facts stored outside the window and loaded when needed.
  • Conversation history: earlier turns of a dialogue, or earlier steps of an agent.

A 2025 survey of more than 1,400 research papers treats context engineering as a formal discipline beyond prompt design, spanning retrieval-augmented generation, memory systems, tool-integrated reasoning and multi-agent systems.

How is context engineering different from prompt engineering?

Prompt engineering is about how instructions are written; context engineering is about everything the model sees, of which the instructions are one part. Anthropic calls context engineering the natural progression of prompt engineering: building with language models becomes less about finding the right words and more about which configuration of context is most likely to produce the behaviour you want.

The difference shows most in agents, whose context changes at every step and has to be curated again before each call.

Prompt engineeringContext engineering
Main questionHow should the instructions be written?What should the model see at this step, and in what form?
ScopeSystem prompt, instructions, examples and output formatEverything in the window: instructions, retrieved documents, tool definitions and results, memory and history
When the work happensA discrete writing task, mostly at design timeBefore every model call, as the application assembles the context
Typical artefactsPrompt templates and few-shot examplesRetrieval pipeline, tool set, memory stores, compaction rules and token budgets
Typical failuresVague guidance, or brittle rules hardcoded in the promptMissing, stale, excessive, unauthorised or poisoned information
How it is testedPrompt variants against sample inputsEvaluation sets run across retrieval settings, tool sets and context lengths, plus records of what the model saw

Why does more context not mean better answers?

Because models do not use long inputs evenly or reliably: several studies show accuracy falling as inputs grow, well before the advertised context window is full.

  • Position matters. The “Lost in the Middle” study found a U-shaped curve: models used information best at the beginning or end of the input and worst in the middle. In one setting, GPT-3.5-Turbo did worse with the relevant document in the middle than with no documents at all. In open-domain question answering, 50 retrieved documents instead of 20 improved results by only about 1.5% for GPT-3.5-Turbo and 1% for Claude-1.3.
  • Advertised length is not usable length. RULER tested 17 long-context models, all claiming at least 32,000 tokens. Despite near-perfect scores on the simple needle-in-a-haystack test, almost all showed large drops as length grew, and only about half performed satisfactorily at 32,000 tokens.
  • Literal matching hides the problem. NoLiMa minimised the word overlap between each question and the fact that answers it. At 32,000 tokens, 11 of 13 models claiming at least 128,000 tokens fell below half of their short-input scores; GPT-4o dropped from 99.3% to 69.7%.
  • Length alone hurts. Du and colleagues found accuracy falling by 13.9% to 85% as inputs grew, even when the model could retrieve all the relevant information, and even when the extra tokens were blank space or masked out.

Anthropic’s engineers call this decline context rot. They relate it to the transformer architecture, in which every token attends to every other token, creating n² pairwise relationships for n tokens, and describe a gradient rather than a hard cliff. Test your own model at the lengths you will run, but the lesson holds: fewer, better passages, the most important information at the start or end, and nothing the current step does not need.

How does context length affect cost and latency?

Every token in context uses GPU memory and processing time. On infrastructure you run yourself, that becomes hardware: longer contexts mean fewer concurrent users per GPU, or more GPUs.

The main memory cost is the key-value (KV) cache: the attention keys and values of earlier tokens, kept so the model does not recompute them for each new token. The PagedAttention paper gives an example: a 13-billion-parameter model at 16-bit precision needed about 800 KB per token, so a single 2,048-token request could need up to 1.6 GB, and the total grows with the number of concurrent requests. Estimate it for your model, context length and load with the LLM GPU sizing calculator.

Latency follows. Before the first token appears, the model processes the whole prompt in a step called prefill, so longer inputs delay the answer. Agents multiply both effects: Anthropic reported that its agents typically use about four times as many tokens as chat interactions, and its multi-agent systems about fifteen times as many.

What are the security risks in a model’s context?

The main risks are passages a user may not see, instructions or false facts planted in retrieved content, more personal data than the task needs, and leaks through shared caches. Whatever enters the context can shape the answer and reappear in it, so treat the context as a security boundary.

  • Permission-aware retrieval. Return only passages the requesting user may read, filtered before they reach the model. OWASP lists unauthorised access and cross-context leaks among vector and embedding weaknesses, and recommends permission-aware vector stores with strict logical and access partitioning. Our article on policy-enforced RAG boundaries covers the design.
  • Untrusted content. Retrieved documents, web pages, emails and tool results can carry instructions. OWASP calls this indirect prompt injection, notes that RAG does not fully mitigate it, and advises segregating and identifying external content, least privilege and human approval for high-risk actions. Poisoning is related: the PoisonedRAG researchers made a RAG system give attacker-chosen answers with a 90% success rate by adding five crafted texts per target question to a knowledge base of millions.
  • The least data needed. Pass only what the current step requires. Under the GDPR’s data minimisation principle, personal data should be adequate, relevant and limited to what is necessary for the purpose, and a smaller context leaves less to leak.
  • Shared caches. A prefix cache shared between users can let one user infer what another sent from response times. vLLM’s per-request cache salt restricts reuse to requests with the same salt, which its documentation says prevents such timing-based attacks.

For agents, where tool results flow back into the context and outputs become actions, see our guide to AI agent security.

What are the main context engineering techniques?

Retrieval, just-in-time retrieval, a minimal tool set and token-efficient tool results control what enters the context; compaction, notes and sub-agents, covered in the next section, shrink what an agent has accumulated.

Retrieval-augmented generation (RAG) searches a document collection for the passages most relevant to a question and gives them to the model, which answers from them and can cite them. Our explainer on what retrieval-augmented generation is covers the pipeline. For context engineering, the decisions are how many passages to include, in what order, with which labels and under whose permissions; a short, well-ranked list is the better starting point.

Beyond retrieval:

  • Just-in-time retrieval. Instead of loading data before the call, an agent keeps lightweight references, such as file paths, stored queries or links, and loads data through tools when it needs it. Anthropic notes that runtime exploration is slower than retrieving pre-computed data, and suggests a hybrid: some data up front for speed, the rest on demand.
  • A minimal tool set. Every tool definition takes up context. Anthropic advises a minimal viable set of tools: if a human engineer cannot say which tool fits a situation, an agent cannot be expected to do better. With many tools, retrieve the relevant definitions first; in the RAG-MCP study, this more than tripled tool selection accuracy (43.13% against 13.62%) and cut prompt tokens by more than half.
  • Token-efficient tool results. Tools should return only high-signal information. Anthropic recommends pagination, range selection, filtering and truncation with sensible defaults; Claude Code limits tool responses to 25,000 tokens by default.

How does context engineering work for AI agents?

For agents, context engineering means deciding before every step what to carry forward, because each step adds tool calls, results and reasoning to the history. The code around the model, often called the agent harness, makes that decision; our guide to what an agent harness is covers its other jobs. Anthropic’s engineering team describes these techniques for long-running agents:

  • Tool-result clearing. Remove the raw output of tool calls made many steps ago. Anthropic calls this one of the safest, lightest-touch forms of compaction.
  • Compaction. When the conversation nears the window limit, summarise it and continue from the summary. Claude Code keeps architectural decisions, unresolved bugs and implementation details, plus the five most recently accessed files. Anthropic warns that overly aggressive compaction can lose subtle context whose importance only shows later.
  • Structured notes. The agent writes notes to memory outside the context window and reads them back later, which suits iterative work with clear milestones. Memory needs an owner, rules on what may be written, expiry and access control; see our article on scoping and expiring agent memory.
  • Sub-agents. A sub-agent works on a focused task in a clean context window and returns a condensed summary, often 1,000 to 2,000 tokens. It adds the token cost noted above, and Anthropic says tasks that need all agents to share the same context, or that have many dependencies between agents, are a poor fit today.

Each technique trades completeness for focus, so evaluate the agent on complete tasks, not single steps.

What is context window management on your own infrastructure?

Context window management keeps the input and the expected output within the model’s limit, and decides what to drop, summarise or move out when the window fills. On your own servers, the serving engine sets that limit and you pay for it in memory.

  • Engine limits. The limit that applies is the one you configure, which can be lower than the model’s maximum. In vLLM, the maximum model length covers the prompt and the output together, so the budget must leave room for the answer. Ollama’s documentation recommends at least 64,000 tokens for agents, web search and coding tools, and notes that a larger context length increases the memory needed to run a model.
  • Budgets. Give each part of the context a token budget, covering instructions, tool definitions, retrieved passages, history and the answer, and decide in advance what gives way first when a request exceeds it.
  • Prefix caching. vLLM’s automatic prefix caching reuses the KV cache of earlier requests when a new request shares the same prefix, which suits repeated questions over one long document and multi-turn conversations; it shortens prefill only, not token generation. SGLang’s RadixAttention also reuses the KV cache. vLLM identifies each cached block by its own tokens and all the tokens before it, so a change near the start of the prompt, such as a timestamp in the system prompt, prevents reuse of everything after it. Put stable content first and per-request content last. Our comparison of vLLM, SGLang, llama.cpp and Ollama covers each engine’s caching.
  • Metrics. vLLM exposes prompt-token counts, prefix-cache hits, KV-cache usage and time to first token, which show whether a context change helps or hurts.

How do you measure and govern context?

Treat context as configuration that changes behaviour: test it against an evaluation set, record what the model saw, and change it under control.

  • Evaluation sets. Build a set of real questions or tasks with expected answers and sources, and run it whenever a context setting changes, such as the number and order of passages, the tool set, compaction thresholds or memory rules. Score retrieval and generation separately: the Ragas framework, for example, distinguishes whether retrieval found relevant and focused passages from whether the model used them faithfully.
  • A record of what the model saw. For each answer or action, log the prompt and tool-definition versions, the retrieved passages and their versions, tool results, memory entries and summaries used, model and engine versions, and token counts per component. OWASP recommends detailed, immutable logs of retrieval activity. For high-risk AI systems, Article 12 of the EU AI Act requires that the system technically allows automatic logging of events over its lifetime; whether a RAG system or agent is high-risk depends on its intended purpose. The logs hold confidential and personal data, so keep them inside your boundary with access control and a retention period.
  • Change control. Version the system prompt, tool descriptions, retrieval settings, compaction rules and memory policies like code. Review each change, run the evaluation set before release and keep the previous version ready to restore.

Where should an enterprise start with context engineering?

Start with one use case and look at what its model actually receives today.

  1. Capture real contexts. Log a sample of complete model inputs and count tokens by component.
  2. Fix retrieval first. Enforce permissions before ranking, pass a short, well-ranked list of passages and label them as data.
  3. Set budgets. Allocate tokens per component, leave room for the answer and put stable parts first.
  4. Measure and govern. Build the evaluation set, test at realistic lengths and loads, and add the record of what the model saw and change control before go-live.
  5. Extend to agents. Start with a minimal tool set, just-in-time retrieval and tool-result clearing, and add compaction, notes or sub-agents only when evaluation shows the need.

SysArt builds these controls into enterprise RAG implementations and AI agents on infrastructure you control, from the retrieval pipeline and serving layer to the evaluation set and audit trail.

Frequently asked questions

What is context engineering in AI?

Context engineering is the work of choosing and arranging everything a language model receives when it is called: the system prompt, retrieved documents, tool definitions and tool results, memory and conversation history. Anthropic describes it as strategies for curating and maintaining the optimal set of tokens during inference. In practice it means deciding what to include, what to leave out, in what order, and how to keep the result secure and traceable.

What is the difference between context engineering and prompt engineering?

Prompt engineering is about writing and organising instructions. Context engineering covers everything the model sees at each step: the prompt, plus retrieved documents, tool definitions, tool results, memory and history. Anthropic contrasts the discrete task of writing a prompt with context engineering, which is iterative: the context is curated again each time the application decides what to pass to the model, which matters most for agents that accumulate tool results.

Is context engineering the same as RAG?

No. Retrieval-augmented generation (RAG) is one context engineering technique: it searches a document collection and passes the most relevant passages to the model. Context engineering also covers the system prompt, tool definitions and results, memory, conversation history and how all of them share a limited window. In an enterprise RAG system, it decides how many passages to include, in what order, with which labels and under whose permissions.

Do larger context windows make context engineering unnecessary?

No. Research on long inputs finds that models use information in the middle of a long context less reliably, that many models score well below their short-input level at lengths far inside their advertised windows, and that length alone can reduce accuracy even when the right information is present. Anthropic's engineers call this decline context rot. Longer contexts also cost more memory and time, so selection still matters.

How do AI agents manage their context window?

An agent's context grows with every tool call, so the code around the model has to keep it in check. Common techniques are loading data just in time through tools, clearing old tool results, compacting long histories into summaries, writing structured notes to memory outside the window, and giving focused subtasks to sub-agents that return short summaries. Each keeps the working context small but can lose detail or add cost, so evaluate agents on complete tasks.

How does context length affect GPU memory on-premises?

Each token in context occupies key-value (KV) cache memory on the GPU while the request runs, so memory grows with context length and with the number of concurrent requests. The PagedAttention paper gives an example: about 800 KB per token for a 13-billion-parameter model at 16-bit precision, or up to 1.6 GB for one 2,048-token request. Longer prompts also take longer to process before the first token appears.

Can retrieved documents manipulate an LLM?

Yes. OWASP describes indirect prompt injection as instructions that arrive through external content such as websites or files, and notes that RAG does not fully mitigate it. The PoisonedRAG researchers made a RAG system give attacker-chosen answers with a 90% success rate by adding five crafted texts per target question to a knowledge base of millions. Treat retrieved text and tool results as data, limit what the model can do and test with planted documents.

What should you log about an LLM's context?

Enough to reconstruct what the model saw for each answer or action: prompt and tool-definition versions, the identifiers and versions of retrieved passages, tool calls and results, memory entries and summaries used, model and engine versions, and token counts. The logs hold confidential and personal data, so keep them inside your boundary with access control and a retention period. Under the EU AI Act, high-risk systems must technically allow automatic event logging.

Sources

  1. Anthropic Engineering: Effective context engineering for AI agents (29 September 2025) · checked 29 October 2026
  2. Anthropic Engineering: Writing effective tools for agents (11 September 2025) · checked 29 October 2026
  3. Anthropic Engineering: How we built our multi-agent research system (13 June 2025) · checked 29 October 2026
  4. Mei et al.: A Survey of Context Engineering for Large Language Models (arXiv 2507.13334) · checked 29 October 2026
  5. Liu et al.: Lost in the Middle, How Language Models Use Long Contexts (TACL) · checked 29 October 2026
  6. Hsieh et al.: RULER, What's the Real Context Size of Your Long-Context Language Models? (COLM 2024) · checked 29 October 2026
  7. Modarressi et al.: NoLiMa, Long-Context Evaluation Beyond Literal Matching (ICML 2025) · checked 29 October 2026
  8. Du et al.: Context Length Alone Hurts LLM Performance Despite Perfect Retrieval (Findings of EMNLP 2025) · checked 29 October 2026
  9. Kwon et al.: Efficient Memory Management for Large Language Model Serving with PagedAttention (SOSP 2023) · checked 29 October 2026
  10. vLLM documentation: automatic prefix caching · checked 29 October 2026
  11. vLLM documentation: prefix caching design (block hashing and cache salting) · checked 29 October 2026
  12. vLLM documentation: engine arguments (maximum model length) · checked 29 October 2026
  13. vLLM documentation: metrics · checked 29 October 2026
  14. Zheng et al.: SGLang, Efficient Execution of Structured Language Model Programs (arXiv 2312.07104) · checked 29 October 2026
  15. Ollama documentation: context length · checked 29 October 2026
  16. Gan and Sun: RAG-MCP, Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation (arXiv 2505.03275) · checked 29 October 2026
  17. OWASP GenAI Security Project: LLM01:2025 Prompt Injection · checked 29 October 2026
  18. OWASP GenAI Security Project: LLM08:2025 Vector and Embedding Weaknesses · checked 29 October 2026
  19. Zou et al.: PoisonedRAG, Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models (USENIX Security 2025) · checked 29 October 2026
  20. Es et al.: Ragas, Automated Evaluation of Retrieval Augmented Generation · checked 29 October 2026
  21. European Commission: Principles of the GDPR (data minimisation) · checked 29 October 2026
  22. AI Act Service Desk: Article 12, record-keeping · checked 29 October 2026

Design the context for one use case

Bring a RAG or agent use case, the sources and tools it needs and the access rules that apply. In a briefing we outline the retrieval design, the context budget, the logging and the evaluation set that will show whether it works.