Handling stop reasons
When you make a request to the Messages API, Claude’s response includes a stop_reason
field that indicates why the model stopped generating its response. Understanding these values is crucial for building robust applications that handle different response types appropriately.
For details about stop_reason
in the API response, see the Messages API reference.
What is stop_reason?
The stop_reason
field is part of every successful Messages API response. Unlike errors, which indicate failures in processing your request, stop_reason
tells you why Claude successfully completed its response generation.
Stop reason values
end_turn
The most common stop reason. Indicates Claude finished its response naturally.
max_tokens
Claude stopped because it reached the max_tokens
limit specified in your request.
stop_sequence
Claude encountered one of your custom stop sequences.
tool_use
Claude is calling a tool and expects you to execute it.
pause_turn
Used with server tools like web search when Claude needs to pause a long-running operation.
refusal
Claude refused to generate a response due to safety concerns.
Best practices for handling stop reasons
1. Always check stop_reason
Make it a habit to check the stop_reason
in your response handling logic:
2. Handle max_tokens gracefully
When a response is truncated due to token limits:
3. Implement retry logic for pause_turn
For server tools that may pause:
Stop reasons vs. errors
It’s important to distinguish between stop_reason
values and actual errors:
Stop reasons (successful responses)
- Part of the response body
- Indicate why generation stopped normally
- Response contains valid content
Errors (failed requests)
- HTTP status codes 4xx or 5xx
- Indicate request processing failures
- Response contains error details
Streaming considerations
When using streaming, stop_reason
is:
null
in the initialmessage_start
event- Provided in the
message_delta
event - Non-null in all other events
Common patterns
Handling tool use workflows
Ensuring complete responses
By properly handling stop_reason
values, you can build more robust applications that gracefully handle different response scenarios and provide better user experiences.