The Context Window as a Finite Attention Budget
Explore how to measure an AI agent's context window, fixed token overhead, remaining capacity, and evidence growth with LiteLLM. Compare local token estimates with provider billing, calculate quadratic attention costs, and understand why fitting within a window does not guarantee reliable reasoning.
We'll cover the following...
In the previous lesson, we saw that a model’s context has eight parts. All eight share one limited space: the context window. In this lesson, we’ll measure that space for our on-call assistant. We’ll see how many tokens the window can hold, how much of it is used before any evidence arrives, and why the cost of reading a context grows much faster than its length.
Is the window size the limit?
Every model has a published context window size, such as about 1 million tokens for Gemini 2.5 Flash. A token is a small piece of text, often a word or part of a word. The window size tells us the most tokens the model accepts in one request. If we send more, the request is rejected.
The window size doesn’t tell us how costly it is to process a context that fits. A request that uses only a small part of the window is accepted, yet its cost still grows as it gets longer. So whether a context fits and how costly it is to process are separate questions. This lesson answers the second one, first with arithmetic and then with code.
Why does attention cost grow quadratically?
Models like Gemini and GPT are transformers. When a transformer reads a context, each token looks at every other token to work out how they relate. This step is called attention. So for n tokens, the model scores roughly
1,000 tokens: About 1,000 × 1,000 = 1,000,000 pairwise relationships.
10,000 tokens: About 10,000 × 10,000 = 100,000,000 pairwise relationships.
100,000 tokens: About 100,000 × 100,000 = 10,000,000,000 pairwise relationships.
Going from 10,000 to 100,000 tokens makes the context 10 times longer, but it creates about 100 times more pairs to score. So a longer context isn’t just a little more expensive. Its cost grows much faster than its length.
Does length also hurt reasoning?
Yes. A long context costs more, and it can also lower the quality of the answer. Two reasons stand out:
Short-sequence training: Models are trained mostly on shorter texts. A very long input puts the model in a range it has seen less often, so its reasoning can get worse.
Read-heavy agent loops: An agent like our on-call assistant reads far more than it writes. It reads runbooks, deploy logs, and the incident thread, and then writes a short answer. So almost all of the cost goes into reading.
Put together, most of the quadratic cost is spent on tokens the model has to read, at lengths it handles less well, before it writes a single word of the answer.
How big is the fixed overhead?
Some tokens are sent on every call, no matter what the engineer asks. For the on-call assistant, these are the system prompt and the search tool’s definition. Their cost is the fixed overhead: the minimum every call pays before any evidence arrives. Let’s measure it with code.
Note: Guessing tokens from word counts doesn’t work well, especially for text with punctuation, JSON braces, and field names. It’s always better to count with a tokenizer.
Step 1: Define the fixed configuration
We start with the parts every call carries: the model name, the system prompt, and the search tool’s schema. We write the tool in the OpenAI function format, and LiteLLM converts it for whichever provider we use.
In the code above:
Line 1: We import
osto read environment variables.Line 3: We read the model name from
LLM_MODEL, falling back togemini/gemini-2.5-flash. Changing this one variable switches every later step to another provider.Lines 5–8: We define
SYSTEM_PROMPT, which tells the model to answer only from the retrieved runbooks and postmortems and to cite every step as[doc_id].Lines 10–24: We define
SEARCH_TOOL, the one tool the assistant exposes. Itsparametersblock is a JSON schema with a requiredquerystring andtop_kinteger.Lines 26–28: We print the model and tool name. The
if __name__ == "__main__":guard stops these prints when later steps import this file.
Step 2: Count the fixed overhead
Next, we count these fixed tokens. LiteLLM’s token_counter() counts tokens on our own machine. It uses the model’s own tokenizer when one is available and a close approximation when it isn’t.
Here’s what the code does:
Lines 1–2: We import
litellmand the fixed configuration from Step 1.Lines 6–9: We build a probe conversation: the real system prompt plus a one-character user message, so nearly every counted token comes from the fixed parts.
Line 10: We count the probe without tools to get the system prompt’s cost alone.
Line 11: We count it again with
tools=[SEARCH_TOOL], because a tool schema is serialized into the prompt and billed like any other input.Lines 15–19: We print both counts and their difference, which is the tool schema’s share.
With the default Gemini model, the output looks like this. Other models may differ by a few tokens.
System prompt alone: 68 tokensPrompt + tool schema: 136 tokensTool schema adds: 68 tokens
A single small tool schema costs as much as the whole system prompt. This matters as agents grow: an agent with 30 tools can spend thousands of tokens on tool schemas before it reads any evidence. We’ll deal with this problem in Chapter 3.
How much room is left?
If we subtract the fixed overhead from the window size, we get the remaining capacity. This is the space left for everything that changes from call to call: retrieved notes, conversation history, and scratchpad entries.
Step 3: Compute the remaining capacity
We read the window size from LiteLLM’s built-in list of models, so we don’t have to copy it by hand.
Let’s walk through the code:
Lines 6–8: We define
context_window(), which looks the model up withlitellm.get_model_info()and returns itsmax_input_tokens, falling back tomax_tokensfor models that only list one limit.Lines 12–14: We read the window, reuse
count_fixed_overhead()from Step 2, and subtract to get the remaining capacity.Lines 15–17: We print all three numbers with thousands separators.
When we run this step, it prints the window size and what’s left of it:
Context window: 1,048,576 tokensFixed overhead: 136 tokensRemaining capacity: 1,048,440 tokens
With about a million tokens free, the window looks almost unlimited. The next steps show why that’s misleading.
Step 4: Add a note store
To profile a real call, the assistant needs documents to search. The file note_store.py holds eight short runbook and postmortem notes, plus a simple keyword search. We’ll reuse this file throughout the course.
In this step’s code:
Lines 3–12: We define
NOTE_STORE, a list of eight notes, each with adoc_idandtext. Noticenote-4: it’s the 2024 version of the checkout runbook innote-1, and it still says to restart the Redis cache first.Lines 15–16: We define
tokenize(), which lowercases text and returns its set of words.Lines 19–23: We define
search_documents(). It scores each note by how many words it shares with the query, sorts by score, and returns the toptop_knotes that share at least one word. Ties keep their store order.Lines 26–29: We run the latency question and print each hit.
Running the file prints the top five hits for the latency question:
note-1 | Checkout latency runbook, updated May 2026. If checkout latency spikes...note-2 | Postmortem, March 2026. Checkout latency spiked after a deploy added a...note-4 | Checkout latency runbook, 2024 version. If checkout latency spikes aft...note-5 | Search latency runbook. If search latency spikes, scale out the search...note-3 | Checkout feature flags are listed on the flags dashboard. Turning a fl...
The stale note-4 ranks third, just below the current runbook it copies. We’ll deal with it in the next lesson.
Step 5: Profile one complete call
Now let’s build a complete call, with the system prompt, the retrieved notes, and the question, and count everything the assistant would send.
Here’s how it works:
Line 6: We store the running question in
QUERY.Lines 9–15: We define
build_messages(), which retrieves the top notes, formats each as[doc_id] text, and places them before the question in the user message.Line 20: We count the whole call, tool schema included.
Lines 21–23: We print the total, whether it fits under the window, and the pairwise relationship count,
total ** 2.
Here’s what the profiler reports for this call:
Total tokens for this call: 351Fits under the window: TruePairwise relationships: 123,201
Step 6: Grow the evidence
A 351-token call is small. In a real incident, though, the context keeps growing as the assistant reads more documents, tool output, and messages. To see what that does to the cost, we’ll repeat the evidence 10 times and then 100 times.
In the code above:
Lines 5–6: We build the normal call and pull out its user message, which holds the evidence.
Lines 9–11: We repeat that evidence 1, 10, and 100 times and count the tokens for each size.
Lines 12–13: We square the count and compute how many times more pairs this size has than the previous one.
Line 14: We print one aligned row per size.
The output shows how the token count and the number of pairs grow:
1 x evidence -> 283 tokens -> 80,089 pairs10 x evidence -> 2,239 tokens -> 5,013,121 pairs (63x more pairs)100 x evidence -> 21,766 tokens -> 473,758,756 pairs (95x more pairs)
Even at 100x, the call uses only about 2% of the million-token window, yet the number of pairs grew more than 5,900 times. The first jump is a bit under 100x because the system prompt stays the same size, which softens the growth at small sizes.
Try your own numbers in the calculator below. Increase the retrieved tokens and notice how little the remaining capacity changes while the number of pairs shoots up.
What does the provider actually bill?
So far, every count came from token_counter(), which estimates tokens on our machine. The provider also counts the tokens it receives and returns that count in response.usage. That’s the number we’re billed for. It can differ a little from our estimate, because each provider wraps messages and tools in its own format.
Step 7: Compare with provider billing
This step calls a real model, so it needs an API key for your provider.
Here’s what changes in this step:
Lines 5–6: We build the same call as Step 5 and estimate its tokens locally.
Lines 8–14: We send it with
litellm.completion(). Settingtool_choice="none"keeps the schema in the request, so it’s still billed, but tells the model to answer from the notes.Line 15: We read
response.usage, which LiteLLM normalizes to OpenAI’s field names for every provider.Lines 17–20: We print the estimate, the billed input tokens, the output tokens, and the input-to-output ratio.
Line 21: We print the answer, with a fallback in case the model returns no text.
The billed input should land within a few percent of our estimate. The input-to-output ratio should be well above 1:1, since this call reads far more than it writes. With a thinking model such as Gemini 2.5 Flash, the output count also includes the model’s hidden reasoning tokens, which are billed even though we never see them.
Is fitting under the window enough?
This is an easy mistake to make. We send every retrieved document, see that the total fits in the window, and assume the context is fine because nothing was cut. Fitting only tells us the request was accepted. It tells us nothing about the two costs we measured in this lesson:
Attention cost: The number of pairs grows with the square of the length, as Step 6 showed.
Reasoning quality: Long inputs push the model into lengths it handles less well.
So a context can fit in the window and still be expensive and unreliable. Our profiler’s numbers showed exactly that.
The next lesson fixes this with four moves:
Write: Keep information outside the window and read it back only when needed.
Select: Choose which documents from a larger store enter the window.
Compress: Shrink what was selected.
Isolate: Run part of the work in a separate call.
What’s next?
In this lesson, we measured the fixed overhead of a call with token_counter(), worked out how much room is left in the window, compared our estimate with the provider’s bill, and saw why fitting in the window doesn’t make a context healthy. In the next lesson, we’ll use these numbers to decide how to handle each part of the on-call assistant’s context with Write, Select, Compress, and Isolate.