Sub topic 1
What the Context Window Is and Why Context Engineering Matters
Prerequisites
This chapter assumes you have:
- Called a large language model (LLM) through a chat interface or an API.
- Seen the terms prompt, system prompt, and token, and have a rough idea of what each means.
- Enough Python to read short functions and dictionaries.
You do not need any library or API key. The code below uses a stand-in function for the model.
What the context window is
The context window is the total amount of text a model can take into account when it produces a response. Everything the model uses on a given call must fit inside it: instructions, earlier messages, documents, tool definitions, and the reply it is generating.
The window is measured in tokens, the chunks of text a model reads and writes. A token is often a short word or part of a word. The next chapter covers tokens in detail. For now, treat the window as a fixed-size container with a hard upper limit set by the model.
Two facts define how you work with it:
- The model has no memory between calls. An LLM call is a function from input text to output text. Nothing carries over unless you put it in the input.
- The limit covers input and output together. If a model has a 200,000-token window and you send 190,000 tokens, at most 10,000 remain for the reply. Some providers also cap output separately, below what the window would allow.
The model only knows what is in the window
Chat products feel like conversations with a persistent partner. Underneath, the application resends the conversation on every turn. The model sees one long piece of text and continues it.
The following sketch shows the effect. fake_model stands in for a real API. Like a real model, it can only use the messages it receives.
def fake_model(messages):
# Stand-in for a real API call. It can only use what is in `messages`.
text = " ".join(m["content"] for m in messages)
if "My name is " in text and "What is my name?" in messages[-1]["content"]:
name = text.split("My name is ")[1].split(".")[0]
return "Your name is " + name + "."
return "I don't know."
history = []
def ask(question, send_history):
user_message = {"role": "user", "content": question}
messages = (history if send_history else []) + [user_message]
reply = fake_model(messages)
history.append(user_message)
history.append({"role": "assistant", "content": reply})
return reply
print(ask("My name is Ada.", send_history=True))
print(ask("What is my name?", send_history=False))
print(ask("What is my name?", send_history=True))The output is:
I don't know.
I don't know.
Your name is Ada.The second call fails because the application did not send the earlier message. The third succeeds because the history was included. The application records the exchange in both cases, so whether the model "remembers" depends only on what the application chooses to send.
Context engineering is the work of making that choice well, on every call.
Context engineering versus prompt engineering
Prompt engineering is about wording: how to phrase an instruction, which examples to show, what format to request. It treats the prompt as a mostly fixed block of text that you refine.
Context engineering is about the whole input as a changing system. In an application with tools, retrieval, and multi-turn sessions, the input is assembled fresh for each call from many sources. The wording of the system prompt is one part. The rest is a set of decisions about what to include, how much, in what order, and when to remove it.
| Aspect | Prompt engineering | Context engineering |
|---|---|---|
| Main question | How should I phrase this instruction? | What should the model see on this call? |
| Unit of work | A prompt template | The assembled input for each call |
| Changes over time | Rarely, when you edit the prompt | Every call, as history, documents, and tool results change |
| Typical tools | Rewording, examples, formatting rules | Retrieval, trimming, summarizing, caching, subagents |
| Typical failure | Ambiguous or underspecified instructions | Missing, stale, excessive, or conflicting information |
The two overlap. A well-worded instruction is still part of the context, and good context engineering includes good wording. The difference is scope. A perfectly phrased instruction fails if the document it refers to was never loaded, or if it is buried under 80,000 tokens of unrelated tool output.
Why it matters
A larger window does not remove the need for this work. There are four reasons.
Quality depends on what is present and what is absent
The model cannot use information it was not given. If the answer depends on a refund policy that is not in the context, the model will either say it does not know or produce a plausible guess. The reverse also holds. Irrelevant, outdated, or contradictory content in the window can pull the answer off course. Later chapters name these failures: distraction, poisoning, confusion, and clash.
Capacity is finite, and agents fill it quickly
A single question with one document fits easily. A long-running agent does not. Each step can add a tool result, a file listing, or a log. Over dozens of steps, the context grows until it hits the limit or until the useful material is a small fraction of it. Something has to be dropped, shortened, or moved elsewhere, and that choice is engineering.
Cost and latency scale with input size
Most providers charge per input token and per output token. Because the full context is resent on every call, a bloated context is paid for again each time. Long inputs also take longer to process. An agent that makes 40 calls with a 100,000-token context sends 4,000,000 input tokens in total, even if each call adds only a little new information.
Behavior is only reproducible if the input is
When an application gives a bad answer, the first debugging step is to look at the exact context of that call. If your application builds contexts in an ad hoc way, you cannot reproduce or fix the problem. Treating context assembly as explicit code makes it inspectable and testable.
How a call is built
The diagram shows the flow in a typical application. Several sources feed a step that assembles the context. The model sees only the result.
The arrow from the response back to the history is what makes the problem recurring. Every output becomes a candidate input for the next call.
Edge cases and common misconceptions
- "The model remembers me across sessions." Unless the product stores something and injects it into the next context, it does not. Features called "memory" are context engineering: stored notes are loaded back into the window.
- "Anything within the window limit is handled equally well." The limit is a hard cap on what is accepted. It does not guarantee the model uses every part with equal reliability. Long contexts often degrade in practice, which is why placement and selection get their own chapters.
- "If I fill the window, nothing is lost." Depending on the API, an input over the limit either returns an error or is truncated by the application. Silent truncation is the worse case, because the model may lose instructions without any signal. Check how your stack behaves.
- "Output tokens are free once input fits." Output counts toward the window and toward cost. A context that leaves too little room for the reply can cut the response off midway.
- "More context is safer." Extra material has a cost in money, latency, and sometimes accuracy. The goal is the smallest context that still contains what the model needs for the current step.
What you will do in this tutorial
The remaining chapters build a working toolkit on top of this model:
- Measure the window in tokens and set a budget.
- Break a context into its parts and cost each one.
- Select relevant content, order it, and recognize the ways it goes wrong.
- Manage long sessions with retrieval, trimming, compaction, external notes, and subagents.
- Structure prompts for caching, and evaluate each change against a fixed test set before adopting it.
A useful habit to start now: when a model answers badly, ask "What was in the context?" before asking "What should I rephrase?"
Exercise
An agent makes 25 calls in a session. The fixed part of its context (system prompt and tool definitions) is 6,000 tokens. Conversation history starts at 0 and grows by 2,000 tokens on every call, and the history added after call N is included in call N+1. Each call's reply is 500 tokens, which is already counted in the 2,000-token growth. How many input tokens does call 25 contain, and why does this matter even if call 25 is within the window limit?
Show answer
Call 25 includes the history from the 24 previous calls: 24 x 2,000 = 48,000 tokens, plus the 6,000 fixed tokens, so 54,000 input tokens (ignoring the new user message). It matters because the whole context is resent on every call. Cost and latency grow with each call, and the fixed 6,000 tokens are paid for 25 times. Even inside the window limit, a growing history raises cost and can lower answer quality, so you need a plan for trimming or compacting it.