Context engineering: deciding what the model sees
Why the context window is the main lever on quality, cost and latency; the parts of a context (rules, task, evidence, history, tools, state); budgeting tokens; packing by value per token; summarising and compacting history; ordering for attention; caching stable prefixes; and a runnable packer.
By Sandip Maity, Applied AI Engineer
The model knows nothing except its weights and the tokens you send. Prompt wording matters, but in real applications the bigger decisions are about which material goes into the window, how much of it, in what form and in what order. That is context engineering, and it is where most quality, cost and latency problems in RAG and agent systems are won or lost.
#What goes into a context
| Part | Example | Changes |
|---|---|---|
| Rules | System prompt, persona, output format, safety rules | Rarely |
| Tools | Tool names, descriptions and schemas | Rarely |
| Task | The user's current request | Every request |
| Evidence | Retrieved chunks, files, search results | Every request |
| History | Earlier turns of the conversation | Grows |
| Working state | Tool results, plans, scratch notes in an agent run | Grows fast |
Every token costs prefill compute (time to first token) and, on a hosted API, money. On a local server it also costs KV cache memory for every concurrent user. And quality is not monotonic: models are distracted by irrelevant passages, and they use the start and end of a long context more reliably than the middle.
#Budget first
Write the budget down like any other resource:
Context window 32,768 tokens
Reserved for output 1,500 (the answer, plus reasoning if the model thinks)
Rules + tool schemas 1,200 (stable prefix: cache it)
Task 300
Evidence 6,000 (about 12 chunks of 500 tokens)
History 2,000 (summarise beyond this)
Agent working state 4,000 (compact tool results)
Headroom 17,768 (unused on purpose)A budget well under the window is normal. The window is a limit, not a target.
Pro content
Keep reading with Inference Academy Pro
Unlock the rest of this lesson, including 1 animated diagram, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.
Still to come in this lesson
- Packing: value per token
- Order for attention and for caching
- Keeping history and agent state small
- Evidence quality beats evidence quantity
- Measuring context changes
- Common mistakes
- Exercises
You will be able to answer
- A model has a 128K-token window. Why not always fill it?
- Which parts of the context should be pinned and never dropped?
- Why put stable content (system prompt, tool schemas) at the start of the prompt?
- An agent's tool results are 30K tokens of raw JSON per step. What helps most?
- Where should the most important evidence usually go?