Anthropic max_tokens Needs a Route Cap Before Provider Dispatch
Anthropic requires max_tokens on Messages API requests and defines it as the absolute output ceiling, although a model can stop earlier. A production gateway should bind that field to the authenticated route, resolved model, workload, and continuation policy. This guide separates caller requests from enforced caps, handles zero-token cache warming, classifies stop reasons, and defines an acceptance fixture for route drift.

Anthropic's Messages API accepts max_tokens as the absolute number of tokens Claude may generate before stopping. The model can finish earlier, and each model has its own permitted maximum. That makes the field a caller-controlled resource request rather than a prediction of response length. An authenticated support route asking for 600 tokens and a report-generation route asking for 8,000 tokens should pass through different policy limits even when both call the same model.
I want the gateway to resolve that limit before dispatch. A provider-side maximum catches invalid values. A route cap decides what this caller and workload are allowed to request.
TL;DR
- Bind
max_tokensto the authenticated route and workload, subject to the resolved Anthropic model. - Record the caller's requested value and the gateway's enforced value as separate fields.
- Treat
stop_reason: max_tokensas a truncated response state, rather than a successful complete answer. - Reserve
max_tokens: 0for an approved prompt-cache prewarming route.
max_tokens is an output ceiling
Anthropic's Messages API reference defines max_tokens as the maximum generated-token count before stopping. A model can stop before reaching the value, and different models accept different maxima, so the field caps one response without promising that the full allowance will be consumed.
A route policy should resolve four facts before forwarding POST /v1/messages: authenticated identity, application route, resolved model, and requested max_tokens. The decision can then reject a value above the route cap or replace it under an explicit normalization rule. Silent normalization leaves the application believing it bought a larger generation budget than the gateway allowed, so return or record the enforced value where the caller can diagnose it.
Keep the provider's model maximum as a separate constraint. The effective ceiling is the smallest allowed value across the caller request and route policy, subject to the current model capability. The LLM API parameter allowlisting guide provides the wider pattern for rejecting unapproved request controls.
Route caps should follow the workload
A short classification route may need 80 tokens, while a contract-summary route may need 2,000. An agent route can need enough room to emit a valid tool_use block. Copying one 8,192-token default across these routes grants unnecessary capacity to the first two and can truncate the third at the worst point.
Set the cap in versioned route policy. Store the route identifier, model allowlist, minimum usable value, maximum value, and handling rule for omission or excess. Anthropic's current API reference marks max_tokens as a request parameter, so a gateway should reject a missing value before provider dispatch instead of inventing an undocumented application default.
My opinion is blunt: an organization-wide output cap is only a placeholder. It ignores the difference between a two-label classifier and a multi-page analysis while making both harder to review.
The per-route AI policies guide explains how identity and URL path select the rule. The token cap becomes one named decision inside that route record.
Zero belongs to cache prewarming
The API reference documents one special value. Setting max_tokens to 0 populates the prompt cache without generating a response. That behavior belongs on a cache-prewarming route with its own authorization, rather than on an ordinary user-facing generation route.
A caller that changes 600 to 0 has changed the requested operation. The expected response now contains no generated answer. Allowing the value everywhere can turn a valid user action into an empty-looking result that application code misclassifies as a provider failure.
Create a distinct rule for prewarming. Require an approved cached prefix, model, identity, and request purpose. Record requested_max_tokens: 0 and the policy decision alongside the provider response and cache-related usage fields available to the application. A normal generation route should reject zero with a stable local error before it spends a provider exchange.
Picture the release dashboard: one grey cache-warm row with zero output sits between hundreds of green answer rows. Without the route label, an on-call engineer has to guess whether the blank output was deliberate.
Stop reasons determine the final state
Anthropic's stop reasons guide says stop_reason: max_tokens means the response reached the request limit and was truncated. end_turn means Claude completed naturally. The same guide distinguishes model_context_window_exceeded, which means the response filled the model's context window and should also be treated as truncated.
Classify every HTTP 200 through the terminal response. Store its stop reason, output-token usage, enforced cap, model, and provider message ID. A route that requires complete structured output should reject or quarantine a max_tokens result. A conversational route may show the partial answer with a visible continuation state.
Continuation is another model request. Preserve the earlier response. Bound the continuation count and cumulative output allowance, then issue another route decision. An automatic loop that grants a fresh cap until Claude finishes defeats the original limit.
The AI audit log schema can carry the shared identity, route, policy version, provider ID, and outcome fields beside this token-specific state.
Enforcement needs a deterministic record
Create the decision record before provider dispatch. Capture what the caller requested and the cap selected by route policy. Add the model capability consulted, enforced token count, policy version, and decision reason. After the response returns, append the provider response ID, usage, stop reason, and terminal application state.
Preserve omission as its own input state. A request that explicitly sends 1,024 differs from a client library that dropped the field before serialization. Inspect the actual routed JSON body, because configuration objects and wire payloads can diverge during SDK upgrades.
Reject strings, negative numbers, fractions, values above the route cap, zero on generation routes, and values unsupported by the resolved model. If policy normalizes an allowed high value downward, make that behavior part of the route contract and test the response metadata the application receives.
The Anthropic API gateway pattern owns the wider base-URL and identity design, including response inspection. This control owns one field and its lifecycle.
A route fixture should force every terminal branch
Send the same authenticated request through two deployed routes with different caps. Ask for a value allowed on the report route and denied on the classifier route. Confirm that the rejected request never reaches the Anthropic stub and that the allowed request carries the exact enforced integer.
Exercise missing, zero, negative, fractional, string, at-cap, and above-cap values. Change the resolved model while keeping the caller request fixed, then verify policy evaluates the current model entry. Return end_turn and max_tokens responses from the stub. Also return a model_context_window_exceeded response and check that the application records three distinct outcomes.
Finally, return a partial structured object under max_tokens. The consumer should quarantine it rather than parsing it as a completed result. Trigger one approved continuation and prove that it creates a second routed decision under the same application operation, with a bounded cumulative budget.
Keep the raw fixture output beside the test report. A screenshot of a green test badge hides the value that crossed the HTTP boundary.
DeepInspect
DeepInspect can enforce max_tokens when authenticated user or agent traffic is deliberately routed through its HTTP proxy to Anthropic. It can resolve the route and model, reject unapproved values before provider dispatch, preserve requested and enforced values, and add the response stop reason to the per-decision record.
The application owns prompt construction, continuation behavior, completeness checks, and user-visible handling of partial output. Direct Anthropic calls and any traffic that bypasses the proxy remain outside this control.
Book a technical deep dive at deepinspect.ai.
Frequently asked questions
- Is max_tokens a guaranteed response length?
No. Anthropic defines it as the absolute maximum number of generated tokens and says models can stop earlier. Record actual output usage and the terminal stop reason instead of treating the requested ceiling as consumption.
- Should the gateway clamp values above the route cap?
A gateway can clamp only under an explicit route contract that exposes and records the enforced value. Rejection is clearer for structured and high-impact workflows because the caller learns that its requested generation budget was unavailable before relying on the result.
- Does max_tokens limit the input context?
max_tokensgoverns generated output. Input size and the model context window are separate constraints. Anthropic exposesmodel_context_window_exceededas a distinct stop reason when the response fills the available context window.- Can an application continue after stop_reason max_tokens?
It can make another Messages request with the prior content and a continuation instruction. Treat that as a new routed request with another decision, attempt record, deadline, and cumulative output budget. Never turn one capped call into an unbounded continuation loop.