Learning path: Prompt and Context Engineering · Step 7 of 8
Context Engineering: What Belongs in the Context Window, Turn by Turn
A support agent on turn twelve sends 1,679 tokens to the model, and the question is only 20 of them. Measure each part of the window, give it a budget, put it in the right order, and compact it to 1,089 tokens without losing the facts the next step needs.
What you will learn
- Measure every part of an agent's context window in tokens
- Give each part a budget and order the window for attention
- Shrink a window with three compaction moves and check that the key facts survive
- Trace common agent failures back to what was in the window
Before you start
- Basic Python
- LLM Tokens, Context Windows and Cost
A support agent is twelve turns into a chat with a customer about returning a pair of headphones. The customer types one short line: replacement please, and send the label to my other email. That line is 20 tokens. The model reads 1,679.
The other 1,659 tokens are everything the agent sent along with the question. A good answer on turn twelve comes from all of it, so the prompt you wrote at the start is only one small piece. Choosing all of it, again on every turn, is context engineering. In this article you'll measure that turn part by part, give each part a budget, put the parts in a sensible order and trim the window by more than a third, with tests to prove nothing important was lost.
From a prompt to a context
When people say prompt engineering, they usually mean one well-written instruction. But look at what the model actually receives on turn twelve:
- the system prompt (the agent's rules)
- the tool definitions (what the agent is allowed to call)
- the retrieved help articles
- the chat history
- the tool results from earlier calls
- and, last, the new question
Your carefully written prompt is the first item on that list. The other five change on every turn, and somebody has to decide what goes in.
Packing a carry-on
Think of packing a carry-on bag for a trip. The bag has a fixed size, and it doesn't grow because the trip is long. So you pack what you need for this trip, not everything you own. You roll your clothes instead of folding them: same clothes, less space. And on a long trip you repack each day. Yesterday's things come out and today's go in.
The bag is the context window. Packing it on purpose, every turn, is context engineering. What you leave out matters as much as what you pack. (If the window itself is new to you, start with LLM Tokens, Context Windows and Cost.)
Measure what is in the window
You can't budget what you haven't measured. The project for this lesson stores turn twelve in turn12.json: the system prompt, three tool definitions, five help articles, eleven earlier turns (22 messages), two order lookups and the new question. No API key is needed and no model is called. tiktoken just counts the tokens.
import json
from pathlib import Path
import tiktoken
ENC = tiktoken.get_encoding("cl100k_base")
TURN = json.loads((Path(__file__).parent / "turn12.json").read_text(encoding="utf-8"))
def tokens(obj) -> int:
text = obj if isinstance(obj, str) else json.dumps(obj)
return len(ENC.encode(text))
def measure(ctx: dict) -> dict[str, int]:
"""Tokens per part of the window, in the order the parts are sent."""
return {
"system prompt": tokens(ctx["system"]),
"tool definitions": tokens(ctx["tools"]),
"retrieved docs": tokens(ctx["docs"]),
"chat history": tokens(ctx["history"]),
"tool results": tokens(ctx["tool_results"]),
"question": tokens(ctx["question"]),
}
tokens turns any part into text (JSON for lists and dicts) and counts it. measure does that for each of the six parts. Here is turn twelve as it stands:
| Part | Tokens |
|---|---|
| System prompt | 71 |
| Tool definitions | 251 |
| Retrieved docs | 219 |
| Chat history | 545 |
| Tool results | 573 |
| Question | 20 |
| Total | 1,679 |
The biggest part is the tool results, 573 tokens, because two full order lookups are still sitting there. The chat history is close behind at 545. The question itself is a tiny slice. These counts come from tiktoken's cl100k_base encoding on our own text. Other models count a little differently, so treat them as sizes to compare.
Give every part a budget
Next, give each part a simple rule. Nothing fancy, just a sentence you can check:
| Part | Budget rule |
|---|---|
| System prompt | Short and stable: rules, not knowledge |
| Tool definitions | Only the tools this agent needs |
| Retrieved docs | The top few articles, not every match |
| History | A summary plus the last few turns |
| Tool results | The latest one whole, older ones as a one-line stub |
And keep room free for the answer, because the answer is written into the same window. For retrieved docs, picking the best blocks until a token budget is full is shown step by step in RAG Prompt Assembly and Citations.
Order the window for attention
Models tend to use the start and the end of a long context better than the middle. So place things on purpose:
The system prompt and tool definitions are the same on every turn, so they go first (and a fixed opening is also what lets a provider cache it). The help articles and the history summary are reference material, so they sit in the middle. The latest tool result and the new question are what this turn is about, so they go last. Important rules at the top, the task at the bottom, and nothing important in the middle.
Compaction: same meaning, fewer tokens
Compaction is rolling the clothes. You keep the meaning and use less space. The project applies three moves to the same turn.
1. Clear old tool results
def clear_old_tool_results(ctx: dict, keep_last: int = 1) -> dict:
"""Old tool results were already used: keep a one-line stub so the agent knows the call happened."""
old = ctx["tool_results"][:-keep_last]
stubs = ["[cleared: lookup_order %s]" % r["order_id"] for r in old]
return {**ctx, "tool_results": stubs + ctx["tool_results"][-keep_last:]}
The first lookup was for order 4417, a gift card the customer asked about early in the chat. It has already been used, so it becomes [cleared: lookup_order 4417]. The agent still knows the call happened. The lookup for order 4390, the headphones, is the latest one and the one this turn depends on, so it stays whole. That's why this move only takes the tool results from 573 to 480: the big result is the one we keep.
2. Summarise old turns
def compact_history(ctx: dict, keep_turns: int = 2) -> dict:
"""Replace old turns with a short summary note; keep the last few turns word for word."""
keep = ctx["history"][-2 * keep_turns:]
summary = {"role": "user", "content": (
"Summary of earlier turns: order 4417 shipped (Parcelway PW-88213); address changes go to the carrier. "
"Headphones from order 4390 crackle on the left; inside the return window, which closes 28 March; "
"no restocking fee; box not required, include cables.")}
return {**ctx, "history": [summary] + keep}
With keep_turns=2, the last two turns (four messages) stay word for word, and everything before them is replaced by one short note. In this project the note is written by hand, so you can see exactly what a good summary keeps: the order numbers, the fault, the date the return window closes, the fee and the box rule. The small talk about gift cards and paying with two cards is gone. History goes from 545 tokens to 166.
3. Retrieve fewer articles
def retrieve_fewer(ctx: dict, k: int = 2) -> dict:
"""Send only the best k help articles (here they are already ranked)."""
return {**ctx, "docs": ctx["docs"][:k]}
def trimmed(ctx: dict) -> dict:
return retrieve_fewer(compact_history(clear_old_tool_results(ctx)))
The five articles are already ranked, and the top two are the ones about faulty returns and how to start one. The other three (refund timing, replacements and gift cards) stay out of this turn. Docs go from 219 tokens to 101. trimmed applies all three moves in a row.
Before and after
if __name__ == "__main__":
before, after = measure(TURN), measure(trimmed(TURN))
print(f"{'part':<18}{'before':>8}{'after':>8}")
for part in before:
print(f"{part:<18}{before[part]:>8}{after[part]:>8}")
print(f"{'total':<18}{sum(before.values()):>8}{sum(after.values()):>8}")
part before after
system prompt 71 71
tool definitions 251 251
retrieved docs 219 101
chat history 545 166
tool results 573 480
question 20 20
total 1679 1089
The whole window goes from 1,679 to 1,089 tokens, 590 fewer, about 35% smaller. The rules and the question didn't change at all.
Prove the important facts survived
Smaller is easy. Smaller and still correct is the point. The project's tests check exactly that:
from budget import TURN, clear_old_tool_results, measure, trimmed
def test_trim_makes_the_window_smaller():
assert sum(measure(trimmed(TURN)).values()) < sum(measure(TURN).values())
def test_trim_keeps_what_the_next_step_needs():
t = trimmed(TURN)
assert t["system"] == TURN["system"] # instructions stay
assert t["question"] == TURN["question"] # the new question stays
assert t["tool_results"][-1]["order_id"] == "4390" # the latest tool result stays whole
assert "28 March" in t["history"][0]["content"] # the summary keeps the key fact
def test_cleared_result_leaves_a_stub():
assert clear_old_tool_results(TURN)["tool_results"][0] == "[cleared: lookup_order 4417]"
python -m pytest -q
3 passed
Write a test like the second one for every fact your agent can't afford to lose. Then you can trim harder without guessing. To see the same moves keep an agent working across twenty turns, read Context Engineering for a Long-Running Agent.
Most agent failures are context failures
When an agent goes wrong, the cause is very often the context, not the model:
| Symptom | Context cause | Fix |
|---|---|---|
| Forgets a rule | The rule is buried in the middle | Rules at the top |
| Uses old data | A stale tool result is still in the window | Clear old results |
| Picks the wrong tool | Too many similar tools | Send only the tools it needs |
| Makes things up | The right article was never retrieved | Fix retrieval |
So before you blame the model, print the window and read what it actually saw.
What belongs in the window?
Ask one question of every piece: does this turn need it?
| Pack it | Leave it out |
|---|---|
| Rules the agent must follow | Tools this agent never calls |
| Facts this question depends on | Articles that only half match |
| The latest tool result | Raw results already used |
| A summary of what was decided | Small talk from ten turns ago |
The best context is the smallest set of facts that still gets the job done.
Common mistakes
- Tuning the prompt while the window is full of junk. On turn twelve, your prompt is 71 of 1,679 tokens. Look at the other 1,608 first.
- Clearing the latest tool result. Old results become stubs; the one this turn depends on stays whole.
- A summary that drops the key fact. Once the old turns are gone, the note is where the agent looks for what was said. If a key fact like the return window date isn't in it, you're relying on luck. Test for it.
- Putting rules in the middle between long articles, where they're easiest to miss.
- Filling the window to the limit. The answer needs room too.
Quick recap
| Step | What you do | Turn twelve |
|---|---|---|
| Measure | Count tokens per part | 1,679 tokens, question only 20 |
| Budget | One rule per part, room left for the answer | Top few docs, summary plus last turns |
| Order | Stable on top, reference in the middle, task last | Rules and tools first, question last |
| Compact | Stub old results, summarise history, fewer docs | 1,679 down to 1,089 |
| Check | Tests for the facts that must survive | 3 tests pass |
Try it yourself
- Run
python budget.pyand read the before and after table. - Change a dial: set
keep_turns=3incompact_history, ork=3inretrieve_fewer. Predict which row moves and by roughly how much, then run it and compare the totals. - Print one turn of your own agent's window and mark every piece that turn did not need.
The project files and sample prompts for this lesson are in the StudyEasy AI Community, free to join.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.