May we use cookies so Meta, Google, LinkedIn and ChatGPT see your visit and we learn which ads work? PrivacyMay we use cookies to see which pages help, and let Meta, Google, LinkedIn and ChatGPT see your visit, so we know which of our ads work? That way we spend less on ads that do not work. We do not sell your data, and the site works the same if you decline. You can change your answer at any time under Cookie settings at the foot of the page. Privacy policy
Loading...
System Design and AI Engineering, by Roni Das. 989 interactive lessons in two courses.: 770 in System Design and 219 in AI Engineering.
Context Engineering Explained: What Goes in the Window, What to Leave Out, and Why
What is context engineering?
Context engineering is choosing what goes into a language model's context window on every call: instructions, tool definitions, retrieved documents, memory and earlier turns, in what order, and what to leave out. It matters because a model is stateless and rereads only what you send, and because more text is not better: models get worse as the input grows, well before the window is full. In our measured runs, sending 20 documents instead of 5 cut the questions the model got right from 10 of 20 to 6 of 20, and 100 tools instead of 5 made each reply about 13 times slower.
Answer last checked
Save your progress and get the AI Engineering cheat sheet PDF
AI Engineering Cheat Sheet: what our labs measured, one rule per result. 12 pages. Free with an account.
This guide answers 12 questions about context engineering: what it is, how it differs from prompt engineering, what really fills an agent's context window, and how tool count, the number of retrieved documents and their order change the result. The measured numbers come from the agents and evaluation lessons of our AI Engineering course; the outside findings are linked under each answer.
Context engineering is deciding what fills this bar on every step (a worked example budget)On every step an agent's model reads one block of text: instructions, tool definitions, retrieved facts, a summary of old turns and the recent turns word for word. In this worked example the recent turns take about two thirds of the space, which is where most context engineering decisions land.
Context engineering is deciding what fills this bar on every step (a worked example budget)On every step an agent's model reads one block of text: instructions, tool definitions, retrieved facts, a summary of old turns and the recent turns word for word. In this worked example the recent turns take about two thirds of the space, which is where most context engineering decisions land.
The short version
Send the smallest set of text that does the job. Keep fixed instructions and hard rules in a protected block at the top, describe only the tools this step needs, store big tool results outside the prompt with an id, retrieve fewer documents than the retrieval metric tempts you to, and put the current instruction near the end. Then measure the right-answer rate at the context sizes your agent really reaches.
Readers in India pay in rupees; readers in the US, UK, Singapore, Australia and the Gulf see US dollar prices and can pay by card or PayPal. The pages for your region: India, Singapore, Australia, the Gulf and UK and Europe.
This page is the free part.
The course goes deeper on Context engineering
₹1,333 in India/$35 everywhere elseonce, for the whole course
The Generative AI and Agentic AI course covers Context engineering across a run of lessons, not one page. These 4 alone are about 224 minutes of step-by-step reading, every one with code you run in the browser, all with a quiz.
Agents have no memory between calls. What the model sees is the transcript you resend every step, and what it forgets is whatever you cut to fit. How to manage both.
A model's recall falls as its window fills, and worst from the middle. Measure the fill level where your agent starts to rot, and re-run it per model version.
Two small models, 60 requests, each offered 5 to 100 tools. Picking the right tool barely suffered until 100 tools, and look-alikes alone did no harm. The bigger problems were elsewhere: right choices written as broken JSON, valid calls that Ollama's chat API silently dropped, and replies that took 13 times longer with every tool on offer.
Raising k took recall@k from 45% to 90% on 818 documents, and took the number of questions the system actually got right from 10 of 20 down to 6. Same retrieval, same questions, no judge in the grading path. The component metric cannot go down, which is what makes it dangerous to optimise.
A language model knows nothing about your task except the text you send it on that call. Context engineering is the work of choosing that text, call after call, as an agent runs.
What is context engineering?
Context engineering is deciding what goes into a model's context window on each call: the instructions, the tool definitions, the documents you retrieve, the memory you carry forward and the conversation so far, in what order, and what you leave out. Anthropic defines it as the set of strategies for curating and maintaining the best set of tokens during inference, including everything that lands there outside the prompt itself.
The reason it needs a name is that a model is stateless. On every step of an agent, your code resends the whole picture, and the model rereads it from the top. Whatever you put in, it can use. Whatever you cut, it has forgotten, and it will not tell you.
What is the difference between context engineering and prompt engineering?
Prompt engineering is writing the instructions well: the wording, the examples, the format you ask for. Context engineering is the larger job around it: everything else that fills the window, such as tool results, retrieved documents, memory and earlier turns, and how all of it changes from step to step of a long run.
For a single question and answer the two are nearly the same thing. For an agent that runs 40 steps, the instructions are a small fixed block and most of the window is material your code chose to keep, fetch or drop. That is where most of the quality and most of the cost are decided.
A billing agent. The user gives an account id on turn 2 and asks about it again on turn 30. Between those turns, tools have fetched a pricing table, an FAQ page and a status page. If your code simply drops the oldest turns to make room, the account id goes with them, and the agent answers with a guess. If it keeps turns by how relevant they are to the current question, the id survives.
The same agent shows the other moves: the rule never delete without confirming lives in a protected block that is never summarised, big tool results are stored outside the prompt with a short head and an id the agent can fetch again, and only the tools this step needs are described.
No, and this is the main reason the field exists. Chroma's context rot study tested 18 models and found they got worse as the input grew, on deliberately simple tasks, well before the advertised window limit. The older lost-in-the-middle study found models use facts at the start and end of a long input more reliably than facts in the middle.
The failure is silent. Crossing the window limit gives you an error. Everything below it succeeds, and the only symptom is a slightly higher share of wrong answers. Anthropic's advice is to find the smallest possible set of high-signal tokens that gets the result you want.
Most of an agent's window is not instructions. It is the history and the tool output your code chose to keep, and it is paid for again on every step.
Keep hard rules out of the part of the context that gets summarisedSummarising old turns is necessary on a long run, and it loses detail on purpose. Rules that must never be lost, such as confirm before any delete, belong in a protected block the summariser never touches.
Because the whole transcript is resent on every step, so a tool result fetched on step 3 is paid for on step 4, step 5 and every step after. The course counted a 40-turn run with real tool outputs: the tools produced 83,783 characters, but keeping all of it in the transcript sent 1,769,810 characters over the run, 21 times as much. Turn 40 alone cost 16.5 times what turn 1 cost.
Storing each tool result outside the prompt and keeping only a 200-character head plus an id cut the last request from 86,183 characters to 12,000, and nothing was lost, because the agent could fetch the full result when it needed it. These are characters, not tokens; the ranking of the strategies is what carries over.
What we measured: 40 turns, real tool outputs: 83,783 characters produced, 1,769,810 sent when everything is kept (21 times); turn 40 cost 16.5 times turn 1; store-and-refer cut the last request from 86,183 to 12,000 characters.
What should an agent do when the conversation no longer fits the context window?
There are three moves and each loses something. Dropping the oldest turns is free and dangerous, because it silently deletes whatever fact lived early on. Summarising older turns keeps the gist but costs a model call and drops detail by design. Keeping turns by relevance to the current step is the most precise, but needs a relevance score, and a turn that scores low can still be the one that mattered.
Whichever you use, put hard rules outside its reach. A summariser reads one early line such as never delete a record without confirming as old chatter and drops it. Keep such rules in the system prompt or a pinned block the summariser never touches.
How is agent memory related to context engineering?
Two different problems share the word memory. Working memory is the running transcript the model reads every step: it is bounded by the window and costs tokens on every call. Long-term memory is facts worth keeping across separate runs, such as a user who always wants prices in euros, and it is a retrieval problem: store it outside, fetch it only when relevant.
Mixing them up goes wrong both ways. Stuffing every remembered fact into the transcript blows the budget in a few steps, and keeping the current task's scratch work in a vector store adds a retrieval failure to something that should simply be in the prompt.
Yes. Providers reuse the work of reading an unchanged start of a prompt, so a stable opening is cheap to resend. Rewriting the start, for example by dropping or summarising the oldest turns, invalidates that reuse and the remaining text is read again at full price.
So the order you build the context in matters for cost as well as quality: fixed instructions and tool definitions first, changing material last. The prompt caching guide covers the rules and the measured savings.
Three decisions shape most windows: how many tools to describe, how many retrieved documents to include, and where in the window the important part sits. Each was measured in the course on small open models.
How many tools should an agent see at once?
Fewer than you think, but mostly for speed and cost. With two small models and 60 requests, picking the right tool barely suffered: llama3.2:3b got all 60 right with up to 50 tools on offer, qwen2.5:3b got 59 or 60, and both dipped only at 100 tools, to 55 and 56. Tools that looked alike did no harm on their own.
The cost was certain. Every tool is written into every prompt, about 57 tokens each on llama3.2:3b, so the prompt grew from 428 tokens with 5 tools to 5,862 with 100, and the median reply on the laptop went from 2.7 seconds to 35.5. Give each step only the tools it can use.
What we measured: llama3.2:3b and qwen2.5:3b, 60 requests: right tool 60 of 60 up to 50 tools (llama3.2:3b), 55 and 56 at 100; prompt 428 to 5,862 tokens; median reply 2.7 s to 35.5 s.
How many retrieved documents should go into the context?
Fewer than the retrieval metric suggests. On 818 documents and 20 questions, raising k, the number of documents handed to the model, from 1 to 20 lifted retrieval from 9 of 20 questions to 18 of 20 with the right document somewhere in the list. But the number of questions where the model actually used the right document peaked at 10 of 20 at k of 5 and fell to 6 of 20 at k of 20.
The retrieval number can only go up as k grows, which is what makes it dangerous to tune on. Measure the end result, the right answer, as you change k, and pick k on your own system.
What we measured: qwen3:4b, 818 documents, 20 questions: right document retrieved 9 of 20 at k=1 and 18 of 20 at k=20; right document used 10 of 20 at k=5 and 6 of 20 at k=20.
Does the order of information in the context matter?
Yes, and more than people expect. With the same ten documents, the same question and qwen3:4b at temperature 0, moving the right document from the middle of the list to the end took the score from 4 of 14 to 14 of 14. A later control showed most of that gap came from how the documents were labelled, not only from where the right one sat, which is its own lesson: record both the order and the format in your evals.
The working rules are to put the current instruction near the end, where models read best, keep the most important material at the edges rather than the middle, and keep the same layout between eval runs so a score change means what you think.
What we measured: qwen3:4b, temperature 0, ten documents: 4 of 14 right with the answer document in the middle, 14 of 14 with it at the end; a control traced most of the gap to the document labels.
How do I know if my context engineering is working?
Measure it at the fill levels your agent really reaches. Run a fixed set of tasks with the context at several sizes and positions, watch where the right-answer rate starts to fall, and treat that point as your working budget rather than the advertised window. Re-run it when you change model versions, because the curve moves.
Alongside that, log the size of each request and the share taken by each part (instructions, tools, retrieved text, history). Repeated or near-duplicate tool output is usually the first thing to prune, because confusable material hurts recall more than plain length.
What goes wrong with Context engineering at scale?
The failure cases are what separate an answer from experience. The lessons below go through them, starting with "Agent Memory and Context: What the Model Sees, and What It Forgets".
The lessons that teach the next part
Agents have no memory between calls. What the model sees is the transcript you resend every step, and what it forgets is whatever you cut to fit. How to manage both.
A model's recall falls as its window fills, and worst from the middle. Measure the fill level where your agent starts to rot, and re-run it per model version.
Two small models, 60 requests, each offered 5 to 100 tools. Picking the right tool barely suffered until 100 tools, and look-alikes alone did no harm. The bigger problems were elsewhere: right choices written as broken JSON, valid calls that Ollama's chat API silently dropped, and replies that took 13 times longer with every tool on offer.
Raising k took recall@k from 45% to 90% on 818 documents, and took the number of questions the system actually got right from 10 of 20 down to 6. Same retrieval, same questions, no judge in the grading path. The component metric cannot go down, which is what makes it dangerous to optimise.
Every answer on this page comes from our AI Engineering course: 219 lessons on RAG, evals, agents, serving, security and MLOps. Many of them are built around a real experiment. You learn why the answer is right, which is what an interviewer checks with the second question. 10 lessons are free to read, with no card needed.
These questions are a start. The interview asks more.
Get all 150 questions in the AI Engineering (LLM applications) pack
Each question has why it is asked, a full answer, what the interviewer listens for, the follow-ups, the common mistakes and a diagram (180 diagrams in all). A PDF you keep, junior to staff level.