# Output token caps: set max_tokens without cutting answers off

URL: https://infro.io/blog/output-token-caps-set-max-tokens-without-cutting-answers-off
Author: INFRO Editorial (https://infro.io/blog/editorial)
Publisher: INFRO
Published: 2026-12-01
Last modified: 2026-12-01
Last reviewed: 2026-12-01 (next review due 2026-12-31)
Topic: Cost and FinOps
Format: Guide

> Set max_tokens just above a high percentile (p99 or p99.9) of your observed total output per route, with reasoning tokens counted inside it, then watch the truncation share. Judge the cap by cost per successful task, not by tokens per request: a cap that cuts answers off raises that number.

Key takeaways:
- Pick the cap per route from a high percentile of observed total output tokens, including reasoning tokens, not from a round number.
- On OpenAI and Anthropic reasoning or thinking tokens count toward the output limit, so a low cap can end a request with billed tokens and no visible answer.
- A truncated answer is paid for and usually unusable, so compare caps by cost per successful task rather than cost per request.
- A cap mostly bounds the tail; the mean moves little, so expect protection against runaway outputs rather than a large drop in average spend.
- Alert on the truncation share and on output tokens per request, because both drift when a prompt or a model snapshot changes.

## 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](https://infro.io/blog/llm-spend-controls-budgets) and [reasoning tokens](https://infro.io/blog/reasoning-tokens-cost) 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.

```python
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.

> **Example: Illustrative percentiles**
> For a support-reply route, suppose the observed total output is p50 220, p95 640, p99 1,400 and p99.9 2,600 tokens (made-up figures). A cap of 1,750 (p99 × 1.25) would touch roughly 1% of requests and would stop a runaway reply at 1,750 tokens instead of the model's own limit. A cap of 3,250 (p99.9 × 1.25) touches about 0.1% and bounds the tail more loosely.

## 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 |

Table: Where the cap and reasoning tokens meet, per the vendor pages read for this article.

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]

```python
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:

1. **Free text shown to a person:** show it, mark it as cut off, and offer "continue". Retrying silently doubles the spend.
2. **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.
3. **Tool calls:** never execute an incomplete call; retry with a higher cap.
4. **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](https://infro.io/blog/cost-per-successful-task) for the general metric.

> **Example: Illustrative cap comparison**
> Assume an input of 1,500 tokens billed at a quarter of the output rate (a 4:1 ratio, illustrative), so input costs the equivalent of 375 output tokens. Costs below are in output-token equivalents, and every figure is made up.
> 
> | Cap | Mean output | Truncated | Cost per request | Cost per successful task |
> | --- | --- | --- | --- | --- |
> | 4,096 | 310 | 0.1% | 685 | 686 |
> | 1,500 | 295 | 1% | 670 | 677 |
> | 800 | 270 | 4% | 645 | 672 |
> | 400 | 215 | 22% | 590 | 756 |
> 
> The 400 cap has the lowest cost per request and the highest cost per successful task. The 800 cap beats the loose cap only slightly: the mean barely moves because most answers are short. What a cap buys is a bound on the tail, not a large cut in the average.

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.

## Questions

### Should I set one cap for the whole organization?

No. Output length differs by route: a classifier, a summarizer and a drafting assistant have different distributions. A single organization-wide number is either too tight for the long routes or too loose to bound the short ones. Set it per route or per feature, and keep an organization ceiling only as a backstop.

### Is a stop sequence or a prompt instruction a substitute for a cap?

They shape length but do not bound it. A stop sequence ends output only if the model emits it, and a length instruction is a request the model may not follow. The cap is the only control the provider enforces, so use all three: instruct for the typical length, and cap for the worst case.

## Sources

1. Reasoning models — OpenAI. https://developers.openai.com/api/docs/guides/reasoning (accessed 2026-12-01)
2. Extended thinking — Anthropic. https://platform.claude.com/docs/en/build-with-claude/extended-thinking (accessed 2026-12-01)
3. Stop reasons and fallback — Anthropic. https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons (accessed 2026-12-01)
4. Chat completions — INFRO. https://infro.io/docs/api/chat-completions (accessed 2026-12-01)
5. Traffic changes — INFRO. https://infro.io/docs/observability/traffic-changes (accessed 2026-12-01)
