Context Is the Scarcest Resource: the Window, Attention Decay, and Cost — From Prompt Engineering to Context Engineering
Break a session's context into four pieces — system prompt, tool definitions, history, and tool results — and work out each one's share, then see why a longer window actually makes mistakes more likely, and reckon the three-part bill of cost, latency, and accuracy.
Today's Goals
- Name the four pieces that make up a model request's context, and work out each one's token share
- Explain attention budget and context rot in your own words, and name the three costs they bring
- Judge whether a problem can be solved with prompt engineering or must be escalated to context engineering
This course solves exactly one thing: what should actually go into the request every time you call a model. Today is about seeing clearly what is in there now — without that, all the pruning, compaction, and isolation of the next four days is guesswork. Once you have read it, scroll back to the top and tick off the three goals.
Plain-Language Walkthrough
Packing a carry-on suitcase before a trip
A carry-on suitcase has fixed capacity. You are away five days and want to bring clothes, a laptop, chargers, a contract, an umbrella, and samples for a client. Start packing and you find the hard part was never whether the case is big enough, but three questions: what has to go in now; what can be bought or borrowed once you arrive; and what looks useful but will never once be opened.
The clever move is not buying a bigger case. The bigger the case, the more you stuff into it, and finding a pen at the hotel takes five minutes of digging. What actually works is three habits: list what goes in before packing, take things out along the way as you need them, and repack at a layover to throw out whatever is finished.
A model's context window is that suitcase. Its capacity is counted in tokens — one token is roughly three or four letters of English. Every call, you have to fill the case again from scratch and hand it over, because the model itself has no memory: it does not recall what was said last turn, and if you do not pack it again, it does not know.
So what to pack turns from a detail into a discipline. It has a name — context engineering — and a one-line definition: before each inference, pick the smallest set of high-signal tokens that lets the model do the right thing. Note the two words in that sentence: smallest and high-signal. They conflict often, and making the trade-off inside that conflict is what these five days practice.
Start by remembering one counter-intuitive conclusion: packing more does not mean working better. The third section explains why.
What is actually in one request
Open the case and look. The context an agent request carries is almost always made of four pieces:
Mermaid source
flowchart LR
A[System prompt] --> E[The context of one request]
B[Tool definitions] --> E
C[Conversation history] --> E
D[Tool results] --> E- The system prompt: role, procedure, hard constraints. Resent verbatim every turn, with essentially constant length.
- Tool definitions: each tool's name, description, and parameter shape. Also resent every turn, with length growing with the number of tools.
- Conversation history: what the user said and what the model said. A few dozen tokens per turn, growing linearly.
- Tool results: the data tools hand back. One call can add two thousand tokens, growing in steps.
Those four grow in completely different ways, so they have to be treated separately. Look at them as one total token count and you will never know where to cut.
The difference in growth has a less obvious consequence: the payoff from changing each piece differs entirely. The system prompt is resent verbatim every turn, so halving it benefits every turn of the whole session — the piece with the highest compounding. Tool results are added once and then sit there, so pruning one saves only that one, but their single-shot volume is the largest, which makes their absolute payoff the highest. Conversation history grows slowest and is usually the smallest of the four. Those three properties set the order of the next four days, and day five puts a real bill on the table to show it.
The easiest thing to get wrong: tool results are written inside messages whose role is user, which makes them look like part of the conversation history, but they are not something the user said. They are data, not dialogue. Count them inside the history and the table is worthless. When splitting, go by content block type, not by message role:
// Split into four pieces by content block type: tool results get their own bucket, never mixed into history
export function splitContext(system, tools, messages) {
const history = []
const toolResults = []
for (const msg of messages) {
const kept = []
for (const block of msg.content) {
if (block.type === 'tool_result') {
toolResults.push({ id: block.tool_use_id, content: block.content })
} else {
kept.push(block)
}
}
// Do not put back a message left with no blocks; the API rejects an empty message
if (kept.length > 0) history.push({ role: msg.role, content: kept })
}
return { system, tools, history, toolResults }
}# Split into four pieces by content block type: tool results get their own bucket, never mixed into history
def split_context(system, tools, messages):
history = []
tool_results = []
for msg in messages:
kept = []
for block in msg["content"]:
if block["type"] == "tool_result":
tool_results.append({"id": block["tool_use_id"], "content": block["content"]})
else:
kept.append(block)
# Do not put back a message left with no blocks; the API rejects an empty message
if kept:
history.append({"role": msg["role"], "content": kept})
return {"system": system, "tools": tools, "history": history, "tool_results": tool_results}Today's lab runs that code over a fictional e-commerce support session. Spoiler on the result: system prompt 280, tool definitions 308, conversation history 218, tool results 2191 — tool results alone are 72.9%. That proportion is very typical of real projects, and almost everybody guesses the bulk is conversation history before they measure.
Attention budget and context rot
"So I switch to a model with a bigger window and I am fine?"
That is everyone's first reaction and the first intuition this course dismantles. A bigger window does solve "it does not fit," but it does not solve another problem: the more you pack, the more the model overlooks.
That phenomenon has a name, context rot: as context grows longer, the model's ability to recall information inside it accurately declines. Its origin is architectural — in a Transformer every token has to relate to every other token, so n tokens mean on the order of n-squared pairwise relations. The longer the context, the thinner the same fixed attention is spread. This is not a cliff but a gentle slope: no particular length suddenly collapses, but every extra thousand irrelevant tokens costs a little accuracy.
There is a more practical reason too: models see mostly shorter sequences during training, so the parameters dedicated to very long-range dependencies are few to begin with. "A nominal 200K window" and "stable behavior across 200K tokens" are two different statements; the nominal number is capacity, not a guarantee.
So the right mindset treats attention as a budget rather than treating the window as capacity. Capacity thinking asks whether there is still room; budget thinking asks whether this thousand tokens is worth spending. The latter is this course's way of thinking.
One judgment you can use immediately: if you cannot say which specific decision a piece of content will change, it should not be added. That criterion comes back repeatedly on day two when trimming the system prompt and day three when pruning tool results.
Three bills: money, latency, accuracy
A longer context makes you pay three bills, and most people count only the first.
The first is money. Input tokens are billed by volume, and the model having no memory means everything before gets resent every turn. In a 20-turn session, turn 1 might send 3,000 tokens while turn 20 sends 11,000, and the total input for the session is a running sum rather than the value of the last call. Today's lab has you compute that sum yourself.
Putting numbers on it hits harder. Say a session runs 20 turns, turn 1 sends 3,000 tokens, and each later turn adds some as history and tool results accumulate, reaching 11,000 by turn 20. What you pay for is not 11,000 but the sum of all 20 — roughly 140,000 tokens on a linear estimate. Plenty of people quote that 11,000 in a cost estimate and thereby understate the session by an order of magnitude. Day five works this bill out in full from today's real lab data, including how caching rewrites it.
The second is latency. The longer the input, the slower the first token. What a user feels is not "thirty percent more expensive" but "it spun for four seconds." And this bill gets amplified in an agent setting: one task calls the model many times over, each a little slower, and the accumulation is a distinctly perceptible "this thing is sluggish."
The third is accuracy, and it is the most easily overlooked. As the last section said, irrelevant content dilutes attention. What makes this bill frightening is that it does not raise an error: the model will not tell you it missed a constraint because the context was too cluttered; it will simply give a plausible-looking answer that violates the system prompt. By the time you notice, it is usually a production incident.
The line between prompt engineering and context engineering
Prompt engineering cares about writing one passage well: how the role is set, how the task is stated, how the format is constrained. Context engineering cares about how the whole suitcase is packed: that passage is one item of luggage, and beside it sit the tool definitions, the history, and the tool results, all of which change every turn.
The line is actually clear. Ask yourself one question: is my problem that a single call was not written clearly enough, or that things were not kept clean across many turns?
- The same question is answered wrongly once and answered correctly after a rephrasing — that is prompt engineering.
- The first five turns are fine and by turn twenty it starts violating the original constraints — that is context engineering.
- The data was clearly retrieved and the model says it does not have that information — also context engineering; the information is in the window, only drowned.
A harder criterion: prompt engineering deals with content, context engineering with budget allocation. If your change is "make this sentence more precise," it is the former; if it is "how much should this piece get, and when should it be thrown out," it is the latter.
This course assumes you can already write prompts. If that part is shaky, start with Prompt Engineering in 5 Days; the basics of writing an agent loop are in day 5 of the 30-day course, which covers the full round trip of a tool call — the origin of this course's tool definitions and tool results.
What each of the five days fixes
Of the four pieces, only three are actually actionable, and the five days are ordered by their payoff:
- Today (D1) is measurement: split the four pieces, work out the shares, and find where your bulk is. Without that table, everything later is a guess.
- D2 treats the system prompt: resent every turn, it has the highest compounding of the four. Altitude, layering, and progressive disclosure cut it in half.
- D3 treats tool definitions and tool results: usually the bulk. It gives criteria for pruning the tool list and a pruner that quantifies the before-and-after gap.
- D4 treats conversation history: a long-running task will fill the window. Compaction, external notes, and subagent isolation each fit different situations.
- D5 closes the loop: turn the first four days' techniques into a measurable cycle, work out the bill, watch two utilization metrics, and triage against four failure modes.
Mind the order: measure before changing, and treat what is resent before what merely grows. Many people start with compaction because it sounds the most sophisticated; but compaction treats the history, and the history is often the smallest of the four — you work at it for an afternoon and the bill does not budge.
Source Reading
Hands-On Lab
The first four criteria need no key, and only the fifth needs the real endpoint. Before you start, settle one thing: which piece do you think is largest? Write your guess down before running, because the moment you find it wrong is where this lab's real value is.
- Get the solution's
MOCK=1 pnpm startrunning, look at the share table for a session split four ways, and compare it against your guess. - Go back to the starter and complete exercise 1's splitting function, then run once to confirm the tool results row is no longer 0 and the four pieces sum to the total.
- Complete exercise 2's offline estimator, switching from counting characters to counting by character class, and watch the total drop from seven thousand-odd back to around three thousand.
- Complete exercise 3's differential counting and exercise 4's share calculation, then rerun with
TOOL_COUNT=8and watch which piece loses control of its share first. - Configure
ANTHROPIC_API_KEY, dropMOCK=1, run once, subtract the two totals, and record the direction and size of the estimator's error.
Interview Questions
Today's 3 questions are in the question bank below, weighted toward what makes up the context window, attention budget and context rot, and the boundary between context engineering and prompt engineering. Expand each one and read the analysis before the key points — practicing the derivation beats memorizing bullets. The high-frequency labels for the domestic and overseas markets are there so you can pick by target market.
Checklist and Tomorrow
- Name the four pieces that make up a model request's context, and work out each one's token share
- Explain attention budget and context rot in your own words, and name the three costs they bring
- Judge whether a problem can be solved with prompt engineering or must be escalated to context engineering
- Explain why tool results must be counted apart from conversation history rather than both as messages
- All 5 acceptance criteria of the lab pass, with the estimator's error against the real count recorded
- Answer at least 2 of the 3 interview questions without looking at the key points
Tomorrow (D2) we start work on the piece with the highest compounding: the system prompt. It is resent verbatim every turn, so changing it once saves money on the whole session. We will cover how to judge whether a system prompt is written too fine or too coarse, how to layer it, and what content should not be in it at all. Treat what is resent before what merely grows — that order is not casual, it is sorted by how much each change saves.
Interview questions
What actually goes into the context of a single agent request, and which part is most likely to blow up?一次 Agent 请求的上下文里都有什么?哪一块最容易失控,为什么?
Common in ChinaCommon overseasBasic#context-window#token-budgetHow to reason about it · think before answering
- This question separates people who have measured from people who have read. Naming the four parts is easy; describing how each one grows is where the signal is.
- Classify the four by growth pattern: system prompt and tool definitions are resent verbatim every turn at roughly constant size; conversation history grows linearly by tens of tokens per turn; tool results grow in steps, often thousands of tokens per call.
- Conclusion: tool results are the most likely to blow up, because a single increment is one to two orders of magnitude larger than the others and its size is decided by an external system you do not control. Tool definitions come second since they scale with a tool count that only ever goes up.
- Add the subtlety: tool results live inside user-role messages but they are data, not dialogue. Bucketing by message role folds them into history and ruins the breakdown, so bucket by content block type instead.
- Expect the follow-up: what numbers did you actually see? A concrete figure lands best, for example tool results at 72.9 percent of a customer-support session while most people had guessed history.
分析过程 · 先想清楚再作答
- 这题在考你有没有真的量过。能背出「系统提示、工具定义、历史、工具结果」四块的人很多,能说出各自增长方式的人很少,区分度全在后半句。
- 怎么拆:按「每一轮会怎么变」给四块归类。系统提示和工具定义是每轮原样重发、长度基本不变;对话历史是线性增长,每轮加几十个 token;工具结果是阶梯增长,一次调用就能加两千。
- 结论:最容易失控的是工具结果,因为它的单次增量比其它三块大一到两个数量级,而且完全由外部系统决定,你写代码的时候看不到它会有多大。工具定义排第二,它随工具数量线性增长,而工具是最容易被顺手加上去的东西。
- 补一个容易被忽略的点:工具结果虽然写在 user 角色的消息里,但它是数据不是对话。按消息角色统计会把它算进历史,那张表就废了——要按内容块的类型拆。
- 可预期的追问:那你实际量出来是多少?给一个具体数字最有说服力,比如一次电商客服会话里工具结果占 72.9%,而大多数人事先都猜的是对话历史。
Key points
- Four parts: system prompt, tool definitions, conversation history, tool results.
- Group them by growth: the first two are resent every turn at near-constant size, history grows linearly, tool results grow in steps.
- Tool results blow up first because a single call can add thousands of tokens and its size is set externally; tool definitions are second, scaling with tool count.
- Bucket by content block type, not by message role, or tool results get miscounted as history.
答题要点
- 四块:系统提示、工具定义、对话历史、工具结果。
- 按增长方式分:前两块每轮重发且基本恒定,历史线性增长,工具结果阶梯增长。
- 最容易失控的是工具结果,单次增量最大且由外部系统决定;其次是工具定义,随工具数量增长。
- 统计时要按内容块类型拆,不能按消息角色拆,否则工具结果会被算进对话历史。
Context windows keep growing. Why not just put everything potentially relevant into the prompt?窗口越来越大了,为什么不能把所有可能有用的资料都塞进去?
Common in ChinaCommon overseasIntermediate#context-rot#attention-budget#costHow to reason about it · think before answering
- The hinge is whether you treat the window as capacity or attention as a budget. Answering only with cost reads as inexperience, since cost is the easiest and least dangerous of the three bills.
- Split into capability and cost. On capability, name context rot: recall accuracy degrades as context grows, rooted in the n-squared pairwise relationships a transformer maintains over n tokens, plus the fact that long-range parameters are underrepresented in training.
- Stress that this is a gradient, not a cliff. No specific length breaks; every thousand irrelevant tokens shaves a little accuracy. That phrasing distinguishes people who read primary sources.
- On cost, give three bills: money (the model is stateless, so every turn resends everything and the total is cumulative, not the last call), latency (slower time to first token), and accuracy (irrelevant content dilutes attention). The third is worst because it never raises an error, it just returns a plausible answer that violates a stated constraint.
- Expect the follow-up: how do you decide whether a given chunk earns its place? Give an operational test: if you cannot name the specific decision it changes, it does not go in.
分析过程 · 先想清楚再作答
- 这题的题眼是「你知不知道窗口是容量、注意力是预算」。只回答「太贵了」的人会被判成没做过工程,因为成本是三笔账里最容易想到、也最不致命的一笔。
- 怎么拆:分成能力和代价两条线。能力这条线要点出上下文腐烂——随着上下文变长,模型准确回忆其中信息的能力会下降,根源在于 Transformer 里 n 个 token 有 n 平方级别的两两关系,注意力被摊薄;而且训练语料里长序列本来就少,处理长距离依赖的参数不够多。
- 关键是要强调它是一条缓坡不是一道悬崖:没有哪个长度会突然崩掉,每多塞一千个不相干的 token,正确率就低一点点。这个措辞能立刻区分读过一手材料的人。
- 代价这条线给三笔账:钱(模型无状态,每轮全量重发,总输入是累加值不是最后那次的值)、延迟(首字返回变慢)、正确率(无关内容稀释注意力)。第三笔最贵,因为它不会报错,只会给出看起来合理但违反了约束的回答。
- 可预期的追问:那你怎么判断某段内容该不该加?给一条可执行的判据——说不出它会改变模型哪一个具体决定,就不该加。
Key points
- The window is capacity; attention is the budget. Fitting is not the same as being used well.
- Context rot: recall degrades as context grows, as a gradient rather than a hard cliff.
- Three bills: money (stateless models resend everything each turn, so cost is cumulative), latency, and accuracy.
- Accuracy is the dangerous one because it fails silently with plausible answers that break stated constraints.
- Test: if you cannot name the specific decision a chunk changes, leave it out.
答题要点
- 窗口是容量,注意力是预算;容量够不代表模型用得好。
- 上下文腐烂:上下文越长,准确回忆的能力越差,是渐进的性能梯度而不是一道悬崖。
- 三笔账:钱(每轮全量重发,成本是累加值)、延迟、正确率。
- 正确率那一笔最危险,因为它不报错,只会给出看似合理却违反约束的回答。
- 判据:说不出这段内容会改变哪一个具体决定,就不该放进去。
Where is the line between prompt engineering and context engineering, and when do you switch?提示词工程和上下文工程的分界在哪?什么时候该从前者切换到后者?
Common in ChinaCommon overseasIntermediate#prompt-engineering#context-engineering#scopingHow to reason about it · think before answering
- The trap is answering that context engineering is just prompt engineering leveled up. Interviewers want a rule they can apply to classify a live problem.
- Start with the object of each. Prompt engineering shapes content: how to phrase one instruction precisely. Context engineering allocates budget: how much of the window each part gets and when to drop things. One optimizes inside a single call, the other manages state across turns.
- Then give a symptom-based test. Wrong once but right after rephrasing means a prompt problem. Fine for five turns and violating the original constraints by turn twenty means a context problem. Retrieving the data and then claiming it does not exist is also a context problem: the information is in the window but buried.
- Conclusion: you switch not when the prompt is good enough, but when the cause moves from single-turn phrasing to multi-turn accumulation. Adding tools, adding retrieval, or running long sessions each trigger the switch.
- Expect the follow-up: does context engineering subsume prompt engineering? The system prompt is one of the four parts, so prompt engineering is a subproblem, but it cannot touch tool definitions, history, or tool results.
分析过程 · 先想清楚再作答
- 这题最容易答成「上下文工程是提示词工程的升级版」,那是营销话术。面试官想听的是一条能当场用来分类问题的判据。
- 怎么拆:先给对象的差别。提示词工程处理的是内容——一段话怎么写才准确;上下文工程处理的是预算分配——整只箱子里各块占多少、什么时候该扔。前者是单次调用内的优化,后者是跨多轮的状态管理。
- 再给一条现场可用的分类法,用症状反推:同一个问题问一次答错、换个说法就对,是提示词问题;前五轮正常、第二十轮开始违反最初约束,是上下文问题;明明查到了数据模型却说没有,也是上下文问题——信息在窗口里,只是被淹没了。
- 结论:切换的时机不是「提示词写得够好了」,而是「问题的成因从单次表达变成了多轮累积」。加了工具、加了检索、开始多轮长跑,这三件事任何一件发生,都意味着该切换了。
- 可预期的追问:那上下文工程包含提示词工程吗?答:系统提示是上下文四块里的一块,所以提示词工程是上下文工程的一个子问题,但它解决不了另外三块——工具定义、历史和工具结果都不是靠把话写好能管住的。
Key points
- Prompt engineering shapes content; context engineering allocates budget across turns.
- Classify by symptom: fixed by rephrasing is a prompt issue; drifting after many turns is a context issue; retrieved but reported missing is also a context issue.
- Switch when the cause moves from single-turn phrasing to multi-turn accumulation, typically after adding tools, retrieval, or long-running sessions.
- The system prompt is one of four parts, so good phrasing alone cannot control the other three.
答题要点
- 提示词工程处理内容,上下文工程处理预算分配;一个在单次调用内,一个跨多轮。
- 症状分类法:换个说法就对是提示词问题;跑久了开始违反约束是上下文问题;查到了却说没有也是上下文问题。
- 切换时机是问题成因从单次表达变成多轮累积,通常发生在加工具、加检索、开始长跑之后。
- 系统提示只是上下文四块之一,所以写好提示词管不住另外三块。