Sub topic 2
Tokens and budgeting the window
Prerequisites
This chapter assumes you have called a language model through a chat or API interface and know what a system prompt is. You should also be able to read short Python functions. The previous chapter introduced the context window as the fixed amount of text a model can consider on one call. This chapter turns that limit into numbers you can plan with.
What a token is
A token is the unit of text a model reads and writes. A tokenizer splits text into pieces from a fixed vocabulary. A piece can be a whole word, part of a word, a single character, or punctuation. The model never sees raw characters. It sees a sequence of integer IDs, one per token.
Three consequences follow:
- The context window is measured in tokens, not characters or words.
- Providers bill by tokens, and latency grows with token count.
- Different models use different tokenizers. The same text can have different counts on different models.
A common rule of thumb for English prose is about 4 characters per token, or roughly three quarters of a word. This is only an average. Other kinds of content usually cost more per character:
| Content | Typical behavior |
|---|---|
| Plain English prose | Close to the 4 characters per token average |
| Source code | Often more tokens per character, because of symbols and indentation |
| JSON and logs | Often expensive, because of quotes, braces, repeated keys, and IDs |
| Long numbers, hashes, UUIDs | Split into many short pieces |
| Non-English text | Often more tokens per word, depending on the language and tokenizer |
The exact ratios depend on the tokenizer, so measure your own data. If your provider offers a token-counting endpoint or a tokenizer library, use it to calibrate your estimates against real counts.
The window is shared by input and output
The context window is a single budget. Everything the model reads and everything it writes must fit inside it together. Many providers also set a separate cap on output length, so you have two limits to respect.
The input side contains the system prompt, tool definitions, retrieved documents, conversation history, and the user's question. The output side contains the model's reply. Some models also produce reasoning tokens before the visible answer, and these usually count against the output budget too.
If you fill the window with input, the model has no room to answer. Depending on the provider you get a hard error, or a reply cut off in mid-sentence. So the first step in budgeting is to reserve output space before you allocate anything else.
Fixed costs and variable costs
It helps to sort the parts of a context by how predictable their size is.
- Fixed costs are the same on every call. The system prompt and tool definitions belong here. You can measure them once and treat them as constants.
- Bounded variable costs change per call but you control the cap. Retrieved documents are an example, because you choose how many to include and how long each can be.
- Unbounded variable costs grow without a cap unless you act. Conversation history and tool results are the usual culprits. A single tool call that returns a large file or a long search result can consume a large share of the window.
Budgeting means turning the unbounded costs into bounded ones. You do this by setting a cap for each category and deciding what to drop when the cap is reached.
A budget as arithmetic
A workable budget is a subtraction followed by a split:
remaining = window - output_reserve - system - tools - question
documents get: remaining * doc_share
history gets: whatever remains after documents are chosenGiving history "whatever remains" is deliberate. If the selected documents are short, history can use the leftover space. If you instead gave each a fixed share, unused space in one category would be wasted.
The following code implements this. It estimates tokens, ranks documents by relevance, and keeps the newest history that still fits.
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
# Use your model provider's tokenizer for exact counts.
return max(1, len(text) // 4)
def pick_within_budget(items, budget):
chosen, used = [], 0
for item in items:
cost = estimate_tokens(item)
if used + cost > budget:
break
chosen.append(item)
used += cost
return chosen, used
def build_context(system, question, history, docs, window, output_reserve, doc_share=0.5):
# docs is a list of (relevance_score, text) pairs; history is oldest-first.
remaining = window - output_reserve - estimate_tokens(system) - estimate_tokens(question)
if remaining <= 0:
raise ValueError("system prompt and question leave no room")
ranked_docs = [text for _, text in sorted(docs, key=lambda d: d[0], reverse=True)]
picked_docs, used_docs = pick_within_budget(ranked_docs, int(remaining * doc_share))
picked_history, _ = pick_within_budget(list(reversed(history)), remaining - used_docs)
picked_history.reverse()
return {
"system": system,
"documents": picked_docs,
"history": picked_history,
"question": question,
}Three details are worth noticing:
build_contextraises an error when the fixed parts alone exceed the window. Failing early is better than sending a request that the provider will reject.- History is reversed before selection so that the newest messages are considered first. It is reversed back afterward so the model sees it in chronological order.
pick_within_budgetstops at the first item that does not fit.
Worked example
Now run the function with small numbers so you can check the arithmetic by hand. The placeholder strings are repeated characters, which makes each token cost exact under the 4-characters-per-token estimate.
system = "You are a support assistant." # 28 chars -> 7 tokens
question = "How do I reset my password?" # 27 chars -> 6 tokens
docs = [
(0.9, "A" * 160), # 40 tokens, most relevant
(0.8, "B" * 160), # 40 tokens
(0.7, "C" * 40), # 10 tokens
]
history = ["1" * 120, "2" * 120, "3" * 120, "4" * 120] # 30 tokens each
ctx = build_context(system, question, history, docs, window=200, output_reserve=50)
print(len(ctx["documents"]), len(ctx["history"]))
print([h[0] for h in ctx["history"]])The system prompt is 28 characters, so it costs 7 tokens. The arithmetic goes like this:
remaining = 200 - 50 - 7 - 6 = 137.- The document budget is
int(137 * 0.5) = 68. Document A costs 40 and fits. Document B would bring the total to 80, so selection stops. - History gets
137 - 40 = 97. Messages 4, 3, and 2 cost 90 together and fit. Message 1 would bring the total to 120, so it is dropped.
The program prints:
1 3
['2', '3', '4']One document and the three newest history messages survive. The total input is 7 + 6 + 40 + 90 = 143 tokens, and with the 50-token output reserve the request uses 193 of 200 tokens.
Edge cases and gotchas
Stopping at the first miss. In the example, document C costs only 10 tokens. After A is chosen, 28 tokens of the document budget remain, so C would fit. The break in pick_within_budget stops before it reaches C. This is the right behavior for history, where skipping a message leaves a gap in the conversation. For ranked documents you might prefer continue, which skips an oversized item and keeps filling the budget with smaller ones. Choose based on whether order and contiguity matter.
The estimate is not the truth. If the estimate undercounts, a request that passed your check can still fail at the provider. Leave a safety margin, commonly 5 to 10 percent of the window, or count with the real tokenizer.
Per-message overhead. Chat APIs add formatting tokens around each message, such as role markers. Tool definitions are serialized into the prompt in a provider-specific format. Your own sum of raw text lengths will undercount these.
A bigger window is not a free pass. A larger window raises the ceiling, but you still pay for every token in cost and latency. Models can also use long contexts less reliably, which the later chapters on context failures and ordering cover. A budget is a design choice and not only a defense against the limit.
Reserve for the real output size. If you set the output reserve too small, replies get truncated. If you set it far too large, you waste input space. Base the reserve on the longest reply you expect and adjust it from logs.
Cap tool results at the source. Truncate or summarize large tool output before it enters the context. A cap applied at the point of entry is easier to reason about than trimming after the fact.
Exercise
A model has an 8,000-token window. You reserve 1,000 tokens for output. The system prompt costs 600 tokens, the tool definitions cost 1,400, and the user's question costs 100. You use doc_share = 0.5, and the selected documents turn out to use only 1,500 tokens of their allowance. How many tokens are left for history, and why is that more than the document allowance would suggest?
Show answer
remaining = 8,000 - 1,000 - 600 - 1,400 - 100 = 4,900 tokens. The document allowance is 4,900 * 0.5 = 2,450, but the documents used only 1,500. History gets the rest of the remaining budget, 4,900 - 1,500 = 3,400 tokens. History receives more than the other half (2,450) because unused document space flows to it instead of being wasted.
Exercise
Why does buildcontext reverse the history before calling pickwithin_budget, and then reverse the chosen messages again?
Show answer
The first reversal puts the newest messages first, so the budget is spent on the most recent turns and the oldest are the ones dropped. The second reversal restores chronological order, so the model reads the kept messages in the order they happened.