Try it first
Before you read, pick what you think is right. It's fine to be wrong.
How do prompt engineering and context engineering differ?
Why does the position where information is placed in the context matter?
Prompt engineering is only a part. Context is everything the model reads at once: the system instructions, retrieved documents, tool descriptions, past conversation, examples, and the current question. Context engineering is deciding what to put in, what to leave out, and in what order to place it.
Type: Build Language: Python (standard library only) Prerequisites: Stage 1 Prompt Engineering, Stage 3 Embeddings Time: About 90 minutes Next stage: Stage 5 RAG — Retrieve and Answer Run: Right in the browser (no installation). It does not call a model. It actually assembles the text that would be sent to a model, and counts whether the information needed is in that text.
What you will learn
- Count how many tokens each part of the context window costs (system instructions, tools, documents, conversation, question, room for the answer).
- Compare rough estimates such as "word count × 1.3" with real tokenizer numbers to see how wrong they are for Korean.
- Build a budget manager in which the question and the rules are never cut, and everything else is filled in order of importance.
- Build conversation memory that shrinks old conversation while keeping must-have facts such as an order number.
- Insert only the tools and documents each question needs, and compare the result with "put everything in" using numbers.
The problem
The example in this lesson is a support agent for an imaginary online shop, "Moashop". It has one paragraph of rules, 8 help articles, 10 tools, and 12 turns of past conversation. Counted with OpenAI's o200k tokenizer, that is 1,495 tokens. Nearly half of it, 730 tokens, is tool descriptions. That is the case even though the customer never once said a tool name.
Today's model windows are large. Anthropic's latest Claude models have 1 million tokens, OpenAI GPT-5 has 400,000 tokens, and Google Gemini 2.5 and 3 have 1,048,576 input tokens. It is easy to think that at this scale 1,495 tokens is nothing to worry about. But there are two problems.
First, the speed at which it grows. The conversation gets longer every turn, tools multiply every time you add a feature, and a coding agent puts in thousands of tokens every time it opens a file. When the window fills, something has to be cut, and if you cut without thinking, what is actually needed gets cut.
Second, being put in does not mean being used. Liu et al. (2023) placed the one document containing the answer at various positions among 20 documents and measured the correct-answer rate. GPT-3.5-Turbo scored 75.8% when the answer was in the first position, 53.8% in the exact middle (10th), and 63.2% in the last. In the middle it was even lower than when no document was given at all (56.1%). The more unneeded text there is, the more the needed text gets buried.
Context engineering is making the necessary information always get in, and the unnecessary information get in less, within a fixed window.
Concepts
The window is not a roomy warehouse but a narrow desk
The context window is all the tokens the model handles in a single request. It is not only the input. The answer the model will write also lives in the same window. For a model that thinks (a reasoning model), the tokens spent on thinking are counted too.
| Model (official docs, November 2026) | Window | Maximum usable for the answer |
|---|---|---|
| Anthropic Claude latest models | 1 million tokens | 128,000 tokens (including thinking tokens) |
| OpenAI GPT-5 | 400,000 tokens | 128,000 tokens |
| Google Gemini 4 | Input, thinking and answer share 1,048,576 tokens | 65,536 tokens by default |
| Google Gemini 3, 2.5 | 1,048,576 input tokens | 65,536 tokens |
| Meta Llama 4 Scout | States 10 million tokens | — |
XenLook note Keep two things in mind when you look at these numbers. One: whe…
Keep two things in mind when you look at these numbers. One: whether the "window size" covers input and answer together or input only is written differently by each company. For Gemini 4 it is the combined size, while Gemini 3 and 2.5 list input and answer separately. Two: the size a company states and the size the model handles well are different. Llama 4 Scout advertises 10 million tokens, but its actual training was done at 256K length, and it says it verified longer lengths with needle-in-a-haystack tests and code. GPT-5 is now handing its place to a newer model, so check the model list of the day before you use it.
The window is closer to a narrow desk than a roomy warehouse. You can put everything on it, but the more you put on it, the harder it is to find the paper you need, and cost and response time grow too. The parts you put on the desk compete with each other for space.
- Rules (system prompt)
- Memory (must-keep facts)
- Tool descriptions
- Retrieved documents
- Past conversation (summary + recent turns)
- The current question
- Room for the answer (including thinking tokens)
Information placed in the middle
"Lost in the Middle" by Liu et al. (2023) is the most cited experiment in this field. To recap:
- Among several documents, they moved the position of the one document containing the answer and measured the correct-answer rate (10, 20 and 30 documents).
- For many models, the result was a U shape: the correct-answer rate was high when the answer was at the very beginning or very end, and low when it was in the middle.
- It differs from model to model. In the same experiment (20 documents), Claude-1.3 was almost flat: 59.9% in the first position, 56.8% in the middle, 60.1% at the end.
XenLook note What this experiment measured is the correct-answer rate, not th…
What this experiment measured is the correct-answer rate, not the "attention scores" inside the model. And it was measured on 2023 models. So rather than memorizing "the middle is a place where things get thrown away", it is more accurate to remember "the result can change with position, so measure it on my own model". Chroma's "Context Rot" (2025) confirmed again, with 18 models, that performance drops as the input gets longer.
The practical rules that come out of this are:
- Put the rules (system prompt) at the very beginning.
- Put the current question at the very end.
- For retrieved documents, put the most relevant ones at both ends and the less relevant ones in the middle. The effect differs from model to model, so confirm it by measuring.
- Above all, inserting less of what is unneeded is more reliable than arranging positions.
The parts that make up the window
Rules (system prompt): They decide who the model answers as, based on what, and which lines it keeps. They are resent with every request, so write them short and clear.
Tool descriptions: Each tool includes a name, a description and an input format (JSON schema). The 10 tools in this lesson take 59–95 tokens each in o200k, 730 tokens in total. With dozens of tools it becomes tens of thousands of tokens. Anthropic reported that about 50 tools from several MCP servers took about 72,000 tokens, and that a "tool search" approach, which finds and loads tools when needed, brought that down to about 8,700 tokens (an 85% reduction). In the same post, the accuracy of choosing tools also rose from 49% to 74% for Claude Opus 4, and from 79.5% to 88.1% for Opus 4.5.
Retrieved documents: Guides, files and search results fetched by retrieval. A wrong document does not just take up space; it can pull the model toward a wrong answer.
Past conversation: It grows every turn. Most of it has nothing to do with the current question, but a fact that appeared only once at the start, such as an order number, may be needed later.
Examples (few-shot): The input and output examples you saw in Stage 1. A few examples are often better than a long explanation, but they also use space.
Room for the answer: The tokens the model will write its answer in. For a model that thinks, the thinking tokens come out of here too. If you fill the window to the brim with input, the answer gets cut off. Do not memorize how much to leave as "so many tokens"; decide it from the length of your answers and your thinking settings.
Ways to shrink
Summarizing the conversation: Replace old turns with a summary instead of leaving them as they are. Keep the last few turns as they are. Claude Code summarizes and continues when the conversation gets long (compaction), and Anthropic explains that it keeps what was decided, unresolved problems, and a few recently opened files.
Filtering by relevance: Score each retrieved document for relevance to the question and drop the low ones. The threshold differs by model and data, so decide it with evaluation questions, as in Stage 3.
Choosing tools: Insert only the tools that fit the question. The tool search you saw earlier is the way to have the model side do this for you.
Fetching when needed: Instead of putting everything in beforehand, give only file paths or a document list and let the model open what it needs with tools. This is how a coding agent finds and opens files instead of putting in all the code.
Clearing tool results: Remove tool results that have already been fully used (for example, the contents of a long file read long ago) from the window.
Memory
Short-term memory: The current conversation. It sits directly in the window and is managed by summarizing and truncating.
Long-term memory: Facts and preferences that remain after the conversation ends. "This user likes large text", "This project uses PostgreSQL". Store them separately and insert them when a conversation starts. Claude Code reads the project's CLAUDE.md and automatic memory at the start of every session.
XenLook note CLAUDE.md is context the model reads, not a setting that is gu…
CLAUDE.md is context the model reads, not a setting that is guaranteed to be obeyed. Even if you write "do not modify this folder", the model can break it. What must be blocked is blocked with a mechanism such as a hook that checks before a tool runs. Put rules in the context and prohibitions in the mechanism.
Episodic memory: Find and insert past conversations that resemble the present one. "Last week we solved a similar payment error like this." It is found with the embedding search from Stage 3.
- The current question
- Short-term memory<br/>Current conversation (summary + recent turns)
- Long-term memory<br/>Stored facts and preferences
- Episodic memory<br/>Similar past conversations (embedding search)
- Context window
Assembling anew for every question
Sending the same rules, the same tools and the same conversation whole every time is waste. Assemble like this for each question.
- Secure space first for what must never be cut (the rules, the question).
- Insert the must-keep facts (memory such as the order number).
- Insert only the tools that fit the question.
- Insert only the documents that fit the question.
- In the remaining space, insert the recent conversation, then the summary of the old conversation.
- Lay it out in reading order. The rules at the very beginning, the question at the very end.
- Measure whether the needed information really got in.
Insertion order (priority) and placement order (reading order) are different. The question claims its space first, but when placed, it goes at the very end.
Build
XenLook note The Python names and output text are in English because real wor…
The Python names and output text are in English because real working code usually is too. It uses only the standard library (json, math, re), so it runs as is, with no installation, in "Run the code" at the bottom of this page. It does not call a model. Instead it actually assembles the text that would be sent to a model, and counts whether the information needed for each question is in that text. This measures "was it included", not whether the model answers correctly.
1) Data
There are the rules, 8 help articles, 10 tools, 12 turns of past conversation, and 8 questions that come after the conversation. Each question has the phrases its answer absolutely needs (needs) and the tool that should be called (tool) attached. The order number appears only in the first turn of the conversation. The last question, "돈을 돌려받고 싶어요" ("I want my money back"), was deliberately made so that it shares no words with the refund help article or the refund tool.
import json
import math
import re
SYSTEM_PROMPT = (
"너는 모아샵 고객 상담 에이전트다. 아래 안내문과 도구만 근거로 답한다. "
"안내문에 없는 내용은 모른다고 말하고 상담원 연결을 권한다. "
"주문번호와 금액은 대화에 나온 그대로 쓴다."
)
KNOWLEDGE = [
{"id": "refund", "title": "환불",
"text": "상품을 받은 날부터 7일 안에 환불을 요청할 수 있습니다. 포장을 뜯지 않은 상품은 전액 환불됩니다. "
"포장을 뜯은 상품은 상품에 문제가 있을 때만 환불됩니다. 환불 금액은 결제한 수단으로 3영업일 안에 돌아갑니다."},
{"id": "shipping", "title": "배송",
"text": "오후 2시 전에 결제한 주문은 당일 출고합니다. 출고 다음 날 도착하는 것이 보통입니다. "
"제주와 도서 지역은 1~2일 더 걸립니다. 배송 조회는 주문 내역 화면에서 할 수 있습니다."},
{"id": "address", "title": "배송지 변경",
"text": "배송지는 출고 전까지만 바꿀 수 있습니다. 출고 뒤에는 택배사에 직접 요청해야 합니다."},
{"id": "coupon", "title": "쿠폰",
"text": "쿠폰은 결제 금액이 3만 원 이상일 때만 쓸 수 있습니다. 쿠폰 두 장을 한 주문에 함께 쓸 수는 없습니다. "
"기한이 지난 쿠폰은 되살릴 수 없습니다."},
{"id": "exchange", "title": "교환",
"text": "교환은 받은 날부터 14일 안에 신청합니다. 크기나 색 교환의 왕복 배송비는 고객이 냅니다."},
{"id": "gift", "title": "선물 포장",
"text": "선물 포장은 주문할 때 고르며, 출고 전이면 고객센터에서 더할 수 있습니다. "
"선물 포장한 주문에는 가격표와 영수증을 넣지 않습니다."},
{"id": "receipt", "title": "영수증",
"text": "현금영수증과 세금계산서는 결제 완료 화면에서 발급합니다. 이미 발급한 영수증은 주문을 취소하면 함께 취소됩니다."},
{"id": "membership", "title": "회원 등급",
"text": "골드 등급은 지난 6개월 구매 금액이 50만 원 이상인 회원입니다. 골드 등급은 무료 배송 쿠폰을 매달 두 장 받습니다."},
]
TOOLS = [
{"name": "order_lookup", "description": "주문번호로 주문 상태, 결제 금액, 출고 여부를 조회한다.",
"params": {"order_id": "주문번호"}, "keywords": [], "always": True},
{"name": "track_shipping", "description": "송장 번호와 지금 배송 위치를 조회한다.",
"params": {"order_id": "주문번호"}, "keywords": ["배송", "택배", "도착"]},
{"name": "change_address", "description": "출고 전 주문의 배송지를 바꾼다.",
"params": {"order_id": "주문번호", "address": "새 배송지"}, "keywords": ["배송지", "주소"]},
{"name": "request_refund", "description": "환불을 신청한다. 사유를 함께 받는다.",
"params": {"order_id": "주문번호", "reason": "환불 사유"}, "keywords": ["환불", "반품"]},
{"name": "request_exchange", "description": "크기나 색 교환을 신청한다.",
"params": {"order_id": "주문번호", "option": "바꿀 크기나 색"}, "keywords": ["교환"]},
{"name": "cancel_order", "description": "출고 전 주문을 취소한다.",
"params": {"order_id": "주문번호"}, "keywords": ["취소"]},
{"name": "check_coupon", "description": "쿠폰 사용 조건과 남은 기한을 확인한다.",
"params": {"coupon_code": "쿠폰 번호"}, "keywords": ["쿠폰", "할인"]},
{"name": "add_gift_wrap", "description": "출고 전 주문에 선물 포장을 더한다.",
"params": {"order_id": "주문번호"}, "keywords": ["선물", "포장"]},
{"name": "issue_receipt", "description": "현금영수증이나 세금계산서를 발급한다.",
"params": {"order_id": "주문번호", "kind": "현금영수증 또는 세금계산서"}, "keywords": ["영수증", "계산서"]},
{"name": "search_products", "description": "상품을 이름이나 분류로 찾는다.",
"params": {"query": "찾을 말"}, "keywords": ["상품", "추천", "찾아"]},
]
CONVERSATION = [
("user", "안녕하세요. 어제 주문한 것 문의드려요. 주문번호는 MO-20261104-0172예요."),
("assistant", "주문번호 MO-20261104-0172 확인했습니다. 무선 이어폰 1개이고, 오후 1시 12분에 결제되어 당일 출고 대상입니다."),
("user", "선물이라서 선물 포장 부탁드려요. 가격표는 빼 주세요."),
("assistant", "출고 전이라 선물 포장을 더했습니다. 선물 포장한 주문에는 가격표와 영수증을 넣지 않습니다."),
("user", "그리고 쿠폰을 쓰려고 했는데 결제 화면에 안 보였어요."),
("assistant", "결제 금액이 3만 원 이상일 때만 쿠폰이 보입니다. 이번 주문은 2만 8천 원이라 쿠폰을 쓸 수 없었습니다."),
("user", "아 그렇군요. 다음엔 더 담아서 살게요. 골드 등급은 어떻게 돼요?"),
("assistant", "지난 6개월 구매 금액이 50만 원 이상이면 골드 등급이 됩니다. 매달 무료 배송 쿠폰 두 장을 받습니다."),
("user", "알겠습니다. 혹시 색깔 교환도 되나요? 흰색 말고 검은색으로요."),
("assistant", "받은 날부터 14일 안에 교환을 신청할 수 있습니다. 색 교환의 왕복 배송비는 고객님이 내셔야 합니다."),
("user", "음, 배송비를 내야 하면 그냥 둘게요."),
("assistant", "네, 교환은 신청하지 않았습니다. 더 도와드릴 일이 있을까요?"),
]
TEST_CASES = [
{"query": "그 주문 언제 도착해요?", "needs": ["MO-20261104-0172", "출고 다음 날 도착"], "tool": "track_shipping"},
{"query": "포장 뜯었는데 환불돼요?", "needs": ["포장을 뜯은 상품은"], "tool": "request_refund"},
{"query": "배송지를 회사로 바꿀 수 있나요?", "needs": ["출고 전까지만", "MO-20261104-0172"], "tool": "change_address"},
{"query": "선물 포장한 거 영수증은 어떻게 받아요?", "needs": ["영수증을 넣지 않습니다", "결제 완료 화면"], "tool": "issue_receipt"},
{"query": "쿠폰 두 장 같이 써도 돼요?", "needs": ["함께 쓸 수는 없습니다"], "tool": "check_coupon"},
{"query": "검은색으로 교환 다시 할게요", "needs": ["왕복 배송비", "MO-20261104-0172"], "tool": "request_exchange"},
{"query": "주문 취소해 주세요", "needs": ["MO-20261104-0172"], "tool": "cancel_order"},
{"query": "돈을 돌려받고 싶어요", "needs": ["3영업일"], "tool": "request_refund"},
]
MEASURED_O200K = {
"ko": ("모아샵 환불 정책입니다. 상품을 받은 날부터 7일 안에 환불을 요청할 수 있습니다.", 26),
"en": ("Refunds can be requested within 7 days of receiving the item.", 14),
}
MEASURED_O200K_ALL_TEXTS = 14952) Counting tokens
To make a budget you must count first. The common rough estimate is "word count × 1.3". For English it is fairly accurate, but in Korean one word is split into several tokens, so it falls far short. So we build one more estimate that deliberately counts generously: 1 token per Hangul character, 1.3 tokens per English word, 1 token per three digits, and 1 token per symbol.
HANGUL = re.compile(r"[가-힣]")
PIECE = re.compile(r"[A-Za-z]+|\d+|[^\sA-Za-z\d]")def estimate_tokens_words(text):
"""The common rule of thumb: whitespace words x 1.3. Fine for English, far too low for Korean."""
return round(len(text.split()) * 1.3)
def estimate_tokens(text):
"""A deliberately high estimate: 1 per Hangul syllable, 1.3 per Latin word, 1 per 3 digits, 1 per symbol.
A budget estimate should err high: guessing low is how a request overflows the window.
"""
hangul = len(HANGUL.findall(text))
latin = digits = symbols = 0
for piece in PIECE.findall(HANGUL.sub(" ", text)):
if piece.isascii() and piece.isalpha():
latin += 1
elif piece.isdigit():
digits += math.ceil(len(piece) / 3)
else:
symbols += 1
return hangul + math.ceil(latin * 1.3) + digits + symbolsXenLook note The real token count differs from model to model, because the to…
The real token count differs from model to model, because the tokenizers differ. MEASURED_O200K in the code is a reference value counted once with OpenAI's o200k tokenizer. Claude and Gemini each provide their own token-counting API (see "Try it" below). In a real service, count with that API instead of an estimate.
3) A budget that does not cut the question
ContextBudget first sets aside the room for the answer from the window size, then counts the remaining room for each incoming text. If there is not enough room, it inserts only up to the last sentence that fits. If a text with required=True has no room, it raises an error instead of cutting silently. An error is better than a request going out with the rules or the question cut off.
def split_sentences(text):
return [s for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s]
def fit_sentences(text, limit):
"""Keep whole sentences from the start until the next one would not fit."""
kept, used = [], 0
for s in split_sentences(text):
cost = estimate_tokens(s)
if used + cost > limit:
break
kept.append(s)
used += cost
return " ".join(kept)
class ContextBudget:
"""Token accounting for one request. The output reserve is set aside before anything else."""
def __init__(self, window, reserve_output):
self.window = window
self.reserve_output = reserve_output
self.parts = []
@property
def used(self):
return sum(p["tokens"] for p in self.parts)
@property
def left(self):
return self.window - self.reserve_output - self.used
def take(self, name, text, required=False):
"""Add text if it fits; otherwise keep whole sentences that fit. Returns the text actually kept."""
cost = estimate_tokens(text)
if cost <= self.left:
kept = text
elif required:
raise ValueError(f"{name} needs {cost} tokens but only {self.left} are left")
else:
kept = fit_sentences(text, self.left)
if kept:
self.parts.append({"name": name, "tokens": estimate_tokens(kept), "cut": kept != text})
return kept4) Relevance and placement
It counts how much a document and the question overlap using two-character pieces. As you saw in Stage 3, two-character pieces treat "환불은" and "환불을" (the same word "refund" with different endings) as the same thing. The documents lined up in relevance order are placed with the most relevant first, the second most relevant last, and the rest in the middle.
def bigrams(text):
out = set()
for word in re.findall(r"[\w-]+", text.lower()):
out.update(word[i:i + 2] for i in range(max(1, len(word) - 1)))
return out
def score_relevance(query, text):
"""Share of the query's two-letter pieces that also appear in the text (0 to 1)."""
q = bigrams(query)
return len(q & bigrams(text)) / len(q) if q else 0.0
def rank_documents(query, documents):
scored = [(round(score_relevance(query, d["title"] + " " + d["text"]), 2), d) for d in documents]
return [(s, d) for s, d in sorted(scored, key=lambda x: -x[0]) if s > 0]
def reorder_for_position(items):
"""Best-first list -> best at the front, second best at the back, weakest in the middle."""
front, back = [], []
for i, item in enumerate(items):
(front if i % 2 == 0 else back).append(item)
return front + back[::-1]5) Conversation memory
Recent turns are kept as they are, within a set number of tokens. Turns older than that are summarized by keeping only the sentences in which the customer asks for or decides something. The order number is held separately as a "must-keep fact", wherever in the conversation it appeared.
ORDER_ID = re.compile(r"MO-\d{8}-\d{4}")
FACT_CUES = re.compile(r"MO-\d{8}-\d{4}|부탁|주세요|말고|둘게요|할게요|살게요")def turn_text(turn):
role, text = turn
return ("고객: " if role == "user" else "상담: ") + text
class ConversationMemory:
"""Recent turns verbatim, older turns squeezed into kept sentences, order numbers pinned."""
def __init__(self, turns, recent_tokens):
self.turns = list(turns)
self.recent_tokens = recent_tokens
def pinned_facts(self):
ids = []
for _, text in self.turns:
for oid in ORDER_ID.findall(text):
if oid not in ids:
ids.append(oid)
return [f"상담 중인 주문번호: {oid}" for oid in ids]
def split(self):
"""Newest turns that fit in recent_tokens stay verbatim; everything older goes to the summary."""
recent, used = [], 0
for turn in reversed(self.turns):
cost = estimate_tokens(turn_text(turn))
if used + cost > self.recent_tokens:
break
recent.insert(0, turn)
used += cost
return self.turns[:len(self.turns) - len(recent)], recent
def summary(self, older):
"""Rule-based: keep customer sentences with requests or decisions. A real system asks a model."""
lines = []
for role, text in older:
if role != "user":
continue
lines += [s for s in split_sentences(text) if FACT_CUES.search(s)]
return "앞선 대화 요약: " + " ".join(lines) if lines else ""XenLook note The summary here is sentences picked out by rules, not a summary…
The summary here is sentences picked out by rules, not a summary written by a model. Real services often leave summarizing to a model. Even then, it is safer to hold values that must not be wrong, such as order numbers, amounts and dates, separately as this code does. A model's summary can drop or change numbers.
6) Choosing tools
Each tool gets keywords, and it is chosen if the question contains those keywords. The order-lookup tool is always inserted. It is a simple method that only checks whether the characters are present, so where it goes wrong shows directly in the results.
def tool_text(tool):
return json.dumps({"name": tool["name"], "description": tool["description"],
"input_schema": {"type": "object",
"properties": {k: {"type": "string", "description": v}
for k, v in tool["params"].items()},
"required": list(tool["params"])}},
ensure_ascii=False)
def select_tools(query, tools, limit=3):
"""Always-on tools plus the best keyword matches. Substring matching on purpose, to show its failures."""
always = [t for t in tools if t.get("always")]
scored = []
for t in tools:
if t.get("always"):
continue
hits = sum(1 for k in t["keywords"] if k in query)
if hits:
scored.append((hits, t))
scored.sort(key=lambda x: -x[0])
return always + [t for _, t in scored[:limit]]7) Assembly and "put everything in"
ContextEngine.assemble separates the insertion order from the placement order. When inserting, it claims space in the order rules → question → memory → tools → documents → recent conversation → summary, and when placing, it lays them out in the order rules → memory → tools → documents → summary → recent conversation → question. The question goes in only once, at the very end.
The opponent to compare against, assemble_dump, is the common first version. It puts in all the tools, all the documents and all the conversation, drops the oldest conversation first if it overflows, and if it still overflows, cuts the back of the documents.
class ContextEngine:
"""Decide what goes in by priority, then lay it out in reading order."""
def __init__(self, window, reserve_output=300, recent_tokens=160, doc_limit=3, tool_limit=3):
self.window = window
self.reserve_output = reserve_output
self.recent_tokens = recent_tokens
self.doc_limit = doc_limit
self.tool_limit = tool_limit
def assemble(self, query, turns):
budget = ContextBudget(self.window, self.reserve_output)
memory = ConversationMemory(turns, self.recent_tokens)
older, recent = memory.split()
# Allocation order = priority. The system prompt and the question are reserved first, so they
# can never be the part that gets cut.
system = budget.take("system", SYSTEM_PROMPT, required=True)
question = budget.take("query", "고객 질문: " + query, required=True)
facts = budget.take("memory", "\n".join(memory.pinned_facts()))
tools = [t for t in select_tools(query, TOOLS, self.tool_limit)
if budget.take("tool:" + t["name"], tool_text(t))]
docs = []
for score, d in rank_documents(query, KNOWLEDGE)[:self.doc_limit]:
kept = budget.take("doc:" + d["id"], d["text"])
if kept:
docs.append({"id": d["id"], "title": d["title"], "text": kept})
recent_kept = [t for t in reversed(recent) if budget.take("turn", turn_text(t))][::-1]
summary = budget.take("summary", memory.summary(older)) if older else ""
# Reading order: rules first, question last, retrieved text near the end of the reference part.
sections = [("규칙", system)]
if facts:
sections.append(("기억", facts))
if tools:
sections.append(("도구", "\n".join(tool_text(t) for t in tools)))
if docs:
sections.append(("안내문", "\n".join(f"[{d['title']}] {d['text']}"
for d in reorder_for_position(docs))))
if summary:
sections.append(("요약", summary))
if recent_kept:
sections.append(("최근 대화", "\n".join(turn_text(t) for t in recent_kept)))
sections.append(("질문", question))
text = "\n\n".join(f"## {name}\n{body}" for name, body in sections)
return text, budget, [t["name"] for t in tools], [d["id"] for d in docs]
def assemble_dump(query, turns, window, reserve_output=300):
"""The usual first version: everything in, oldest turns dropped first, then documents cut from the end."""
limit = window - reserve_output
head = SYSTEM_PROMPT + "\n" + "\n".join(tool_text(t) for t in TOOLS)
tail = "고객 질문: " + query
docs = "\n".join(f"[{d['title']}] {d['text']}" for d in KNOWLEDGE)
history = [turn_text(t) for t in turns]
def total():
return sum(estimate_tokens(x) for x in [head, docs, tail] + history)
while history and total() > limit:
history.pop(0)
if total() > limit:
docs = fit_sentences(docs, max(0, limit - estimate_tokens(head) - estimate_tokens(tail)))
return "\n\n".join([head, docs] + history + [tail])
def included(text, needs):
return sum(1 for n in needs if n in text)8) Run it all
It runs the seven experiments in turn. The last one, STEP 7, varies the window size and counts how many of the needed phrases got into the "put everything in" version and into the assembled context.
def all_context_texts():
return ([SYSTEM_PROMPT] + [d["text"] for d in KNOWLEDGE] + [tool_text(t) for t in TOOLS]
+ [turn_text(t) for t in CONVERSATION])
def step_tokens():
print("=" * 64)
print("STEP 1: Estimating tokens")
print("=" * 64)
print(f" {'sample':9} {'words':>5} {'words*1.3':>9} {'estimate':>8} {'o200k':>6}")
for name, (text, measured) in MEASURED_O200K.items():
print(f" {name:9} {len(text.split()):5} {estimate_tokens_words(text):9} "
f"{estimate_tokens(text):8} {measured:6}")
texts = all_context_texts()
words = sum(estimate_tokens_words(t) for t in texts)
est = sum(estimate_tokens(t) for t in texts)
real = MEASURED_O200K_ALL_TEXTS
print(f" {'all ' + str(len(texts)):9} {'':5} {words:9} {est:8} {real:6}")
print(f" words*1.3 over all texts: {100 * (words - real) / real:+.0f}%, estimate: {100 * (est - real) / real:+.0f}%")
print(" guessing low overflows the window; guessing high only wastes some room")
print(" real counts come from each model's counting API")
print()
def step_budget():
print("=" * 64)
print("STEP 2: A budget that cannot cut the question")
print("=" * 64)
query = "그 주문 언제 도착해요?"
window, reserve = 700, 300
history = "\n".join(turn_text(t) for t in CONVERSATION)
docs = "\n".join(d["text"] for d in KNOWLEDGE)
tools = "\n".join(tool_text(t) for t in TOOLS)
arrival = ContextBudget(window, reserve)
for name, text in [("system", SYSTEM_PROMPT), ("tools", tools), ("docs", docs),
("history", history), ("query", "고객 질문: " + query)]:
arrival.take(name, text)
names = [p["name"] + ("(cut)" if p["cut"] else "") for p in arrival.parts]
kept = {p["name"] for p in arrival.parts}
dropped = [n for n in ("system", "tools", "docs", "history", "query") if n not in kept]
print(f" window {window}, output reserve {reserve}, input room {window - reserve}")
print(f" arrival order : kept {', '.join(names)}; dropped {', '.join(dropped)}")
text, budget, _, _ = ContextEngine(window, reserve).assemble(query, CONVERSATION)
print(f" priority order: {budget.used} tokens used, {budget.left} left, query included: {query in text}")
for p in budget.parts:
print(f" {p['name']:24} {p['tokens']:4}{' (cut)' if p['cut'] else ''}")
print()
def step_position():
print("=" * 64)
print("STEP 3: Ordering for position")
print("=" * 64)
query = "선물 포장한 거 영수증은 어떻게 받아요?"
ranked = rank_documents(query, KNOWLEDGE)
print(" relevance:", ", ".join(f"{d['id']} {s:.2f}" for s, d in ranked))
ids = [d["id"] for _, d in ranked]
print(" placed :", " | ".join(reorder_for_position(ids)))
print(" best two sit at the edges, weakest in the middle")
print()
def step_memory():
print("=" * 64)
print("STEP 4: Keeping what matters from old turns")
print("=" * 64)
memory = ConversationMemory(CONVERSATION, recent_tokens=160)
older, recent = memory.split()
full = sum(estimate_tokens(turn_text(t)) for t in CONVERSATION)
summary = memory.summary(older)
kept = sum(estimate_tokens(turn_text(t)) for t in recent)
print(f" {len(CONVERSATION)} turns, {full} tokens verbatim")
print(f" recent {len(recent)} turns verbatim: {kept} tokens")
print(f" older {len(older)} turns -> summary {estimate_tokens(summary)} tokens")
print(" |", summary)
print(" pinned:", "; ".join(memory.pinned_facts()))
tail_only = "\n".join(turn_text(t) for t in recent)
print(f" order number in recent turns alone: {'MO-20261104-0172' in tail_only}")
print(f" order number with summary + pinned: {'MO-20261104-0172' in summary + ' '.join(memory.pinned_facts())}")
print()
def step_tools():
print("=" * 64)
print("STEP 5: Choosing tools")
print("=" * 64)
all_tokens = sum(estimate_tokens(tool_text(t)) for t in TOOLS)
found, extra, spent = 0, 0, 0
for case in TEST_CASES:
chosen = [t["name"] for t in select_tools(case["query"], TOOLS)]
ok = case["tool"] in chosen
found += ok
wrong = [n for n in chosen if n not in ("order_lookup", case["tool"])]
extra += len(wrong)
spent += sum(estimate_tokens(tool_text(t)) for t in TOOLS if t["name"] in chosen)
mark = "ok " if ok else "MISS"
print(f" {mark} {case['query'][:18]:18} -> {', '.join(n for n in chosen if n != 'order_lookup') or '-'}")
n = len(TEST_CASES)
print(f" needed tool offered: {found}/{n}, unneeded extras: {extra}")
print(f" tool tokens: all {len(TOOLS)} tools {all_tokens} per request, selected {spent / n:.0f} on average")
print()
def step_assembly():
print("=" * 64)
print("STEP 6: The assembled context")
print("=" * 64)
query = "그 주문 언제 도착해요?"
text, budget, tools, docs = ContextEngine(1400).assemble(query, CONVERSATION)
print(f" window 1400: {budget.used} input tokens + 300 reserved for the answer")
print(f" question appears {text.count(query)} time(s), as the last section")
for line in text.split("\n"):
print(" |", line if len(line) <= 70 else line[:67] + "...")
print()
def step_measure():
print("=" * 64)
print("STEP 7: Measuring what made it in")
print("=" * 64)
total_needs = sum(len(c["needs"]) for c in TEST_CASES)
n = len(TEST_CASES)
print(f" {n} questions, {total_needs} needed facts; counts facts present in the text, not answers")
print(f" {'window':>6} {'dump + cut':>10} {'engineered':>10} {'dump tokens':>11} {'eng. tokens':>11}")
for window in (2600, 2000, 1600, 1400, 900, 700):
dump_hits = eng_hits = dump_tok = eng_tok = 0
for c in TEST_CASES:
dump = assemble_dump(c["query"], CONVERSATION, window)
text, budget, _, _ = ContextEngine(window).assemble(c["query"], CONVERSATION)
dump_hits += included(dump, c["needs"])
eng_hits += included(text, c["needs"])
dump_tok += estimate_tokens(dump)
eng_tok += budget.used
over = dump_tok / n > window - 300
dump_cell = "too big" if over else f"{dump_hits}/{total_needs}"
print(f" {window:6} {dump_cell:>10} {f'{eng_hits}/{total_needs}':>10} "
f"{dump_tok / n:11.0f} {eng_tok / n:11.0f}")
missed = []
for c in TEST_CASES:
text, _, _, _ = ContextEngine(900).assemble(c["query"], CONVERSATION)
missed += [f"{c['query'][:14]} <- {need}" for need in c["needs"] if need not in text]
print(" engineered misses at 900:", "; ".join(missed) or "none")
print()if __name__ == "__main__":
step_tokens()
step_budget()
step_position()
step_memory()
step_tools()
step_assembly()
step_measure()How to read the results
XenLook note This section is guidance added by XenLook.
This section is guidance added by XenLook.
STEP 1 is token counting.
sample words words*1.3 estimate o200k
ko 12 16 35 26
en 11 14 15 14
all 31 706 2101 1495
words*1.3 over all texts: -53%, estimate: +41%
guessing low overflows the window; guessing high only wastes some room
real counts come from each model's counting APIFor the Korean sentence, "word count × 1.3" says 16 tokens, but the real count is 26 tokens. Over all 31 texts in this program it is 706 against 1,495, less than half. The JSON symbols in the tool descriptions and the Korean descriptions piled on top of each other. If you made a budget from these numbers, the request would overflow the window. The generous estimate counts 41% high. It wastes a little room but does not overflow. If an estimate is going to be wrong, it is better for it to be wrong on the high side.
STEP 2 is the difference in insertion order.
window 700, output reserve 300, input room 400
arrival order : kept system, docs(cut), history(cut); dropped tools, query
priority order: 396 tokens used, 4 left, query included: True
system 76
query 15
memory 18
tool:order_lookup 110
tool:track_shipping 102
doc:shipping 75This is a small window with 400 tokens of room for input. If you fill in order of arrival (rules → tools → documents → conversation → question), the documents and the conversation use up all the room, and the question, of all things, is left out. Not a single tool got in. A tool description (JSON) has no place to cut at a sentence boundary, so it was dropped whole. If you fill by priority, the rules and the question claim their space first, and then the order number, the two tools that are absolutely needed, and one shipping help article go in. There was no room for the conversation, but the order number remained as memory.
STEP 3 is placement.
relevance: gift 0.45, receipt 0.27, refund 0.09
placed : gift | refund | receipt
best two sit at the edges, weakest in the middleFor "선물 포장한 거 영수증은 어떻게 받아요?" ("How do I get the receipt for the one I gift-wrapped?"), the gift-wrap help article is the most relevant and the receipt help article is the next most relevant. The two were placed at the two ends, and the weakly relevant refund help article was placed in the middle.
STEP 4 is conversation memory.
12 turns, 436 tokens verbatim
recent 4 turns verbatim: 125 tokens
older 8 turns -> summary 59 tokens
| 앞선 대화 요약: 주문번호는 MO-20261104-0172예요. 선물이라서 선물 포장 부탁드려요. 가격표는 빼 주세요. 다음엔 더 담아서 살게요.
pinned: 상담 중인 주문번호: MO-20261104-0172
order number in recent turns alone: False
order number with summary + pinned: TrueLeft as they are, the 12 turns of conversation are 436 tokens. Only the last 4 turns (125 tokens) are kept as they are, and the earlier 8 turns were shrunk into a summary of 59 tokens. In the common approach of keeping only the last 4 turns, the order number disappears, because it appeared only in the first turn. The summary and the "must-keep facts" protect it. The limits of a rule-based summary show too. "다음엔 더 담아서 살게요" ("I'll buy more next time") is a sentence that is useless right now, but it stayed because of the word "살게요" ("I will buy").
STEP 5 is choosing tools.
ok 그 주문 언제 도착해요? -> track_shipping
ok 포장 뜯었는데 환불돼요? -> request_refund, add_gift_wrap
ok 배송지를 회사로 바꿀 수 있나요? -> track_shipping, change_address
ok 선물 포장한 거 영수증은 어떻게 -> add_gift_wrap, issue_receipt
ok 쿠폰 두 장 같이 써도 돼요? -> check_coupon
ok 검은색으로 교환 다시 할게요 -> request_exchange
ok 주문 취소해 주세요 -> cancel_order
MISS 돈을 돌려받고 싶어요 -> -
needed tool offered: 7/8, unneeded extras: 3
tool tokens: all 10 tools 1136 per request, selected 252 on averageInserting all ten costs 1,136 tokens per request (by the generous estimate), and inserting a selection costs 252 on average. In exchange, the weakness of character overlap shows.
- In "배송지를…" ("Can I change the shipping address to the office?"), the delivery-tracking tool tags along. Because "배송" ("shipping") is contained in "배송지" ("shipping address").
- In "포장 뜯었는데 환불돼요?" ("I opened the packaging, can I get a refund?"), the gift-wrap tool tags along. Because "포장" ("wrapping") overlaps.
- "돈을 돌려받고 싶어요" ("I want my money back") misses the refund tool (MISS). Not one keyword overlaps.
A tool that tags along wastes room and can confuse the model, but a missed tool keeps the model from doing its job at all. So in practice you choose generously, or compare tool descriptions with the question using the embeddings from Stage 3, or let the model look for tools itself.
STEP 6 is the whole assembled context.
window 1400: 695 input tokens + 300 reserved for the answer
question appears 1 time(s), as the last section
| ## 규칙
| 너는 모아샵 고객 상담 에이전트다. 아래 안내문과 도구만 근거로 답한다. 안내문에 없는 내용은 모른다고 말하고 상담원 연...
|
| ## 기억
| 상담 중인 주문번호: MO-20261104-0172
|
| ## 도구
| {"name": "order_lookup", "description": "주문번호로 주문 상태, 결제 금액, 출고 여부를...
| {"name": "track_shipping", "description": "송장 번호와 지금 배송 위치를 조회한다.",...
|
| ## 안내문
| [배송] 오후 2시 전에 결제한 주문은 당일 출고합니다. 출고 다음 날 도착하는 것이 보통입니다. 제주와 도서 지역은 1...
| [선물 포장] 선물 포장은 주문할 때 고르며, 출고 전이면 고객센터에서 더할 수 있습니다. 선물 포장한 주문에는 가격표와...
| [쿠폰] 쿠폰은 결제 금액이 3만 원 이상일 때만 쓸 수 있습니다. 쿠폰 두 장을 한 주문에 함께 쓸 수는 없습니다. 기...
|
| ## 요약
| 앞선 대화 요약: 주문번호는 MO-20261104-0172예요. 선물이라서 선물 포장 부탁드려요. 가격표는 빼 주세요. ...
|
| ## 최근 대화
| 고객: 알겠습니다. 혹시 색깔 교환도 되나요? 흰색 말고 검은색으로요.
| 상담: 받은 날부터 14일 안에 교환을 신청할 수 있습니다. 색 교환의 왕복 배송비는 고객님이 내셔야 합니다.
| 고객: 음, 배송비를 내야 하면 그냥 둘게요.
| 상담: 네, 교환은 신청하지 않았습니다. 더 도와드릴 일이 있을까요?
|
| ## 질문
| 고객 질문: 그 주문 언제 도착해요?This is the text that actually goes to the model. The rules are at the very beginning, and the question appears once, at the very end. In the documents section, the most relevant shipping help article is first, the second, the coupon help article, is last, and the weakest, the gift-wrap help article, is in the middle. Counting this whole text, including the heading lines, with the generous estimate gives 737 tokens, and counting with o200k gives 555 tokens. Again the estimate counted high.
STEP 7 is measurement.
8 questions, 12 needed facts; counts facts present in the text, not answers
window dump + cut engineered dump tokens eng. tokens
2600 12/12 11/12 2150 691
2000 8/12 11/12 1694 691
1600 1/12 11/12 1292 691
1400 too big 11/12 1222 691
900 too big 11/12 1222 572
700 too big 7/12 1222 395
engineered misses at 900: 돈을 돌려받고 싶어요 <- 3영업일- When the window is roomy (2600), "put everything in" wins. All 12 got in, against 11 for the assembled version. But "put everything in" costs 2,150 tokens per request, and the assembled version 691 tokens. And "was included" is not "was used". As in the Liu et al. experiment above, when there is a lot of unneeded text, even information that was included can get buried. This program cannot measure that.
- When the window shrinks, "put everything in" collapses. At 2000 the oldest conversation is dropped first and the order number disappears, giving 8; at 1600 the documents are cut too, giving 1. From 1400 on, the rules and tools alone overflow the room, so the request itself cannot be sent (
too big). - The assembled version keeps 11 down to 900. At 700 there is not enough room for the conversation and documents, and it falls to 7.
- What the assembled version misses to the end is the "3영업일" ("3 business days") for "돈을 돌려받고 싶어요". Two-character pieces cannot find the refund help article. It is the same limit you saw in Stage 3. You need a learned embedding search, and that is the topic of the next stage, Stage 5 RAG.
| Part of the output | Meaning |
|---|---|
| STEP 1 | "Word count × 1.3" counts Korean at about half. The generous estimate counts high |
| STEP 2 | Filling in arrival order drops the question; filling by priority protects the rules and the question |
| STEP 3 | Put highly relevant documents at both ends and weak documents in the middle |
| STEP 4 | Keeping only recent turns loses the order number; summary + must-keep facts protect it |
| STEP 5 | Selecting tools cuts tokens, but character overlap goes wrong in places |
| STEP 6 | The whole text that goes to the model. The question once, at the very end |
| STEP 7 | How many needed phrases got in at each window size — inclusion, not the correct-answer rate |
Try it
XenLook note All the code below is blocked out with comments (#), so it doe…
All the code below is blocked out with comments (#), so it does not run. To actually run it you need each company's API key. The model IDs and function names are the ones in each company's official documents as of November 2026, so when you run them yourself, check that day's documents once more.
Counting real tokens
Make the budget with the tokenizer of the model you will use, not with an estimate.
# Claude: only counts tokens before sending the message. It costs nothing, and there is a separate per-minute limit
# import anthropic
#
# client = anthropic.Anthropic()
# count = client.messages.count_tokens(
# model="claude-sonnet-5-5",
# system="너는 모아샵 고객 상담 에이전트다.",
# messages=[{"role": "user", "content": "그 주문 언제 도착해요?"}],
# )
# print(count.input_tokens)# Gemini
# from google import genai
#
# client = genai.Client()
# result = client.models.count_tokens(
# model="gemini-4-argon",
# contents="모아샵 환불 정책입니다. 상품을 받은 날부터 7일 안에 환불을 요청할 수 있습니다.",
# )
# print(result.total_tokens)# OpenAI family: counts right on your own computer (pip install tiktoken)
# import tiktoken
#
# enc = tiktoken.get_encoding("o200k_base")
# print(len(enc.encode("모아샵 환불 정책입니다. 상품을 받은 날부터 7일 안에 환불을 요청할 수 있습니다."))) # 26Context management done on the model side
You do not have to build everything yourself. As of November 2026, these features exist.
- Tool search (Anthropic): If you mark a tool with
defer_loading, its description is not inserted at first, and the model uses tool search to find and load only the tools it needs. The 85% reduction you saw earlier comes from this approach. - Compaction and context editing (Anthropic): When the conversation gets long, the server summarizes and continues, or clears tool results that have been fully used.
- Cache: The front part that is sent exactly the same every time (rules, tool descriptions) is stored and reused cheaply. But a cached part still takes up the same space in the window. It saves money and time but not space. Caching is covered separately in a later stage.
The context of a coding agent
Claude Code uses the ideas of this lesson as they are. It does not put in all the code from the start; it finds and opens the files it needs with tools. At the start of a session it reads CLAUDE.md and automatic memory and uses them as long-term memory. When the conversation gets long, it compacts. So it is better to keep CLAUDE.md short and write only what must be known every time. It uses space in the window every session.
Retrieval with context attached
If you split documents into chunks and search them, the chunks lose their own context. Looking only at the chunk "it is returned within 3 business days", you cannot tell what is returned. Anthropic published a method that has a model attach to each chunk a short description such as "This chunk is part of the Moashop refund guide…" and then indexes it. The share where the correct chunk is not among the top 20 fell from 5.7% to 3.7% (a 35% reduction); attaching the same description to keyword search (BM25) too brought it to 2.9% (a 49% reduction), and adding re-ranking brought it to 1.9% (a 67% reduction). The same post says that if the knowledge document is smaller than 200,000 tokens, putting it whole into the prompt without retrieval is also an option. When the window is large and a cache is available, that is simpler.
Export
This lesson makes two deliverables.
Context audit prompt — a prompt template that, when you tell it how your app assembles its context, tabulates the tokens per part, finds where there is waste, where there is truncation risk, and placement problems, and tells you what to fix in what order and how to measure to confirm it.
Context engineering skill — a framework for judgment covering budgeting, insertion order and placement order, conversation memory, tool selection, retrieval and measurement.
The Python code (code/context_engineering.py) is a practice tool that runs on its own. If you replace estimate_tokens with the token-counting API above and score_relevance with the embedding similarity from Stage 3, the budget management, assembly and measurement work as they are, without fixing anything.
XenLook note You can unfold the two deliverables in English under "Deliverabl…
You can unfold the two deliverables in English under "Deliverables" at the bottom of this page. Just copy them as they are and paste them into an AI chat window or a coding agent.
Exercises
- Add waste finding. Put into
ContextBudgeta feature that shows the share of the total that each part's tokens take, and write down which part is the largest at each window size in STEP 7. Do not set a standard like "over some % is waste"; judge by how the inclusion count changes when you shrink that part. - Remove overlapping documents. Build a feature that, when the two-character pieces of two retrieved documents overlap heavily, keeps only the one with the higher score, and measure how much room it wins back. Decide the overlap threshold by measuring too.
- Replay the conversation one turn at a time. Grow
CONVERSATIONone turn at a time, assemble withContextEngineeach time, and draw a table of how the tokens per part change from turn to turn. Find the turn at which a summary first appears. - Choose tools by score. Instead of keyword overlap, score by the two-character-piece relevance between the tool description and the question, and insert in score order until the tool budget fills. See how the missed tools and the tagged-along tools in STEP 5 change.
- Compare three ways of shrinking. Build plain truncation, rule-based summary (this code), and keeping only the sentences related to the question, and measure the "share shrunk" and the "share of needed phrases that remained" together over at least 20 questions.
Key terms
| Term | What people say | What it actually means |
|---|---|---|
| Context window | "How much the model can read" | All the tokens the model handles in a single request. Input and answer (including thinking tokens for a thinking model) go in together. How the size is stated differs by company |
| Context engineering | "Advanced prompt engineering" | Deciding what to put in the window, in what order, and with what priority. Includes retrieval, shrinking, tool selection and memory management |
| Lost in the middle | "It forgets the middle" | The phenomenon where the correct-answer rate drops when the document containing the answer is in the middle. Measured by Liu et al. (2023). The degree differs by model |
| Token budget | "Tokens left" | The window's space divided and set by part. The room for the answer is set aside first |
| Dynamic context | "Load it on the fly" | Choosing tools, documents and conversation and assembling anew for each question |
| Conversation summary | "Compressing the conversation" | Replacing old turns with a summary to cut space. Values that must not be wrong are protected separately |
| Tool selection | "Only the tools needed" | Inserting only the tool descriptions that fit the question. There is also tool search, which has the model look for them itself |
| Long-term memory | "Remembers after the session ends" | Facts and preferences stored separately and inserted at the start of a conversation. Example: CLAUDE.md |
| Episodic memory | "That thing from last time" | Storing past conversations as embeddings and finding and inserting them when they resemble the present one |
| Room for the answer | "Space to write the answer" | The tokens reserved for the model's answer (and thinking). If you fill it all with input, the answer is cut off |
| Must-keep facts | "A pinned note" | Separately holding on to values that must not drop out even when the conversation shrinks, such as an order number (a term added in the XenLook course) |
| Inclusion measurement | "Counting whether it got in" | Counting whether the phrases each question needs got into the assembled context. Different from the correct-answer rate (a term added in the XenLook course) |
Further reading
- Liu et al., 2023 — "Lost in the Middle: How Language Models Use Long Contexts" — The paper that measured how the correct-answer rate changes with the position of the document containing the answer
- Anthropic — "Effective context engineering for AI agents" — Compaction, taking notes, fetching when needed, clearing tool results
- Anthropic — "Introducing Contextual Retrieval" — How attaching context to chunks reduced retrieval failures, and the numbers
- Anthropic — "Introducing advanced tool use" — How tool search reduced tool-description tokens, and the numbers
- Chroma — "Context Rot" — A report that measured, with 18 models, how performance drops as the input gets longer
- Claude Code memory documentation — When
CLAUDE.mdand automatic memory are read and how they are used - Claude context windows documentation and token counting documentation — What counts toward the window, and how to count before sending
- Gemini tokens documentation — Gemini's token counting and window sizes
- Simon Willison — "Context engineering" (2025-06-27) — A summary from the time when this term was spreading. The term itself was spread by Tobi Lütke and Andrej Karpathy
- Greg Kamradt — Needle in a Haystack — A test that has a model find one sentence in a long text. Originally measured with GPT-4 and Claude 2.1
- Pope et al., 2022 — "Efficiently Scaling Transformer Inference" — Why a long input increases memory and response time
- Agrawal et al., 2023 — "SARATHI" — Why the stage of reading the input and the stage of writing the answer differ in cost
- Ainslie et al., 2023 — "GQA" — A method that has several query heads share keys and values, giving quality close to multi-head and speed close to a single key-value
This lesson is Rohit Ghumare's AI Engineering from Scratch translated and corrected by XenLook.
Run it yourself
context_engineering.py
This is the code of this lesson. Press the button and Python runs only inside this browser. Your code and results are never sent to XenLook servers.
Not run yet.
Check your understanding
When you've read it all, try these. You see the answer and the explanation as soon as you choose.
A coding agent uses only 22,700 tokens of a 128,000-token window. Why does it still need budget management?
What is the "sliding window" approach to handling conversation history?
How is it best to divide tokens among the parts when assembling context?
What you take away
These are the things you build in this lesson and keep. Tap to open.
PromptContext Audit PromptA prompt that listens to how your app assembles its context, tabulates the tokens per part, finds waste, truncation risk and placement problems, and tells you what to fix first and how to measure that the fix worked
You are a context engineering auditor. When the user describes how their LLM app assembles the context window, you audit that approach and recommend concrete fixes.
Before recommending anything, ask the following. Do not ask again about anything already answered.
- Model and window size: Which model do you use? What are its window size and maximum answer length? Is thinking (reasoning) turned on?
- Tokens per part: How many tokens are the system prompt, tool descriptions, retrieved documents, past conversation, examples and question, each? How did you count them?
- Tools: How many tools are there? Do you put all of them into every request?
- Retrieval: How do you find documents (embeddings, keyword search, both)? How many do you include?
- Conversation management: Do you include the whole conversation, truncate it, or summarize it? How do you protect values that must be kept, such as order numbers and dates?
- Problems you see: Are answers cut off, does the app forget what was said earlier, call the wrong tool, or have cost or response-time problems?
- Evaluation questions: Do you have questions for which you know the correct answer or the information that is required?
Audit order
1. Sort out the budget
Build a table of tokens per part.
- The numbers must be counted with the token-counting API of the model you will use (Claude
count_tokens, GeminicountTokens, tiktoken for OpenAI-family models). If they were counted with a rough estimate such as "word count × 1.3", mark them as such and warn that the estimate can fall far short for Korean, Japanese, Chinese and JSON. - Write down the room for the answer separately. Check in that model's documentation whether the window size covers input and answer together or input only. If thinking is on, thinking tokens also come out of the room for the answer.
- Write down each part's share of the window. Do not judge something as waste just because its share is large. Whether it is waste is decided in a later step.
2. Truncation risk
- When the window fills up, can the question or the rules be cut off? If the order of insertion is the order of arrival (rules → tools → documents → conversation → question), the question is cut first. The rules and the question must claim their space first, and if there is no space, raise an error instead of cutting silently.
- Is the question counted twice or inserted twice?
- When you discard the conversation starting from the oldest, does an important value that appeared only in the first turn (order number, user name, agreed conditions) disappear with it?
- Does the input fill the window so that the answer gets cut off?
3. Finding waste
Find the following, and write down how many tokens each takes.
- Always the same tool descriptions: Do you put in every tool for every question, including tools that are not used?
- Old conversation: Do you include turns unrelated to the current question as they are?
- Weakly relevant documents: Are low-relevance documents crowding out the documents that are needed? Relevance thresholds differ by model, so do not suggest a fixed value; tell the user to set it from the score distribution of correct versus incorrect documents in the evaluation questions.
- Overlapping information: Does the same fact go into the system prompt, the documents and the conversation several times?
- Long system prompt: Is there anything among the rules resent with every request that could be removed? Do not judge by length alone; judge by removing it and checking whether the results on the evaluation questions change.
4. Placement
- Are the rules at the very beginning and the question at the very end?
- Are retrieved documents placed in relevance order or in arrival order? Suggest a layout that puts the most relevant ones at both ends, but tell the user to measure the effect on their own model, because the results of Liu et al. (2023) differed in degree from model to model.
- Have you separated the order of insertion (priority) from the order of placement (reading order)?
5. What to fix
For each problem you found, give one concrete method.
- Tools: Insert only the tools that fit the question. If there are many tools, use model-side tool search (Anthropic
defer_loading, etc.). - Conversation: Keep recent turns as they are and summarize old ones. Do not leave values that must not be wrong to the summary; hold on to them separately. If server-side compaction or context editing is available, use it.
- Retrieval: Drop weakly relevant documents, drop overlapping documents, re-rank, and attach context to chunks.
- Placement: Separate the order of insertion from the order of placement, and place the question only once, at the very end.
- Counting: Replace rough estimates with that model's token-counting API.
- Cache: Cache the part that is the same every time. But tell the user that caching saves money and time and does not save room in the window.
6. Measure to confirm
For each recommendation, write down the following.
- The tokens saved (per request). If it is an estimate, mark it as such.
- How to confirm by measuring: whether, for each evaluation question, the required information made it into the assembled context (inclusion measurement), and the correct-answer rate of the actual answers. The two are different. Being included does not guarantee being used.
- Whether there is a risk of lower quality, and why.
- The effort required to fix it.
Do not promise in numbers how much quality will improve. Say that you do not know until it is measured.
What the user should tell you
- Model name, window size, whether thinking is used
- Tokens per part and how they were counted
- Number of tools
- Retrieval method (embeddings, keywords, both) and the number of documents inserted
- Conversation management method (include everything, truncate, summarize)
- Problems you see
- If you have evaluation questions, how many
Answer format
- Budget table: tokens per part, share of the window, how they were counted, truncation-risk and waste flags
- The three most urgent problems: truncation risk before waste. Each with its token count
- What to fix: in order of low effort relative to effect
- How to measure to confirm: which evaluation questions you will use to measure inclusion and the correct-answer rate
SkillContext EngineeringA framework for judgment when designing how an LLM app assembles its context — budgeting, insertion order versus placement order, conversation memory, tool selection, retrieval, measurement and common mistakes
When you build an LLM app, use this framework to design how the context is assembled.
Basic principles
- The window is a narrow desk. Even when the window is large, conversation, tools and documents pile up fast. Set a budget for each part.
- Position can change the result. In Liu et al. (2023), many models had a lower correct-answer rate when the document containing the answer was in the middle. The degree differed from model to model. Put the rules first and the question last, and measure the effect on your own model.
- Assemble anew for every question. The tools, documents and conversation that are needed differ from question to question.
- Insert less of what is not needed. The more unneeded text there is, the more the needed text can get buried. Decide how much to cut using evaluation questions.
- Measure. For every request, count the tokens per part, and for every evaluation question, count whether the required information was included.
Setting the budget
| Part | Priority | How to shrink it |
|---|---|---|
| Question | Highest — must not be cut | Do not shrink |
| Rules (system prompt) | Highest — must not be cut | Write it short, remove overlapping statements |
| Must-keep facts | High | As a short single line |
| Tool descriptions | Depends on the question | Only the ones that fit the question, tool search |
| Retrieved documents | Depends on the question | Re-ranking, remove weakly relevant and overlapping ones |
| Past conversation | Depends on the question | Recent turns as they are, old turns summarized |
| Examples (few-shot) | Depends on the question | Only examples similar to the question |
| Room for the answer | Set aside first | Decide from your answer length and thinking settings |
The size of each part varies a lot from app to app. Do not use a number like "usually this many tokens" as a standard; fill in the table with numbers counted in your own app.
Rule: Count tokens with the token-counting API of the model you will use (Claude count_tokens, Gemini countTokens, tiktoken for OpenAI-family models). If you must use an estimate, lean toward the higher count. "Word count × 1.3" can count about half as many tokens as there really are for Korean and JSON.
Rule: Check in the model's documentation whether the window size covers input and answer together or input only. If thinking is on, thinking tokens also come out of the room for the answer.
Insertion order and placement order
Insertion order (priority): question and rules → must-keep facts → tools → documents → recent conversation → summary of old conversation. If there is no room for the question and rules, raise an error instead of cutting silently.
Placement order (reading order): rules → must-keep facts → tools → documents → summary → recent conversation → question. Place the question only once, at the very end.
If you fill in arrival order, the question that arrives last is cut first. Keep the two orders separate.
Kinds of memory
Short-term memory (the current conversation): It lives inside the window. Manage it with recent turns as they are and old turns as a summary. Decide how many turns to keep as they are by tokens, not by the number of turns, and confirm with evaluation questions.
Long-term memory (facts and preferences): What remains after the session ends. "This user likes large text", "This project uses PostgreSQL". Store it separately and insert it when a session starts. Examples: CLAUDE.md, a database. A file like CLAUDE.md is context the model reads, not an enforced setting. Block what must be blocked with a mechanism such as a hook.
Episodic memory (past events): The past conversations that resemble the present one. Store them as embeddings and find and insert similar ones.
Must-keep facts: Values that must not be wrong or missing, such as order numbers, amounts, dates and conditions the user set. Do not leave them to a summary; hold on to them separately and insert them every time.
Choosing tools
Do not insert every tool into every request. They use up room and can make the model call the wrong tool.
- Work out what the question is trying to do (look up an order, refund, schedule, search …)
- Insert only the group of tools that fits
- If it is ambiguous, insert generously. A tool that tags along uses room, but a missed tool keeps the model from doing its job
- Always insert tools that are always needed (for example, order lookup)
- If there are many tools, use model-side tool search. Anthropic reported an 85% reduction in tool-description tokens with about 50 tools
If you choose by character overlap, "shipping address" drags in the delivery-tracking tool, and "I want my money back" misses the refund tool. Compare tool descriptions with the question using embeddings, or let the model search for them itself. Measure how much it shrinks and how much it misses with evaluation questions.
Retrieval
- Re-rank after fetching: Embedding similarity is a coarse filter. Re-ranking with a cross-encoder or an LLM can raise accuracy. Measure how much it rises.
- Relevance threshold: Do not use a fixed value (for example, cosine 0.3). What a score means differs from model to model. Decide it by looking at the score distribution of correct versus incorrect documents in the evaluation questions.
- Remove overlapping chunks: Of two chunks whose content overlaps heavily, keep only the one with the higher score. Decide the overlap threshold by measuring too.
- Placement: Try a layout that puts the most relevant chunks at both ends.
- Number of chunks to insert: There is no fixed right answer. Vary the number of chunks and measure the correct-answer rate and tokens together.
- Attach context to chunks: If you index each chunk with a short description of "which part of which document this chunk is", retrieval failures can drop (Anthropic's contextual retrieval).
- Whole, without retrieval: If the knowledge document is small (Anthropic gives under 200K tokens as an example) and you can use caching, putting it in whole without retrieval can be simpler.
Conversation management
- Keep recent turns as they are. The model needs the immediately preceding context
- Summarize old turns ("We discussed X, decided on Y, and Z is still unresolved")
- Protect must-keep facts separately from the summary. A summary written by a model can drop or change numbers
- Delete tool-call results that are invisible to the user and have been fully used
- Decide when to start summarizing not by a fixed percentage but by when the budget starts to run short. If server-side compaction or context editing is available, use it
Common mistakes
- Inserting the question last, so the question is cut when the window fills up
- Counting the question twice or inserting it twice
- Counting Korean with "word count × 1.3" and going over the window
- Inserting every tool into every request
- Inserting all retrieved documents without filtering them by relevance
- The conversation grows endlessly (no summary)
- Discarding old conversation and discarding the order number in the first turn along with it
- Not leaving room for the answer, so the answer is cut off. Forgetting thinking tokens
- The same information goes in three times: system prompt, documents and conversation
- Thinking that caching also saves room in the window (it saves only money and time)
- Treating "it was included" and "it answered correctly" as the same thing
Starting values and values to decide by measuring
- Room for the answer: decide from the maximum length of your answers + the thinking settings
- Recent conversation to keep as it is: decide by tokens, and confirm with evaluation questions that earlier facts are not lost
- Number of tools and documents to insert: measure the share missed when you reduce them together with the tokens saved
- Relevance and overlap thresholds: decide separately for each model from the score distribution of the evaluation questions
- Evaluation questions: at least 20 questions for which you know the required information. Record inclusion measurement and the correct-answer rate, and measure again whenever you change anything
This course is XenLook's English translation and revision of Rohit Ghumare's AI Engineering from Scratch (MIT License), based on the Korean edition we corrected against the original. Source commit: 8fec9cc19e.
Full MIT License text
MIT License
Copyright (c) 2026 Rohit Ghumare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.Source lesson: phases/11-llm-engineering/05-context-engineering