Skip to content

Cost and FinOpsGuide

Output token caps: set max_tokens without cutting answers off

A cap on output tokens bounds the most expensive side of a request, but a cap set too low turns paid output into a failed task. This guide sets caps from your own output-length percentiles, shows how reasoning budgets share the cap on OpenAI and Anthropic, and judges a cap by cost per successful task.

By INFRO Editorial

Published

9 min read

Glowing token streams being compressed into a precise efficient AI infrastructure pipeline

In short

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

pick_cap.py
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 parametermax_output_tokensmax_tokensNot verified here
Reasoning counts toward capYesYes (thinking counts toward max_tokens)Not verified here
Signal that the cap was hitstatus: incomplete, reason max_output_tokensstop_reason: max_tokensNot verified here
Reasoning tokens reported inoutput_tokens_details.reasoning_tokensoutput_tokens_details.thinking_tokensNot verified here
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

normalize.py
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 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.

Questions readers ask

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.

From the team that builds it

Where this shows up in INFRO

INFRO is a control plane in front of the provider accounts you already hold. The capabilities below are the parts of it this article touches, each with the documentation that defines its behaviour.

  • Text — OpenAI-compatible

    Available with a plan

    POST /v1/chat/completions with the request shape the OpenAI SDKs already send, including streaming and tool calling.

    Read the documentation for Text — OpenAI-compatible
  • Budgets and spend ceilings

    Available with a plan

    A hard cap per organization, project, member, and key, with alerts at your own thresholds.

    Read the documentation for Budgets and spend ceilings
  • Traffic changes

    Available with a plan

    Changes in your traffic that come with no error: a model answered by a new snapshot, longer answers, a lost prompt cache, more fallbacks, answers cut off by the length limit, slower responses or a new error mix. Each finding names the likely cause and the estimated weekly change in provider cost. INFRO sees request metadata, not answers, so it does not judge answer quality.

    Read the documentation for Traffic changes
  • Usage and cost per request

    Available with a plan

    Every request records its model, latency, token or unit counts, and estimated provider cost, queryable by project and key.

    Read the documentation for Usage and cost per request
  • Unit economics and AI cost as a share of revenue

    Available with a plan

    Estimated provider cost per run (median and 90th percentile), per request, per feature, per end customer and per cost center. With the revenue each end customer paid entered by the organization (US dollars, off until switched on), AI cost as a share of that revenue, display only.

INFRO accounts are self-serve. Provider usage is billed to you by your providers; INFRO charges a software subscription and takes 0% of model spend. See plans.

Sources

Numbered in order of first citation. Each was opened and checked against the claim on the date shown.

  1. 1.Reasoning models (opens in a new tab) — OpenAI. Accessed Dec 1, 2026.
  2. 2.Extended thinking (opens in a new tab) — Anthropic. Accessed Dec 1, 2026.
  3. 3.Stop reasons and fallback (opens in a new tab) — Anthropic. Accessed Dec 1, 2026.
  4. 4.Chat completions (opens in a new tab) — INFRO. Accessed Dec 1, 2026.
  5. 5.Traffic changes (opens in a new tab) — INFRO. Accessed Dec 1, 2026.

About this article

Read on 1 December 2026: OpenAI's reasoning guide, Anthropic's extended thinking and stop-reason pages, and INFRO's chat completions and traffic changes docs. The Gemini pricing, thinking and generate-content pages returned no text, so nothing about Gemini's parameters, finish reasons or rates is stated as fact; check them before applying the Gemini rows. Dollar figures and token counts in examples are illustrative.

Last checked against its sources on . The next review is due by . No separate named reviewer is recorded for this article.

How articles are written, sourced and corrected is set out in the editorial standards.