New Tool Radar

AI Concepts

How to Set Max Tokens to Cap Answer Length and Cost

Set max_tokens to the answer length you need, check the answer is not cut off, and keep the cost predictable.

Schematic with three steps: Set max_tokens to the length you need; Generate and check the answer is complete; Raise only if truncation appears.

Max tokens caps the length of the generated output, and it is a hard limit on the length of the answer. It is also a cost control: cost is per input and output token, so an uncapped answer can run long and cost more than the task is worth. The documented advice is to always set it. The check is that the answer is complete at the cap you chose, not cut off mid-sentence.

What you need

  • The answer length your task needs, in tokens
  • The model context window, so the cap fits inside it
  • A note of the cost per output token

Step 1: Set max_tokens to the length you need

Set max_tokens to the number of output tokens the answer needs, plus a small margin. Always set it; it caps cost as well as length.

Step 2: Generate and check the answer is complete

Generate the answer and check it ends cleanly. If it stops mid-sentence or mid-list, the cap is too low for the task.

Step 3: Raise only if truncation appears

Raise the cap only when you see truncation, and re-check the cost. A cap that is far above what the task needs wastes nothing by itself, but it removes the protection against a runaway answer.

Worked example: synthetic max_tokens test

The table below is a synthetic example. It shows the expected result of a max_tokens test; no API call was made.

Max tokens Answer Result
50 Cut off mid-sentence Too low
200 Complete answer Pass
500 Complete answer Pass, but no cap protection
Choice 200 Complete and capped

Expected result (UNTESTED). 50 tokens cut the answer off mid-sentence, 200 tokens complete it, and 200 is picked as the cap. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Max tokens is a hard limit on the length of the answer; a cut answer looks like an error, so check completeness.
  • The maximum output is bounded by the context window minus the prompt length; the prompt and the answer share the window.
  • Always set max_tokens; it caps cost.
  • A generous cap does not make the model write more; it only removes the ceiling, so set the cap to what the task needs.

Sources

See all