Sub topic 7
Limit and shape the output
Output tokens usually cost several times more than input tokens, and they are produced one at a time. That makes output length the most direct lever on both cost and latency. This chapter assumes you know basic Python, have called a chat-style LLM API, and understand the tokens and latency chapters earlier in this tutorial: that output tokens are priced separately, and that decoding time grows with the number of tokens generated.
Why output length matters most
Prefill (processing the prompt) happens in parallel. Decoding does not. Each new token depends on the ones before it, so generation time grows roughly in proportion to output length. Cutting a 400-token answer to 100 tokens can cut decoding time by about three quarters. It also cuts the output share of the bill by the same proportion.
A simple model of total latency:
total latency ≈ queue + prefill + (output_tokens × time_per_output_token)Of these terms, only output tokens are fully under your control through the request itself.
Four tools for controlling output
Four mechanisms work together. Use them in layers, because each one fails in a different way.
| Tool | What it does | Typical failure |
|---|---|---|
| Length instructions in the prompt | Ask for a specific size or format | Model ignores or approximates it |
| `max_tokens` cap | Hard limit on generated tokens | Answer is cut off mid-sentence |
| Stop sequences | End generation at a marker string | Marker never appears, or appears too early |
| Structured output | Constrain the shape of the answer | Schema too loose, so fields are verbose |
Ask for the length you want
Models follow concrete instructions better than vague ones. "Be brief" is weak. These are stronger:
- "Answer in at most two sentences."
- "Return only the category name, nothing else."
- "List at most five bullet points, each under 12 words."
Models count words and sentences more reliably than tokens, so give limits in those units. Also tell the model what to leave out: preambles ("Sure, here is..."), restating the question, and closing summaries. These add tokens and no information.
Set `max_tokens` as a safety cap
max_tokens (named max_completion_tokens or similar by some providers) stops generation after N tokens. Treat it as a guard against runaway output, not as a way to get short answers. The model does not know the cap in advance, so it does not plan to fit inside it. It simply stops, often mid-sentence or mid-JSON.
Pick the cap from data. Measure the output token counts of real requests from your baseline, look at a high percentile such as p99, and set the cap a little above that. A cap far above typical output saves nothing. A cap below it truncates good answers.
Always check why generation ended. Most APIs return a finish reason. The exact name varies by provider, but common values mean "stopped naturally" and "hit the length limit."
def check_finish(finish_reason: str, text: str) -> str:
# "length" is the OpenAI-style value for hitting max_tokens.
# Other providers use different names, for example "max_tokens".
if finish_reason in ("length", "max_tokens"):
raise ValueError(f"Output truncated: {text[-40:]!r}")
return text
print(check_finish("stop", "The capital of France is Paris."))Silently accepting truncated output is a common bug. A truncated JSON object fails to parse. A truncated summary may leave out the key point and still look plausible.
Use stop sequences to end early
A stop sequence is a string that, once generated, ends the response. The stop string itself is normally not included in the output. Stop sequences help when the model tends to continue past the useful part, for example:
- A format that ends with a marker such as
ENDor###. - Few-shot prompts where the model might invent the next example (stop on
\nQ:). - Lists where you only want the first item or the first section.
Choose stop strings that cannot appear in a valid answer. If you stop on "\n\n" and the answer legitimately contains paragraphs, you will cut good output. Providers also limit how many stop sequences you can set, often to a handful.
Shape output with structure
Free-form prose is expensive. A structured format often says the same thing in fewer tokens, and it is easier to parse. Compare two ways to classify a support ticket:
- Prose: "This ticket appears to be about a billing issue, and I would classify it as high priority because the customer mentions a double charge."
- Structured:
{"category": "billing", "priority": "high"}
The second is shorter and can be validated by code. Structured output features (JSON mode or schema-constrained decoding, where available) also reduce retries caused by malformed output.
Structure has its own costs. Long field names are tokens too, and they repeat in every response. Prefer short, clear keys, and avoid asking for explanation fields you will never read. Also, constraining a model too hard can reduce quality on reasoning tasks. If you need the model to think before answering, that thinking costs tokens, so measure whether it pays for itself on your evaluation set.
import json
def parse_ticket(raw: str) -> dict:
data = json.loads(raw)
allowed_categories = {"billing", "technical", "account", "other"}
allowed_priorities = {"low", "medium", "high"}
if data.get("category") not in allowed_categories:
raise ValueError(f"bad category: {data.get('category')!r}")
if data.get("priority") not in allowed_priorities:
raise ValueError(f"bad priority: {data.get('priority')!r}")
return data
print(parse_ticket('{"category": "billing", "priority": "high"}'))Validating the result lets you detect when a shorter format has lost information.
Reasoning tokens and hidden output
Some models generate internal reasoning tokens before the visible answer. Providers usually bill these as output tokens even though you do not see them, and they count toward the output cap. Two consequences follow:
- A small
max_tokenscan be consumed entirely by reasoning, leaving an empty or truncated visible answer. - Cost per request can be much higher than the visible text suggests.
Check the usage fields in the response, which normally report reasoning tokens separately. If your provider offers a setting for reasoning effort or a thinking budget, lower it for simple tasks and measure quality again.
Common errors
- Setting the cap too low. Truncated answers break parsers. Fix: base the cap on a high percentile of measured output, and check the finish reason.
- Using the cap as the only control. The model still plans a long answer and gets cut off. Fix: also instruct the model on length.
- Over-trusting length instructions. Models drift, especially on long or open-ended tasks. Fix: enforce limits in code and log how often output exceeds the target.
- Stop sequences that match valid content. Output is cut early with no error. Fix: pick rare markers and test them against your evaluation set.
- Compressing too far. One-word answers can lose the nuance users need. Fix: compare quality scores before and after shortening, using the small evaluation set from the quality chapter.
- Ignoring streaming interactions. With streaming, truncation is visible to users as it happens. Check the final finish reason, not only that chunks arrived.
A worked check
Suppose your baseline shows an average of 350 output tokens per request, with output priced at $4.00 per million tokens. A prompt change and a cap reduce the average to 120 tokens.
OUTPUT_PRICE_PER_MTOK = 4.00 # placeholder USD per million output tokens
def output_cost(avg_tokens: int, requests: int) -> float:
return avg_tokens * requests * OUTPUT_PRICE_PER_MTOK / 1_000_000
before = output_cost(350, 1_000_000)
after = output_cost(120, 1_000_000)
print(f"before: ${before:,.2f}, after: ${after:,.2f}, saved: ${before - after:,.2f}")For one million requests, this prints a drop from $1,400.00 to $480.00. Decoding time falls by a similar fraction. Before you ship, rerun the evaluation set. A saving is only real if answers remain acceptable.
Summary
- Output tokens cost more and are generated sequentially, so shortening output helps both cost and latency.
- Combine length instructions, a data-driven
max_tokens, stop sequences, and compact structured formats. - Always inspect the finish reason and validate structured output.
- Account for hidden reasoning tokens.
- Verify every change against your evaluation set.
Exercise
Your service sets max_tokens to 50 to keep answers short, and the prompt does not mention length. Users report that some summaries end mid-sentence. Give two fixes, and name one check that would have caught the problem.
Show answer
Fix 1: add a concrete length instruction to the prompt (for example, "Summarize in at most two sentences") so the model plans a short answer instead of being cut off. Fix 2: raise maxtokens to a value based on a high percentile (such as p99) of measured output lengths for properly instructed answers. The check is to inspect the finish reason on each response and treat "length" or "maxtokens" as a truncation event, logging or alerting on its rate.
Exercise
A request returns 300 visible output tokens and the usage report shows 900 output tokens billed. With output priced at $4.00 per million tokens, what did the request cost, and what is the likely explanation?
Show answer
The cost is 900 × 4.00 / 1,000,000 = $0.0036. The likely explanation is hidden reasoning tokens (about 600) that the model generated before the visible answer. They are billed as output tokens. To reduce the cost, lower the reasoning effort or thinking budget for simple tasks and recheck quality.