Token Budgeting: max_tokens, Truncation, and the Cost of a Bad Default
Why a single global max_tokens default breaks latency and cost, how to size per-endpoint budgets from output distributions, and how to fail loudly on truncation
What max_tokens actually controls
max_tokens is the upper bound on how many tokens the model may produce in a single response. It is a ceiling, not a purchase order: providers bill for tokens actually generated, so raising the ceiling on a short-answer endpoint rarely changes the bill by itself. What it does change is the worst case. A model that is allowed to ramble can ramble, and every extra generated token adds latency and cost on that specific request.
The confusion comes from conflating the ceiling with the reservation. Some systems reserve capacity or budget against the maximum, and some client libraries size timeouts from it. Even where no money is reserved, a huge max_tokens signals to your own code that a very long response is acceptable. That signal leaks into timeouts, retry policies, and streaming UX. Treat max_tokens as a contract about the longest answer you are willing to ship, not as a knob you set once and forget.
There is also an interaction with the context window. Input tokens plus the output ceiling must fit within the model's limit. If you set an aggressive output ceiling on a long RAG prompt, you can push the request over the window and get an error before generation starts. Check the live model catalog for the actual limits of whichever model you route to, because they differ across families.
Input truncation versus output truncation
Input truncation happens before the model runs: you cut retrieved documents, conversation history, or tool output to fit a budget. The failure is silent and dangerous. The model answers confidently from a partial context, and nothing in the response says a document was dropped. The fix is to make truncation a visible event in your pipeline: log which chunks were dropped, how many tokens were saved, and whether the dropped content was ranked below the kept content. If you must drop high-ranked content, consider failing the request instead of degrading it.
Output truncation happens when generation hits the ceiling. The response may look syntactically fine but be semantically incomplete: a JSON object missing its closing brace, a list that stops mid-item, an explanation that ends without a conclusion. Some APIs expose a finish reason that distinguishes a natural stop from a length stop; others require you to infer it by comparing output length to the ceiling. Either way, you should not return a truncated answer to a user as if it were complete.
The two failures need different remedies. Input truncation is fixed by better retrieval, summarization, or chunk ranking. Output truncation is fixed by raising the ceiling for that endpoint, asking for a shorter format, or splitting the task into stages. Mixing them up leads to the classic mistake of raising max_tokens when the real problem was that the prompt never contained the answer.
Sizing budgets from real output distributions
The point of this exercise is that a chat assistant, a structured-extraction endpoint, and a document-summarization endpoint should not share a number. Extraction wants a tight ceiling because the schema bounds the answer. Summarization wants a generous one because length is the product. Chat sits in between and depends heavily on whether you stream.
- Instrument first. Log the actual output token count for every successful response, tagged by endpoint, prompt template, and model. Do not guess from character counts; use the tokenizer or the usage field the API returns.
- Compute p50 and p95 per endpoint. The median tells you what a typical request needs; the 95th percentile tells you what a bad-but-normal day looks like. Ignore the maximum unless you have a specific reason to support outliers.
- Set the ceiling above p95 with headroom, not at the maximum. A ceiling near p95 will truncate a meaningful slice of legitimate traffic; a ceiling at the all-time max usually just invites rambling.
- Add a separate hard cap for cost and latency. If a request would exceed your latency SLO at the ceiling, that is a signal to change the prompt or split the task, not to silently accept slower responses.
- Re-measure after prompt or model changes. Output distributions shift when you edit instructions, switch model families, or add tools, and a budget that fit last quarter may truncate today.
Failing loudly instead of returning half an answer
The cheapest bug to fix is the one that announces itself. When generation stops at the ceiling, return an explicit error or a structured flag rather than a plausible-looking partial result. For JSON endpoints, validate the parsed object against the schema and treat a parse failure as truncation until proven otherwise. For prose, compare the finish reason or the output length against the ceiling and mark the response as incomplete.
Decide the retry policy up front. A single retry with a higher ceiling is reasonable for interactive requests where the user is waiting. For batch jobs, retrying every truncated response can double your spend on the worst-behaved prompts, so cap retries and route persistent offenders to a review queue. Also distinguish truncation from other stop conditions: a model that stops because it finished is not the same as one that stopped because you told it to.
Per-endpoint defaults that survive traffic growth
- Store budgets in configuration keyed by endpoint and prompt template, not as a constant in code.
- Version the config alongside prompts so a budget change is reviewable and reversible.
- Alert when the truncation rate for an endpoint crosses a threshold you choose; a rising rate usually means prompts or traffic changed.
- Keep a conservative default for new endpoints and promote it to a measured budget once you have enough samples.
- Document the ceiling next to the timeout and retry settings, because they interact and are usually tuned by different people.
How to apply this with Admesh
Because Admesh exposes an OpenAI-compatible base URL at https://api.admesh.ai/v1 and an Anthropic-compatible endpoint at https://api.admesh.ai/v1/messages, you can keep your existing SDK and pass max_tokens per request exactly as you do today. That makes per-endpoint budgeting a configuration change rather than a migration. One API key and one balance cover multiple model families, so you can compare output-length distributions across providers without juggling credentials.
Start by routing a small slice of traffic through Admesh and logging the usage fields your SDK returns. Group the logs by endpoint and prompt template, then compute p50 and p95 output lengths. Use the model catalog at https://admesh.ai/models to confirm context limits before you raise a ceiling, and the pricing page at https://admesh.ai/pricing to estimate the cost of the headroom you are adding.
Then encode the budgets as per-endpoint config, deploy the truncation detection described above, and watch the truncation rate in the console at https://console.admesh.ai. If you need to switch model families because one is truncating or too slow at your ceiling, the same key and base URL let you do it behind a config flag. The docs at https://docs.admesh.ai cover the request shapes for both compatible endpoints.
Частые вопросы
Does a higher max_tokens always cost more?
How do I know a response was truncated?
Should input and output budgets use the same number?
How often should I revisit budgets?
Источники
Вызывайте эти модели через один шлюз
Admesh предоставляет единый API, совместимый с OpenAI: один Base URL и один ключ для Claude, GPT, DeepSeek и других моделей. Новым аккаунтам доступен пробный кредит без срока действия.
