Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 8 steps

Prompt and Context Engineering
  1. 1
    Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  2. 2
    Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  3. 3
    Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  4. 4
    Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  5. 5
    Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  6. 6
    Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  7. 7
    Context Engineering: What Belongs in the Context Window, Turn by Turn
  8. 8
    Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. LLM Fundamentals

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.

Chaand Sheikh

·27 November 2026LLM Fundamentals

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:

PartTokens
System prompt71
Tool definitions251
Retrieved docs219
Chat history545
Tool results573
Question20
Total1,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:

PartBudget rule
System promptShort and stable: rules, not knowledge
Tool definitionsOnly the tools this agent needs
Retrieved docsThe top few articles, not every match
HistoryA summary plus the last few turns
Tool resultsThe 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:

Order the window: stable on top, reference in the middle, fresh at the bottom Top: stable system prompt, tool definitions same every turn, so it can be cached Middle: reference help articles, history summary looked up when needed don't bury rules here Bottom: fresh latest tool result, the new question what this turn is about
Stable parts first, reference material in the middle, and the task last. Important rules sit at the top so they never sink into the middle.

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
Tokens per part of the window, before and after compaction 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 Whole window: 1,679 tokens before, 1,089 after
The same turn before and after the three moves. Only the three parts that change every turn shrink: docs, history and old tool results. The rules and the question are untouched.

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:

SymptomContext causeFix
Forgets a ruleThe rule is buried in the middleRules at the top
Uses old dataA stale tool result is still in the windowClear old results
Picks the wrong toolToo many similar toolsSend only the tools it needs
Makes things upThe right article was never retrievedFix 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 itLeave it out
Rules the agent must followTools this agent never calls
Facts this question depends onArticles that only half match
The latest tool resultRaw results already used
A summary of what was decidedSmall 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

StepWhat you doTurn twelve
MeasureCount tokens per part1,679 tokens, question only 20
BudgetOne rule per part, room left for the answerTop few docs, summary plus last turns
OrderStable on top, reference in the middle, task lastRules and tools first, question last
CompactStub old results, summarise history, fewer docs1,679 down to 1,089
CheckTests for the facts that must survive3 tests pass

Try it yourself

  1. Run python budget.py and read the before and after table.
  2. Change a dial: set keep_turns=3 in compact_history, or k=3 in retrieve_fewer. Predict which row moves and by roughly how much, then run it and compare the totals.
  3. 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Prompt and Context Engineering · step 7 of 8

Previous
Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
Next post
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

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.

On this page

  • From a prompt to a context
  • Packing a carry-on
  • Measure what is in the window
  • Give every part a budget
  • Order the window for attention
  • Compaction: same meaning, fewer tokens
  • 1. Clear old tool results
  • 2. Summarise old turns
  • 3. Retrieve fewer articles
  • Before and after
  • Prove the important facts survived
  • Most agent failures are context failures
  • What belongs in the window?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.