Sub topic 5
Output Limits and the Combined Token Budget
This chapter assumes you can read basic Python, have called an LLM through a chat or completion API, and are comfortable with simple arithmetic. You should already know what a token is and what a context window is. Here we focus on a detail that trips up many developers: the output has its own limit, and the output shares the context window with the input.
Two limits, one window
A model call has three numbers that matter for sizing:
- Input tokens: everything you send. This includes the system prompt, the conversation history, any documents you attach, tool definitions, and the new user message.
- Output tokens: everything the model generates in reply.
- Context window: the maximum number of tokens the model can handle in one call.
The context window is a combined budget. Input and output draw from the same pool. A model with an 8,000-token window cannot accept 8,000 tokens of input and then also write a reply, because the reply has no room left.
On top of that, most models have a separate cap on output length, often much smaller than the window. A model might offer a 200,000-token window but allow at most 8,192 tokens of output per call. Both rules apply at once, and the stricter one wins.
The budget rule
Write the rule as an inequality:
input_tokens + max_output_tokens <= context_window
max_output_tokens <= model_output_capThe check below is the first of these two rules in code. It is the same helper the chapter on counting tokens builds toward.
def fits_in_window(input_tokens, max_output_tokens, context_window):
return input_tokens + max_output_tokens <= context_window
print(fits_in_window(2000, 500, 8000)) # True
print(fits_in_window(7800, 500, 8000)) # FalseIn the second call, the input alone fits (7,800 is below 8,000), but there are only 200 tokens left for the reply. Asking for up to 500 breaks the budget.
What `max_output_tokens` means
Most APIs let you set a parameter that limits the reply. The name varies by provider. Common names are max_tokens, max_output_tokens, and max_completion_tokens. Check your provider's documentation for the exact name and for how it behaves.
Three points are easy to miss:
- It is a ceiling, not a target. Setting it to 1,000 does not make the model write 1,000 tokens. The model stops when it finishes, which is usually much sooner.
- It does not shorten the answer gracefully. If the model hits the ceiling mid-sentence, the reply is cut off at that point. The model does not know about the limit and does not plan a shorter answer.
- It is checked against the window. Some providers reject a request when input plus the requested maximum exceeds the window, even if the model would have stopped early. Others only fail when generation actually runs out of room. Do not rely on the second behavior.
Worked example
Suppose a model has these limits (made-up numbers for illustration):
| Limit | Value |
|---|---|
| Context window | 16,000 tokens |
| Output cap | 4,000 tokens |
Your prompt has 13,000 input tokens. How many output tokens can you request?
- Room left in the window: 16,000 − 13,000 = 3,000.
- Output cap: 4,000.
- The smaller of the two is 3,000, so that is the most you can request.
If instead your prompt has 5,000 tokens, the window leaves 11,000, but the output cap of 4,000 is stricter. You can request at most 4,000.
This gives a general formula:
def max_allowed_output(input_tokens, context_window, output_cap):
room_in_window = context_window - input_tokens
return max(0, min(room_in_window, output_cap))
print(max_allowed_output(13000, 16000, 4000)) # 3000
print(max_allowed_output(5000, 16000, 4000)) # 4000
print(max_allowed_output(17000, 16000, 4000)) # 0The max(0, ...) guard handles the case where the input alone is already too large. A negative answer would be meaningless, and a zero tells the caller to shrink the input before trying again.
How a reply ends
The API usually tells you why generation stopped. The field is often called stop_reason or finish_reason. Typical values include:
| Meaning | Typical value | What it tells you |
|---|---|---|
| The model finished naturally | `stop` or `end_turn` | The reply is complete. |
| The output ceiling was reached | `length` or `max_tokens` | The reply may be cut off. |
| A stop sequence was matched | `stop_sequence` | Generation ended on a string you chose. |
| The model asked to call a tool | `tool_calls` or `tool_use` | The reply is a request, not a final answer. |
The exact strings differ between providers, so treat the table as a pattern and look up the real values for your API.
A reply that ended because of the length limit is the main case to handle. If you parse the reply as JSON, a truncated reply will usually be invalid JSON and your parser will fail. If you show the text to a user, it may stop in the middle of a word. Always check the stop reason before trusting the output.
def is_truncated(stop_reason):
return stop_reason in {"length", "max_tokens"}
reply = {"text": '{"name": "Ada", "role": "engi', "stop_reason": "length"}
if is_truncated(reply["stop_reason"]):
print("Reply was cut off. Retry with a higher limit or a shorter prompt.")Choosing a value for the output limit
There is no single right setting. Weigh these factors:
- Task shape. A yes/no classifier needs a handful of tokens. A summary may need a few hundred. Code generation or long-form writing may need thousands.
- Cost protection. Output tokens are usually priced higher than input tokens. A lower ceiling puts an upper bound on what a runaway reply can cost.
- Latency. The model writes tokens one after another, so a long reply takes longer. A tighter limit also bounds the wait.
- Truncation risk. A ceiling set too low cuts off good answers. Measure the length of real replies, then set the limit above the longest ones you want to keep.
A practical approach is to log the output token count of real calls, look at the high end of the distribution, and set the ceiling with some margin above it. Combine this with an instruction in the prompt about desired length. The prompt shapes how long the model aims to write, and the ceiling is only a safety net.
Reserving room for the reply
Because output shares the window, long-running applications should reserve output room before adding input. A common pattern is to decide an output reserve first and compute the input budget from it:
def input_budget(context_window, reserved_output, safety_margin=200):
return context_window - reserved_output - safety_margin
print(input_budget(8000, 1000)) # 6800The safety margin covers small mismatches between your token count and the provider's count. These mismatches are real. Providers often add a few tokens of formatting overhead for each message, and a tokenizer library for a different model family may count slightly differently. Chat formats typically add special tokens around each message that your plain-text count does not include.
You then trim or select input until it fits within that budget. The history-trimming helper from a later chapter takes exactly this budget as its argument.
Common errors
- Forgetting that output counts against the window. A prompt that "fits" can still fail once you reserve space for the reply.
- Setting the limit to the window size. Requesting an output equal to the whole window leaves no room for input, so the request is rejected or the effective limit is far lower.
- Ignoring the separate output cap. A large window does not mean large replies. A 200,000-token window with an 8,000-token output cap cannot write a 50,000-token document in one call.
- Not checking the stop reason. Truncated replies look like normal replies until something downstream breaks.
- Counting only the visible text. System prompts, tool definitions, and per-message overhead all count as input. Some models also spend tokens on hidden reasoning that counts as output, which a later chapter covers.
- Assuming a higher limit costs more. You pay for tokens actually generated, not for the ceiling. Raising the ceiling only raises the worst case.
Long outputs that exceed the cap
When the task needs more output than one call can produce, split the work:
- Break the job into parts, such as one section of a report per call.
- Pass a short outline or summary of earlier parts instead of their full text, so input stays small.
- Assemble the parts yourself.
Asking the model to "continue" after a truncated reply is possible, but it is the weaker option. The new call has to receive the truncated text as input, which costs more, and the model may repeat itself or break the format at the seam.
Exercise
A model has a 32,000-token context window and an output cap of 8,000 tokens. Your prompt is 27,500 tokens. (a) What is the largest output limit you can request? (b) If you shorten the prompt to 10,000 tokens, what is the largest limit you can request? (c) A reply comes back with a stop reason of "length". What does that mean, and what should you check before using the reply?
Show answer
(a) Room in the window is 32,000 − 27,500 = 4,500. The output cap is 8,000. The smaller value is 4,500. (b) Room in the window is 32,000 − 10,000 = 22,000, but the output cap of 8,000 is stricter, so the answer is 8,000. (c) The model reached the output limit before it finished, so the reply is probably cut off. Check whether the text is complete, and if it must be valid JSON or code, do not parse it as is. Retry with a higher limit if the cap and window allow, shorten the prompt, or split the task.
Exercise
A chat application uses an 8,000-token window and reserves 1,000 tokens for the reply plus a 200-token safety margin. How many tokens can the system prompt, history, and new message use in total? Why keep a safety margin when you already counted the tokens?
Show answer
8,000 − 1,000 − 200 = 6,800 tokens. The margin covers differences between your count and the provider's count, such as per-message formatting overhead, special tokens, and tokenizer differences between model families. Without it, a request that your count says fits could be rejected.