# Max Tokens

> The Max Tokens is a parameter that limits the length of a response generated by a language model.

## What does max tokens do in an LLM API?

The parameter that sets the maximum number of tokens the model may generate in a response. When the limit is reached, the answer is cut off, so it must be large enough for the expected output and the reasoning of the model.

- Topic: Generation Settings
- Type: concept

## Example

Wrong:

```js
const res = await llm.generate({ prompt, max_tokens: 200 });
const data = JSON.parse(res.text);
```

Right:

```js
const res = await llm.generate({ prompt, max_tokens: 2000 });
if (res.stopReason === 'max_tokens') {
  throw new Error('Response was cut off by the token limit');
}
const data = JSON.parse(res.text);
```

Checking the stop reason catches truncated output before `JSON.parse` fails on missing closing brackets.

## Common mistakes

- Parsing JSON from a response that was cut off by the token limit.
- Thinking max tokens limits the input, when it only limits the output.

## Key points

- The code checks the stop reason and handles a response cut off by the token limit.
- The limit leaves room for the full answer, including tool calls or JSON closing brackets.
- For reasoning models, the limit also covers thinking tokens where the API counts them.

## Interview questions

### Does max tokens include the prompt?

Usually no. It caps only the generated output, but the prompt plus the output must still fit in the context window.

### Does a higher max tokens make answers longer?

No. It is only a ceiling, and the model stops when it is done. Ask for the length you want in the prompt.

### Am I billed for the full max tokens limit?

Normally no. Billing counts the tokens actually generated, not the limit you set.

## Related cards

- [Context Window](https://wonderium.dev/ai/context-window.md)
- [Token](https://wonderium.dev/ai/token.md)
- [Stop Sequences](https://wonderium.dev/ai/stop-sequences.md)
- [Token Cost](https://wonderium.dev/ai/token-cost.md)
- [Structured Output](https://wonderium.dev/ai/structured-output.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/max-tokens
- Last updated: 2026-11-25
