What does the max_tokens parameter control in an LLM API call?
max_tokens caps the number of OUTPUT tokens the model will generate; it does not limit input length (the context window does that).
Imagine you ask a friend a question and add 'reply in at most 100 words'. That instruction does not say anything about how long your question was. You can ask a 5,000-word question with the same 100-word reply limit. max_tokens is that reply limit, except it counts tokens instead of words. Your input can be as long as the model's context window allows. The cap only applies to what the model writes back. If the model is mid-sentence when it hits the cap, it just stops, even mid-word. The reply will look truncated. The way to detect this is to check the finish_reason field in the response, which says 'length' when max_tokens fired.
Detailed answer & concept explanation~6 min readEverything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
6 min: define max_tokens as output-only cap, contrast with context window, walk through mid-sentence truncation, name finish_reason reporting, connect to cost and latency control.
Real products, models, and research that use this idea.
- OpenAI's chat completions API uses max_tokens (or max_completion_tokens on newer models) to cap reply length and reports finish_reason='length' when it fires.
- Anthropic's Claude messages API uses max_tokens as a required parameter (no default) and reports stop_reason='max_tokens' on the response when the cap is hit.
- Cursor and Cody log stop_reason for every code-completion call; a spike in length terminations triggers a prompt-template review.
- Production summarization pipelines set max_tokens proportional to expected summary length (often 200 to 500) rather than the model's maximum, both for cost and for forcing brevity.
What an interviewer would ask next. Try answering before peeking at the approach.
QWhat is the difference between max_tokens and max_completion_tokens in OpenAI's newer API, and why did they introduce the latter?
QHow does max_tokens interact with prompt caching for cost optimization?
Don't say thisRed flags and common mistakes that signal junior thinking. Click to expand.
Red flags and common mistakes that signal junior thinking. Click to expand.
Confusing max_tokens with the context-window limit; max_tokens caps the reply length only, the context window caps total input plus output.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.
Same topic, related formats. Practice these next.