Q&A-7Diagnose and fix generation truncation.
Answer
The 90-second answer. Truncation is almost always one of three things, and the finish reason tells you which. If finish_reason is "length" (Anthropic: stop_reason: "max_tokens"), the model hit your output cap. The prompt fit, the answer didn't. If it's "stop" but the text looks cut, a stop sequence fired early. If there's no finish reason at all, the stream was cancelled or the connection dropped. So: read the finish reason, do the arithmetic on the token budget, then decide whether to reserve more output, shrink the input, or chunk.
The arithmetic. The context window is shared between prompt and completion. On gpt-4o that's 128,000 tokens with a 16,384 max output; the docs page for the model you're actually calling is the only source to trust for both numbers. Exceeding the window is not truncation: it's a 400 invalid_request_error. Truncation is when prompt + max_tokens ≤ window but the model runs out of output budget.
Worked example: the prompt encodes to 118,000 tokens and you left max_tokens at 16,384. 118,000 + 16,384 = 134,384 > 128,000, so the request is rejected outright. Drop max_tokens to 9,488 and it succeeds, but a 12,000-token answer now truncates at 9,488 with finish_reason: "length". That is the trade you are actually making.
Counting. Don't estimate with characters/4. Use the model's tokenizer: tiktoken.encoding_for_model("gpt-4o") gives o200k_base; Anthropic exposes client.messages.count_tokens. Chat framing is not free: OpenAI's token-counting cookbook puts it at ~3 tokens per message plus 3 for the reply priming, so a 20-message history costs ~63 tokens before any content.
import tiktoken
from openai import OpenAI
enc = tiktoken.encoding_for_model("gpt-4o") # o200k_base
CONTEXT, RESERVE, MARGIN = 128_000, 16_384, 512
prompt_tokens = len(enc.encode(prompt)) + 3 * len(messages) + 3
budget = CONTEXT - prompt_tokens - MARGIN
max_tokens = min(RESERVE, budget)
if max_tokens < 1024:
raise ValueError(f"no room: prompt={prompt_tokens}") # shrink input instead
resp = client.chat.completions.create(
model="gpt-4o", messages=messages,
max_tokens=max_tokens, temperature=0,
)
if resp.choices[0].finish_reason == "length":
log.warning("truncated", extra={"completion_tokens": resp.usage.completion_tokens})Trace with prompt_tokens = 118,000: budget = 128,000 − 118,000 − 512 = 9,488; max_tokens = min(16,384, 9,488) = 9,488. With prompt_tokens = 127,600: budget = −112, the guard raises, and you must reduce input rather than reserve output.
Choosing between the three fixes.
| fix | use when | cost |
|---|---|---|
| reserve output | prompt near the window, answer genuinely short | caps long answers; truncates silently |
| reduce/select input | prompt is mostly irrelevant context | retrieval latency; risk of dropping the span that mattered |
| chunk (map-reduce) | input exceeds the window outright | N calls, N× tokens, merge step loses cross-chunk coherence |
Failure modes and how you see them.
finish_reason: "length": output cap. Detect: the field itself, orcompletion_tokens == max_tokens.finish_reason: "stop"with visibly cut text: a stop sequence fired. Detect: log the stop list and check whether the tail matches one.- No finish reason, no usage: stream cancelled, client timeout, or dropped connection. Detect:
stream_options={"include_usage": True}puts usage in the final chunk; if it never arrives, the stream was cut. - Truncated JSON:
json.loadsraises. Fix structurally: strict JSON-schema structured outputs or tool calling, which guarantee parseable output instead of hoping.
Retry. At temperature 0, retrying with identical parameters reproduces the truncation exactly: that's a loop, not a fix. Retry only after changing max_tokens or the input, and only when the call is idempotent (no tool side effects). Track the finish_reason == "length" rate per model and task; a sustained rate above ~1% means your budget is wrong, not that the model is flaky.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.