Sub topic 4
Setting an input budget and reserving room for the reply
This chapter assumes you can write basic Python and know the system, user, and assistant message roles. It also assumes you have a general idea of what tokens are. The previous chapters covered why you resend history and how to count tokens. Here you decide how many of those tokens the input may use.
The window holds input and output
A model's context window is the maximum number of tokens it can handle in one request. The input and the reply both count against it. If your history fills the whole window, the model has no space left to answer. Depending on the provider, the reply is cut off mid-sentence or the request is rejected.
So you never truncate to the window size. You truncate to an input budget, which is the window minus what you must hold back.
The formula
input_budget = context_window - max_output_tokens - safety_margin- context_window is the model's documented limit.
- maxoutputtokens is the reply cap you set on the request. Reserve the cap, not the average reply, because the model may use all of it.
- safety_margin absorbs the error in your token estimates and the formatting tokens the provider adds around each message. A margin of 5 to 10 percent is a common starting point when you estimate. Use a smaller one when you count with the model's real tokenizer.
Putting it in code
def estimate_tokens(message):
# Rough heuristic: about 4 characters per token, plus per-message overhead.
return len(message["content"]) // 4 + 4
def input_budget(context_window, max_output_tokens, margin_ratio=0.1):
margin = int(context_window * margin_ratio)
budget = context_window - max_output_tokens - margin
if budget <= 0:
raise ValueError("Reply size and margin leave no room for input")
return budget
def fits(messages, budget, fixed_overhead=0):
used = sum(estimate_tokens(m) for m in messages) + fixed_overhead
return used <= budget
budget = input_budget(context_window=8192, max_output_tokens=1024)
print(budget) # 6349
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Summarize our plan for the migration."},
]
print(fits(messages, budget)) # TrueThe ValueError matters. If someone configures a reply cap close to the window size, failing at startup is better than silently sending requests with no history.
What counts toward the input
Count everything the provider sees, not only the visible chat.
| Item | Counts as input? | Notes |
|---|---|---|
| System prompt | Yes | Pinned, so it is paid on every request |
| Rolling summary | Yes | Grows until you cap it |
| Recent messages | Yes | The part you truncate |
| Tool or function definitions | Yes | Pass their size as `fixed_overhead` |
| The new user message | Yes | Include it before you truncate |
Common errors
- Budgeting against the full window. The request fits until the model replies, then the reply is truncated.
- Forgetting the new message. Truncate the history together with the incoming user turn, not before it.
- Ignoring fixed overhead. Ten tool definitions can use hundreds of tokens that never appear in
messages. - Using one margin for every model. Different tokenizers disagree with a 4-characters-per-token estimate by different amounts. Compare your estimate with the token usage the API reports, then tune the margin.
Exercise
A model has a 16,000-token context window. You set maxoutputtokens to 2,000 and use a 10% safety margin. Your tool definitions cost 600 tokens, and the system prompt costs 400 tokens. How many tokens are left for conversation history and the new user message?
Show answer
The margin is 1,600. The input budget is 16,000 - 2,000 - 1,600 = 12,400. Subtracting the 600 tool tokens and 400 system tokens leaves 11,400 tokens for history and the new message.