Error database

BadRequestError 400: max_tokens: Field required (Anthropic)

The Anthropic Messages API requires max_tokens on every request — it is the cap on the reply's length. Pass a value sized for the response you expect.

The message you saw
BadRequestError 400: max_tokens: Field required (Anthropic)

By Updated

The error

Output
anthropic.BadRequestError: Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'max_tokens: Field required'}}

What it means

Anthropic's Messages API makes max_tokens mandatory: every request must state the maximum number of tokens the model may generate in its reply. OpenAI's API treats the equivalent as optional, so developers arriving from there omit it and hit this immediately. It is a required field, not a tuning knob you can skip.

Why it happens

The parameter caps output only — your input can be any size the context window allows. Requiring it makes cost and latency bounded by design: you cannot accidentally request an unbounded reply. The friction is one line.

How to fix it

1. Add the field.

python
import anthropic

client = anthropic.Anthropic()
resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain overfitting in two sentences."}],
)
print(resp.content[0].text)

2. Size it for the task, generously. A rough guide: short answers 256-512, normal chat 1024, long-form writing or code generation 4000+. The value is a ceiling, not a target — you are billed for tokens actually generated, so a generous cap costs nothing extra when replies are short.

3. Watch for silent truncation when the cap is too small. A reply that stops mid-sentence hit the ceiling. Check the stop reason:

python
print(resp.stop_reason)
Output
max_tokens

max_tokens as the stop reason means truncation; end_turn means the model finished naturally. Production code should treat unexpected max_tokens stops as a signal to raise the cap or shorten the task.

4. Remember what it does not do. It does not reserve space, does not shrink your bill for short answers, and does not interact with input length except through the shared context window. Setting it near the model's maximum is fine when you genuinely need long output.

How to prevent it

Wrap your Anthropic calls in one helper that always supplies max_tokens from configuration, with per-task overrides. Log stop_reason alongside responses — a rising rate of max_tokens stops is an early warning that your cap or your prompts need adjusting.