Why the output side needs its own limit
Most spend controls act on money: a budget per key, a ceiling per project. They stop the bill after the fact or refuse the next request. An output cap acts earlier, on a single request, and it bounds the part of the request the model decides for itself. You control the input; the model controls how long it talks. Output tokens are also billed at a higher rate than input tokens on most rate cards, so the unbounded variable sits on the expensive side. Read your own provider's rate card for the ratio; the examples below use an illustrative 4:1.
The catch is that the cap is blunt. When a response reaches it, generation stops mid-sentence, mid-JSON or mid-tool-call, and you still pay for every token produced. A cap is therefore not a saving by itself. It is a trade: a bounded worst case against some share of answers that arrive cut off. This guide is about choosing that trade from data and measuring it as cost per successful task, the unit that does not reward a cap for producing cheap garbage.
What it does not cover: spend limits per key or organization, and how to tune reasoning effort. See LLM spend controls and reasoning tokens for those.
Choose the cap from percentiles, not round numbers
Start from what the route actually produces. For each route or feature, collect the total output tokens per request over a representative window, at least a week so weekday and weekend patterns appear, and exclude requests that already hit a limit, because their length is the cap, not the model's choice. Then read the distribution.
- p50 tells you the typical answer and what your prompt asks for.
- p95 is where most "long but normal" answers end.
- p99 and p99.9 show the tail you are trying to bound.
- max is usually an outlier worth reading by hand; it is often a loop, a pasted document echoed back, or a prompt that invited an essay.
A workable rule: set the cap a margin above p99 (or p99.9 for routes where a cut-off answer is costly), then check how many requests the cap would have touched. Replaying the logged lengths against the candidate cap gives the truncation share before you ship it.
import numpy as np
def candidate_caps(output_tokens, margin=1.25):
"""output_tokens: total output tokens per request, reasoning included,
for requests that ended naturally (not at a length limit)."""
x = np.asarray(output_tokens)
pcts = {p: float(np.percentile(x, p)) for p in (50, 95, 99, 99.9)}
caps = {f"p{p}x{margin}": int(v * margin) for p, v in pcts.items()}
# What share of observed requests each cap would have cut off
return {
name: {"cap": cap, "would_truncate": float((x > cap).mean())}
for name, cap in caps.items()
}Two cautions. First, the sample excludes already-truncated requests, so it understates the tail on a route that has been running with a low cap; raise the cap for a trial period to see the true distribution. Second, distributions move: a prompt edit or a new model snapshot changes answer length, so the cap needs a recheck on a schedule, not once.
How reasoning and thinking tokens share the cap
On reasoning models, the number you cap is not the length of the visible answer. OpenAI states that reasoning tokens are not visible through the API, still occupy space in the context window, and are billed as output tokens.1 Its max_output_tokens parameter limits the total the model generates, including reasoning tokens, visible output tokens and non-visible formatting tokens.1 The reasoning count appears in usage.output_tokens_details.reasoning_tokens.1
The failure mode is specific. If generation reaches the limit, the response comes back with status: "incomplete" and incomplete_details.reason set to max_output_tokens, and OpenAI notes this can happen before any visible output is produced, so you can pay for input and reasoning tokens and get no answer.1 OpenAI recommends reserving at least 25,000 tokens for reasoning and output when you start experimenting, and adjusting once you know your prompts' reasoning use.1
Anthropic's manual extended thinking has the same coupling with a different shape. budget_tokens has a minimum of 1,024 and must be less than max_tokens; thinking tokens count toward the max_tokens limit for the turn, so the budget must leave room for the final response.2 The budget is a target, not a strict cap, and max_tokens remains the hard ceiling on total output.2 The thinking share of billed output is reported in usage.output_tokens_details.thinking_tokens.2 Anthropic also marks manual extended thinking as deprecated: Claude 4.7 and later models reject it with a 400 error, and adaptive thinking is the recommended path.2 On those models, a max_tokens cap is still the ceiling you set; check the thinking pages for how the model decides how much to think.
I could not read Gemini's thinking or generate-content pages for this article, so the table leaves that column open. Before applying a cap to Gemini traffic, confirm in Google's docs whether thinking tokens count against the output limit, what the response reports when the limit is hit, and how they are priced.
| OpenAI (Responses) | Anthropic (Messages) | Gemini | |
|---|---|---|---|
| Cap parameter | max_output_tokens | max_tokens | Not verified here |
| Reasoning counts toward cap | Yes | Yes (thinking counts toward max_tokens) | Not verified here |
| Signal that the cap was hit | status: incomplete, reason max_output_tokens | stop_reason: max_tokens | Not verified here |
| Reasoning tokens reported in | output_tokens_details.reasoning_tokens | output_tokens_details.thinking_tokens | Not verified here |
The practical consequence: measure percentiles on total output including reasoning, set the cap on that, and never size it from the visible answer alone. Lowering reasoning effort shifts the distribution left; capping without lowering effort just truncates the thinking.
Detect truncation on every provider
A cap you cannot observe is a silent quality bug. Each API reports truncation differently, so normalize it in one place.
Anthropic's stop_reason is max_tokens when the response reached your limit, and the documented responses are to raise the limit or continue the response.3 It also reports model_context_window_exceeded, which Anthropic says to treat as truncated.3 One case deserves a special branch: if the cut-off lands inside a tool_use block, the tool call is incomplete, and Anthropic says to retry with a higher max_tokens to get the full tool use.3 Executing a half-written tool call is worse than a truncated paragraph.
On OpenAI chat-style endpoints the equivalent is finish_reason: "length"; on Responses it is the incomplete status above.1
def truncated(provider: str, resp: dict) -> bool:
if provider == "openai_responses":
return (resp.get("status") == "incomplete"
and resp.get("incomplete_details", {}).get("reason") == "max_output_tokens")
if provider == "anthropic":
return resp.get("stop_reason") in ("max_tokens", "model_context_window_exceeded")
if provider == "chat_completions":
return resp["choices"][0].get("finish_reason") == "length"
raise ValueError("verify the provider's signal before adding a branch")Then decide the policy per route, because the right reaction differs:
- Free text shown to a person: show it, mark it as cut off, and offer "continue". Retrying silently doubles the spend.
- Structured output or JSON: treat as a failure. A truncated JSON document does not parse, so retry once with a higher cap or fall back to a larger-cap path.
- Tool calls: never execute an incomplete call; retry with a higher cap.
- Reasoning models with empty visible output: retry with more headroom, and log it as a cap that is too low for that effort setting.
Judge a cap by cost per successful task
Tokens per request fall as the cap tightens, which makes a tight cap look good on a cost dashboard. But a truncated answer is billed and typically fails the task, so the denominator matters. Cost per successful task is the request cost divided by the share of requests that succeed, plus the cost of any retry you issue. See cost per successful task for the general metric.
Two corrections to this simple model. If you retry truncated requests at a higher cap, add the retry's full cost to the numerator for those requests; a tight cap with a retry can cost more than a loose cap with none. And if the task has partial value (a truncated summary is still useful), your success definition changes, so use a score or user feedback rather than the absence of a length stop.
The case where a cap earns its keep is the tail. One looping response that runs to the model's maximum output costs as much as dozens of normal ones. A cap above p99.9 costs you almost nothing in truncation and removes that worst case.
What happens when you leave the cap out
Omitting the parameter does not mean no limit. On INFRO's chat completions endpoint, when max_tokens is omitted the provider's own default applies, with two exceptions: Anthropic requires a value, so the gateway sends the model's maximum output (32,768 tokens where the catalog lists none), and under a blocking budget the gateway sends that same ceiling to every provider so a response cannot outrun what the budget reserved.4 max_completion_tokens is accepted as an alias, and OpenAI's reasoning models, which refuse max_tokens, are sent max_completion_tokens whichever name you used.4
So a route without an explicit cap can run at a very different ceiling depending on which provider answers it. If you fail over between providers, set the cap yourself and make it the same everywhere, in terms of total output including reasoning, so the worst case does not change with the target. Remember that tokenizers differ between models, so the same text is a different token count on each; check your cap against each fallback model's own usage numbers.
Operate the cap: watch the drift
A cap is a setting that rots. The distribution under it moves when a prompt gains an instruction, when a provider moves a model name to a new snapshot, or when users change what they ask for. Track three numbers per route: the truncation share, output tokens per request, and the p99 of total output.
INFRO's traffic changes findings include two of these, computed from request metadata and not from answers: output tokens per request up by at least 15% and at least 20 tokens, and the share of finish_reason: length up by at least 3 percentage points, which the docs read as answers reaching max_tokens.5 Each finding names a likely cause and an estimated weekly change in provider cost, and INFRO does not judge answer quality, which needs an evaluation tool.5 Per-request token counts and estimated provider cost are available through usage records, so the percentile query above can run on your own export.
A short review routine:
- Recompute p50, p95, p99 and p99.9 of total output per route monthly, and after any model or prompt change.
- Alert when the truncation share rises above the level you accepted.
- Alert when output tokens per request moves, since it can signal a snapshot change before quality complaints do.
- Confirm tool-calling routes never execute a call from a truncated response.
- Keep the cap identical across every failover target, and re-measure after adding one.
- Report cost per successful task per route, not tokens per request, to the owners of the budget.
