Max Tokens and Stop Reasons
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 6 of 22.
max_tokens is a hard limit. When the reply reaches it, the model stops in the middle of a word and stop_reason is "max_tokens":
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=5,
messages=[{"role": "user", "content": "What is the largest planet?"}],
)
print(response.content[0].text)
print(response.stop_reason)This prints Jupiter is the larges and max_tokens. The model does not know the limit while it writes, so it never shortens its answer to fit. Check the stop reason before you trust the text: show a warning, or ask again with a higher limit.
stop_sequences is a list of strings that end the reply early. The text stops before the first one found, stop_reason is "stop_sequence" and stop_sequence holds the string that matched. With stop_sequences=[","], the question about the tallest mountain returns Mount Everest is the tallest mountain above sea level.
Challenge
EasyWrite a program that notices when an answer was cut short.
- The starter reads a question and a token limit into
limit. - Send the question with
model="claude-opus-5-5"andmax_tokens=limit. - Print
Answer:and the reply text, thenStop:and the stop reason. - Only when the stop reason is
max_tokens, printNote: the answer was cut short.
For example, for the input What is the capital of Japan? and 4 the program prints:
Answer: The capital of
Stop: max_tokens
Note: the answer was cut short.With a limit of 100 the answer is whole, the stop reason is end_turn and there is no note.
Try it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
question = input()
limit = int(input())
# Send the question with max_tokens=limit, print the answer and the stop reason,
# and print the note when the answer was cut short
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
2Controlling the Output
Max Tokens and Stop ReasonsVaried AnswersEffort and ThinkingStreaming ResponsesRecap: Answer BudgetPractice on your own: Online Python compiler