Sub topic 4
Setting an Input Budget and Reserving Room for the Reply
This chapter assumes you can read basic Python, know the system, user and assistant message roles, and have a general idea of what a token is. You should also know that a model has a context window, which is the maximum number of tokens it can handle in one request. Here you will turn that limit into a number your code can enforce: the input token budget.
Why the window is not your input budget
A common mistake is to treat the context window as the space available for your messages. On most chat APIs the window covers the input and the reply together. If the model supports 8,000 tokens and you send 7,900 tokens of history, the reply has room for about 100 tokens. The model then stops in the middle of a sentence, or the API returns an error.
The input budget is the number of tokens you allow yourself to send. It is smaller than the window:
input_budget = context_window - reserved_output - safety_marginEach term has a job:
- context_window is the model's documented limit, for example 8,000 tokens.
- reserved_output is the space you hold back for the reply. It is usually the same value you pass as the maximum output tokens setting (called
max_tokens,max_completion_tokensor similar, depending on the provider). - safety_margin absorbs error in your token count. If you use an estimate, the margin covers the estimate being low.
Providers differ in details. Some enforce a separate cap on output tokens that is lower than the window. Some count hidden tokens, such as reasoning tokens, against the output. Read the documentation for your model and set reserved_output to the largest reply you are willing to allow.
What counts against the budget
Everything you send counts. Developers often count only the visible chat messages and forget the rest:
- The system prompt, which is often the largest fixed cost.
- Every user and assistant message you resend.
- Any summary message you add (later chapters cover summaries).
- Tool definitions, if you pass function schemas. These are often sent as extra input and can take hundreds of tokens.
- Tool call arguments and tool results stored in the history.
- Per-message formatting overhead. Chat APIs wrap each message in special tokens for the role and boundaries. This is usually a few tokens per message, which is why the code in this tutorial adds a small constant to each estimate.
If you ignore tool schemas, your count will be low on every request, and the error is the same size every time. Treat that fixed cost as a separate line item.
A worked example
Suppose your model has an 8,000 token window. You decide replies should never exceed 1,000 tokens, and you want a 400 token margin because you estimate with a character heuristic.
| Item | Tokens |
|---|---|
| Context window | 8,000 |
| Reserved output | 1,000 |
| Safety margin | 400 |
| Input budget | 6,600 |
| System prompt (pinned) | 500 |
| Tool schemas (fixed) | 700 |
| Left for conversation history | 5,400 |
The 5,400 tokens left for history is the number the truncation function actually works with. If you pass 6,600 to truncate_history while also sending 700 tokens of tool schemas that the function does not see, you will go over the window.
Computing the budget in code
Put the arithmetic in one function so the rule lives in one place. It should fail loudly when the settings cannot work, because a negative budget means the configuration is wrong, not that the history is too long.
def input_budget(context_window, reserved_output, safety_margin=0, fixed_overhead=0):
"""Tokens available for messages after reserving reply space.
fixed_overhead: tokens you send on every request that are not part of the
message list you will truncate, such as tool schemas.
"""
budget = context_window - reserved_output - safety_margin - fixed_overhead
if budget <= 0:
raise ValueError(
f"No room for input: window={context_window}, "
f"output={reserved_output}, margin={safety_margin}, "
f"overhead={fixed_overhead}"
)
return budget
budget = input_budget(
context_window=8000,
reserved_output=1000,
safety_margin=400,
fixed_overhead=700,
)
print(budget) # 5900The result is 5,900, not 5,400. The two differ because this function treats the system prompt as part of the message list. In the earlier table, the system prompt was subtracted separately. The truncate_history function from the spine does the same thing internally: it subtracts the cost of the system messages from the budget you give it. So you pass in 5,900, and it keeps the system prompt and fits history into what remains. Both views give the same final history size, as long as you subtract each item exactly once.
Using the budget with truncation
Here is the budget feeding the sliding-window function. It reuses estimate_tokens and truncate_history, which pin the system prompt and walk backward from the newest message.
def estimate_tokens(message):
# Rough heuristic: about 4 characters per token, plus a small per-message overhead.
# Replace with your model's real tokenizer when exact counts matter.
return len(message["content"]) // 4 + 4
def truncate_history(messages, max_input_tokens):
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
budget = max_input_tokens - sum(estimate_tokens(m) for m in system)
kept = []
for message in reversed(rest):
cost = estimate_tokens(message)
if cost > budget:
break
kept.append(message)
budget -= cost
kept.reverse()
# Do not start the window with an orphaned assistant reply.
while kept and kept[0]["role"] != "user":
kept.pop(0)
return system + kept
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for i in range(40):
messages.append({"role": "user", "content": f"Question {i}: " + "x" * 400})
messages.append({"role": "assistant", "content": f"Answer {i}: " + "y" * 400})
trimmed = truncate_history(messages, max_input_tokens=1000)
print(len(messages), "->", len(trimmed))
print(sum(estimate_tokens(m) for m in trimmed), "tokens")With these settings the call keeps the system prompt and the most recent messages that fit, and the printed token total stays at or below 1,000. Change max_input_tokens and watch the kept count change. Because messages are dropped whole, the total is usually a little under the limit rather than exactly on it.
Edge cases and failure modes
The budget is smaller than one message. The loop in truncate_history stops at the first message that does not fit. If the newest user message alone is larger than the remaining budget, kept is empty and you send only the system prompt. The model then answers with no question to answer. Check for this case. Either reject oversize input with a clear message to the user, or truncate the content of that one message deliberately.
The reserved output is too generous. If you reserve 4,000 tokens of an 8,000 token window for replies that average 300 tokens, you throw away half your window on every request. Reserve for the largest reply you need, not the largest the model allows. Many applications set a modest max_tokens and budget around it.
The reserved output is too small. Long answers get cut off, and the API reports a length-related stop reason (the name varies by provider, often length or max_tokens). Log this stop reason. A rising rate of cut-off replies tells you the reservation is too low.
The estimate is biased. The four-characters-per-token heuristic is tuned for English prose. Code, JSON, non-English text and long numbers usually produce more tokens per character, so the heuristic undercounts. Your safety margin has to cover that bias. If your traffic is mostly code, either widen the margin or use the real tokenizer.
A tool result is huge. One search result or file dump can use most of the budget on its own. Cap tool output size when you store it in the history, so one result cannot push everything else out.
The limit changes with the model. Context windows differ between models and between versions of the same model. Keep the window size in configuration keyed by model name, not as a constant in the truncation code.
Calibrating the margin from real data
You do not have to guess the safety margin. Record the estimated input tokens and the provider's reported input tokens for each request, then look at the worst gap.
def required_margin(samples, percentile=0.99):
"""samples: list of (estimated_tokens, reported_tokens) pairs.
Returns the underestimate that covers the given fraction of requests.
"""
gaps = sorted(max(0, reported - estimated) for estimated, reported in samples)
index = min(len(gaps) - 1, int(len(gaps) * percentile))
return gaps[index]
samples = [(5200, 5310), (4800, 4850), (5900, 6120), (3000, 3010), (5500, 5500)]
print(required_margin(samples)) # 220A margin set from the 99th percentile gap, plus a little headroom, is more defensible than a round number. Recompute it when your traffic changes, for example when users start pasting code.
Summary of the decisions
- Find the window for your exact model.
- Choose
reserved_outputfrom the longest reply you need, and pass the same value as the output cap in your request. - Choose a safety margin from measured estimation error.
- Subtract fixed costs such as tool schemas.
- Pass the result to your truncation or compaction step, and make sure each cost is subtracted once.
Exercise
A model has a 16,000 token window. You set the output cap to 2,000 tokens, use a safety margin of 500, and send tool schemas that cost 1,200 tokens on every request. Your system prompt costs 600 tokens and is included in the message list passed to truncatehistory. What value do you pass as maxinput_tokens, and how many tokens of non-system history can be kept at most?
Show answer
maxinputtokens = 16,000 - 2,000 - 500 - 1,200 = 12,300. The system prompt is part of the list, so truncate_history subtracts its 600 tokens itself, leaving at most 11,700 tokens for non-system history. Passing 11,700 instead would count the system prompt twice.
Exercise
Your application sends mostly Python code. Replies are often cut off and the stop reason is "length", while the input estimate looks safely under budget. Name two things to check and the change each suggests.
Show answer
First, check the reserved output against the cap sent in the request. If replies are cut off at the cap, raise the cap and reserve the same amount in the budget. Second, compare estimated input tokens with the provider's reported input tokens. Code produces more tokens per character than the four-character heuristic assumes, so the estimate is probably low. Widen the safety margin or use the model's real tokenizer. Together these keep both the input and the reply inside the window.