Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 15 min · revision 2

Context Engineering: What Goes In and How Much

List everything that enters a model request, from tool definitions to the output reserve, and split a token budget across instructions, history, retrieved content and output. Learn what max output tokens does and does not do, and how to keep conversation state in your own code.

Contentsand lesson path

What you will learn

  • Allocate a context budget across instructions, history, retrieved content and output, and enforce it in code.

01. Why it matters

A model keeps nothing between calls. Everything it knows about the current request (who it is talking to, what was said before, which documents apply, which tools exist) arrives in that one request, as tokens in its context window. The window is a hard limit on input and output together. Inside it, every token you add costs money and time, and too much material makes answers worse: accuracy and recall degrade as the context fills, an effect Anthropic's documentation calls context rot.

Context engineering is the work of deciding what goes into each request, in what order, and how much of each kind. Prompt wording is part of it, but most of the tokens in a real application are not the prompt you wrote: they are history, documents and tool definitions. This lesson gives you a way to account for all of them, and the next lab turns it into code.

02. Everything that enters the context

For a chat feature with tools and retrieval, a request is assembled from six kinds of content:

  1. System instructions: the role, rules and output format. Stable from call to call.
  2. Tool definitions: each tool's name, description and JSON schema. They are input tokens on every call, whether or not the model uses a tool.
  3. Conversation history: earlier user and assistant turns, including tool calls and their results, which are often the largest items of all.
  4. Retrieved content: documents, search results or database rows chosen for this question.
  5. The current user message, with any images or PDFs, which are converted to tokens too.
  6. The output: the answer, plus any thinking tokens, generated into the same window.

Measured for one request of a support assistant, the parts might look like this:

Illustrative: one support-assistant request, by part
part                           tokens   share
system instructions               900      5%
tool definitions (6 tools)      2,400     15%
history (14 turns)              6,800     41%
retrieved passages (5)          4,200     26%
current user message               90      1%
output reserve (max tokens)     2,000     12%
total                          16,390    100%

The user's actual question is less than 1% of the request. History and retrieved passages are the parts that grow, and they are where your decisions have the most effect. Tool definitions are a fixed tax that is easy to forget until you have twenty tools.

03. Allocate a budget

Start by choosing a total budget per request. It must fit the model's window, but it is usually far smaller: many current models accept hundreds of thousands of tokens, yet a support answer rarely needs more than a few thousand, and every extra token adds cost, latency and noise. Then split the total into fixed and flexible parts:

  • Fixed parts are never trimmed to make room: the system instructions and tool definitions, the current user message (with a cap, so one huge paste cannot take everything) and the output reserve. If they do not fit, the request is wrong and your code should say so, for example by asking the user to shorten the message.
  • Flexible parts get a cap and a ranking: retrieved passages up to a cap, best first, and history in whatever room is left, newest first.

Writing the allocation down as data makes the arithmetic checkable:

Python · budget.py
from dataclasses import dataclass


@dataclass(frozen=True)
class ContextBudget:
    total: int  # what you allow per request, often far below the model's window
    instructions: int  # system prompt and tool definitions (fixed)
    current_turn: int  # the newest user message (fixed, but capped)
    output_reserve: int  # becomes max_tokens; room for the answer
    retrieved: int  # cap for retrieved passages (flexible)

    @property
    def history(self) -> int:
        """Whatever is left goes to earlier turns of the conversation."""
        return self.total - (
            self.instructions + self.current_turn + self.output_reserve + self.retrieved
        )

    def check(self, context_window: int) -> None:
        if self.total > context_window:
            raise ValueError(f'budget {self.total} exceeds the window {context_window}')
        if self.history < 0:
            raise ValueError(f'slices overrun the total by {-self.history} tokens')


budget = ContextBudget(
    total=16_000,
    instructions=1_500,
    current_turn=1_000,
    output_reserve=2_000,
    retrieved=6_000,
)
budget.check(context_window=200_000)
print('history gets', budget.history, 'tokens')
Expected output (python budget.py)
history gets 5500 tokens

Every number in the allocation should come from a measurement or a decision you can explain. Measure the instructions and tool definitions with a tokenizer. Set the output reserve from the longest answer you will accept. Set the passage cap from evaluation: how many passages actually improve answers. Which flexible part wins when space is short depends on the feature. A document question-answering bot needs passages more than old small talk; a tutoring chat needs its history more than a fifth search result.

04. The output reserve and max output tokens

The output reserve becomes the max output tokens parameter of the request (max_tokens in Anthropic's API, for example). It is a ceiling, not a booking:

  • The model stops when it finishes or when it reaches the ceiling, whichever comes first. You pay for the tokens it actually generated, not for the ceiling.
  • If it reaches the ceiling, the answer is cut off mid-thought and the stop reason says so (max_tokens in Anthropic's API, length in OpenAI's Chat Completions). Code must check this before using the answer.
  • On reasoning models, thinking tokens are generated into the same allowance, so a reserve sized for the visible answer alone can be used up before the answer starts.

Input and output share the window, but APIs disagree about what happens when input plus the ceiling exceeds it. Some reject the request outright. Recent Claude models accept it and stop with the stop reason model_context_window_exceeded if generation actually runs out of room. Do not depend on either behaviour: enforce the budget in your own code, before the call.

05. Conversation state lives in your code

A plain chat API is stateless: the model "remembers" earlier turns only because your code sends them again with every request, so a conversation costs more on every turn until something limits it. Some APIs can keep the conversation on the server for you, but the stored turns still go back into the context window and count on every call. Four techniques keep history inside its share of the budget, and real applications combine them:

  • A sliding window: keep the newest turns that fit and drop the rest. Simple and predictable, but the user's original goal is often in the first turn.
  • A running summary: replace the dropped turns with a short summary written by a model, and keep the recent turns word for word. It keeps the gist at the cost of an extra call and the risk that the summary gets a detail wrong.
  • Pinned facts: keep a small, structured block of facts that must survive, such as the order number, the user's name or decisions already made, and update it as the conversation goes on.
  • Clearing old tool results: replace large, stale tool outputs with a one-line note once they have been used.

Whatever you drop, drop whole units. A user message travels with the assistant reply that follows it, and a tool call with its result; an answer without its question, or a tool result without its call, confuses the model and is rejected by some APIs. Some providers now offer server-side summarising (compaction) or clearing of old tool results. They are useful, but you still need to know what they keep, so the same design questions apply.

06. Check your understanding

Practice check · 3 questions

Budgets and requests

Three questions about what a request contains and what it costs.

Q1. You set max output tokens to 4,000 on a model with no thinking step, and the answer comes back 250 tokens long. How many output tokens are you billed for?
Q2. A support bot sends a system prompt, 12 tool definitions, 5 retrieved help articles and the chat so far. Which of these take up room in the context window?
Q3. On a reasoning model you set max output tokens to 600, because the answers you want are about 450 tokens long. Many responses stop at that ceiling with little or no visible answer. What is the most likely cause?
Practice only: not graded, not saved, not evidence.

07. Apply it

Write the budget for this skill's practice project before you write the assembler. In a file budget.py:

  1. Pick a total per request and a target model, and check the total against that model's documented context window.
  2. Measure your real system prompt (and tool definitions, if any) with the counting code from the previous lesson, and set caps for the current message and for retrieved passages.
  3. Choose an output reserve from the longest answer you will accept, with headroom for thinking tokens if you use a reasoning model.
  4. Let history take the rest, and write in comments the order in which the flexible parts are cut and what happens when the fixed parts do not fit.

Add three sentences that justify the numbers. The next lab enforces a budget like this one in code.

08. Review prompt

Without looking back, list the six kinds of content that can enter a request and mark each one as fixed or flexible. Explain in two sentences what max output tokens does, what you are billed for, and what the stop reason tells you. Then describe four ways to keep a long conversation within its share of the budget, with one drawback of each.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check