Context Engineering
How to decide what information the model receives on each call, including how to select, compress, order and isolate it and how to keep stale material out.
On this page
Context engineering is the work of deciding everything a model reads on a single call: which documents, history and instructions go in, in what form and order, and what is left out. Prompting is only the wording of the request, while context engineering also covers the material around it. In an application, code does this work on every request, so the quality of that code often matters more than the wording of any one prompt.
The model knows only what is in its context, and the context window is limited. If you send too little, the model guesses. If you send too much, it has to find the useful part among irrelevant material, and when the material contradicts itself, it may follow the wrong version. The goal on every call is to send the smallest set of information that lets the model do the task well.
What good context looks like
Good context is relevant to the task, current, consistent with itself, and clearly labelled so the model can tell an instruction from a document and one source from another. You build it with four techniques, described below: selecting, compressing, ordering and labelling, and isolating. You also decide what to keep out, which is as important as what to put in.
A worked example: choosing context for a returns question
A shop's assistant is asked: "Can I return headphones I've already opened?" The application has six candidate pieces of text. Each has a size in tokens and a relevance score. The score could come from retrieval, from fixed rules, or from a quick check by another model. The budget for this call is 250 tokens.
The method has two parts. First, drop anything stale. Then go through the rest from most to least relevant, skipping pieces with a score below 0.3 and pieces that no longer fit in the budget.
drop stale piecessort the rest by score, highest firstfor each piece: if score < 0.3: skip if used + tokens > budget: skip add it, used += tokens- piece0policy1product2order3FAQ4old policy5shippingscore00.910.620.830.440.750.2tokens012018024033004120560
- budget
- 250
- used
- 0
1The 2019 returns policy was replaced. Keeping it would give the model two rules that disagree, so it is dropped first, whatever its score.
- piece0policy1order2product3FAQ4shippingscore00.910.820.630.440.2tokens01201402803300460
- budget
- 250
- used
- 0
2The other five pieces are sorted by score, so the most useful ones get first claim on the budget.
- piece0policyi1order2product3FAQ4shippingscore00.910.820.630.440.2tokens01201402803300460
- budget
- 250
- used
- 120
3The current returns policy has score 0.9, and 0 + 120 = 120 fits in the budget, so it is added.
- piece0policy1orderi2product3FAQ4shippingscore00.910.820.630.440.2tokens01201402803300460
- budget
- 250
- used
- 160
4The order record says when the customer bought the item and which model it was. 120 + 40 = 160, so it is added.
- piece0policy1order2producti3FAQ4shippingscore00.910.820.630.440.2tokens01201402803300460
- budget
- 250
- used
- 240
5The product page says whether the headphones are in-ear, which matters for hygiene rules. 160 + 80 = 240, so it is added.
- piece0policy1order2product3FAQi4shippingscore00.910.820.630.440.2tokens01201402803300460
- budget
- 250
- used
- 240
6The whole FAQ would bring the total to 240 + 300 = 540, far over the budget of 250, so it is skipped. If one FAQ answer mattered, that answer alone could be sent instead.
- piece0policy1order2product3FAQ4shippingiscore00.910.820.630.440.2tokens01201402803300460
- budget
- 250
- used
- 240
7The shipping rates have score 0.2, which is below 0.3, so they are skipped.
- piece0policy1order2product3FAQ4shippingscore00.910.820.630.440.2tokens01201402803300460
- chosen
- 3
- used
- 240
- send everything
- 720
8Three pieces are chosen, using 240 tokens and containing no contradictions. Sending all six would have cost 720 tokens and included two policies that disagree.
When a piece does not fit, the loop skips it and carries on, because the pieces are independent of each other. This differs from trimming chat history, where you usually drop the oldest messages to keep the conversation in order.
function selectContext(pieces, budget, minScore = 0.3) {
const candidates = pieces
.filter((p) => !p.stale)
.sort((a, b) => b.score - a.score);
const chosen = [];
let used = 0;
for (const p of candidates) {
if (p.score < minScore) continue; // not relevant enough
if (used + p.tokens > budget) continue; // does not fit
chosen.push(p.name);
used += p.tokens;
}
return { chosen, used };
}
selectContext([
{ name: "policy", score: 0.9, tokens: 120 },
{ name: "product", score: 0.6, tokens: 80 },
{ name: "order", score: 0.8, tokens: 40 },
{ name: "FAQ", score: 0.4, tokens: 300 },
{ name: "old policy", score: 0.7, tokens: 120, stale: true },
{ name: "shipping", score: 0.2, tokens: 60 },
], 250); // { chosen: ["policy", "order", "product"], used: 240 }def select_context(pieces, budget, min_score=0.3):
candidates = sorted(
(p for p in pieces if not p.get("stale")),
key=lambda p: p["score"],
reverse=True,
)
chosen, used = [], 0
for p in candidates:
if p["score"] < min_score: # not relevant enough
continue
if used + p["tokens"] > budget: # does not fit
continue
chosen.append(p["name"])
used += p["tokens"]
return chosen, used
select_context([
{"name": "policy", "score": 0.9, "tokens": 120},
{"name": "product", "score": 0.6, "tokens": 80},
{"name": "order", "score": 0.8, "tokens": 40},
{"name": "FAQ", "score": 0.4, "tokens": 300},
{"name": "old policy", "score": 0.7, "tokens": 120, "stale": True},
{"name": "shipping", "score": 0.2, "tokens": 60},
], 250) # (['policy', 'order', 'product'], 240)The sorting cost is negligible next to the model call. The difficult part is producing scores that reflect real relevance and marking stale material honestly.
The two prompts below show what the model receives with and without this selection.
The first reply blended the old and the current policy and never mentioned the in-ear rule. The second reply had every fact it needed, each one labelled, and nothing in the context contradicted anything else.
Techniques for building context
Selecting
Selecting means including only the material this task needs. For a returns question, that excludes the shipping rates and the marketing copy, even though they belong to the same shop. The usual tools are retrieval by similarity to the question, fixed rules such as "always include the customer's order", and a cheap first pass in which a small model or a keyword filter discards obviously unrelated items. Selection fails when the relevance signal is poor: a retriever that returns the wrong passages gives the model confident, wrong material, and the model has no way to know the passages were a bad match.
Compressing
Compressing means shrinking what you have chosen without losing the facts the task depends on. You can send the relevant section of a document instead of the whole document, replace a long conversation with a summary of the decisions made in it, and strip repeated headers, footers and legal boilerplate. Summaries lose detail, so use them for material the model only needs the gist of, and keep exact text for anything it must quote or calculate from, such as a contract clause or a table of figures. A summary written by a model can also introduce errors, so for important material check it before you rely on it.
Ordering and labelling
Ordering and labelling mean arranging the context so the model can tell what each part is. Put the instructions in a place where they cannot be mistaken for part of a document, wrap each piece of material in a labelled block that says what it is and where it came from, and, after a long block of material, repeat the question you want answered. Labels also let the model say which source an answer came from, which makes the answer easier to check. See Structured Output for ways to ask for that in the reply.
Order also affects cost and reliability. Models often use information in the middle of a very long context less reliably than information at the start or the end, so put the question and the most important material near the edges. Many providers can also reuse the processing of a prompt prefix that is identical between calls, so put the parts that never change, such as the instructions and tool definitions, first, and the parts that change on every request, such as the user's question and the retrieved passages, last. Putting a timestamp or other changing value at the top of the prompt makes the prefix different on every call and defeats that reuse.
Isolating
Isolating means splitting a large job into several focused calls instead of one call with everything in it. To compare ten long reports, summarize each report in its own call, then send the ten summaries to a final call that does the comparison. Each call sees only what it needs, and the final call works on short inputs. The cost is more calls and more total latency, and the summaries may drop a detail that the comparison turns out to need, so design the summary step around the question you will ask at the end.
Managing conversation history and tool output
In a long conversation or an agent loop, the history is itself context that grows on every turn. The simplest policy is to drop the oldest messages once a limit is reached, which is cheap but forgets early decisions. A better policy is to keep the last few turns word for word and replace everything older with a summary of the facts and decisions that still matter. Tool results need the same care: a tool that returns a whole file or a thousand database rows fills the context with text the model reads once and never needs again, so return only the relevant part, and clear old tool results from the history once their conclusions have been recorded.
What to keep out
Leave out outdated versions of documents, sources that disagree with each other, loosely related material, secrets the task does not need, and untrusted text that might contain instructions, such as web pages or customer emails. The last one matters because the model may follow instructions that appear inside material you only meant it to read, as Prompt Injection explains.
Pitfalls and nuances
How this changes what you do in practice
Before you tune the wording of a prompt, look at the full text the model received on a failing example. Most wrong answers trace back to something missing, something stale or two sources that disagree, and rewording does not fix any of those. Log the final assembled context for each request while you are developing, so you can read it.
When you build a context, work through the techniques in order. Select the pieces the task needs, compress the ones that are long, label each piece and place the instruction and the question where they will not be missed, and split the job into several calls if one context would be too large or too mixed. Then test with and without each optional piece, and keep only the ones that improve the answers.
When you use a coding assistant, apply the same thinking by hand: give it the error message, the failing test and the relevant files before anything else, instead of pointing it at the whole project.
A coding assistant must fix a failing test for a shopping-cart total. You could give it the whole repository (about 2,000 files), the failing test file, the function being tested, the test's error output, the team's style guide, last week's chat about a different feature, and the README. Decide what to include and what to leave out, and give a reason for each choice.
Show a sample answer
Include the following.
- The error output, because it shows what actually went wrong and is often the most useful piece.
- The failing test, because it defines what correct behaviour is.
- The function under test, and anything it calls that is involved in the failure, such as a discount helper.
A few relevant lines of the style guide are optional, and worth including only if the fix will be reviewed against it.
Leave out everything else. The whole repository would bury the few files that matter. Last week's chat is about a different feature and may refer to code that has since changed. The README is rarely needed for a local fix.
Coding tools that search the repository make this selection themselves, so naming the error and the files first still helps them start from the right place.
A support bot sometimes quotes an old refund period. Both the old and the new policy are in its context. What is the best fix?
You need to compare 10 long reports. Which approach uses the isolating technique?
In the worked example, why was the FAQ skipped even though its score was above the 0.3 threshold?
What to practise next
The worked example assumed that relevance scores already existed. RAG Basics shows how to compute them by searching your documents with embeddings, and Chunking and Retrieval covers how to cut documents into pieces worth retrieving.