Study FAQ
How should I parse a Claude Messages response and handle its stop reason?
Also asked as 2
- How do I read Claude content blocks, stop_reason, and usage safely?
- Why might a successful Claude Messages response still require more work?
Answer
Read the Messages response as an ordered collection of typed content blocks plus metadata. Inspect stop_reason before accepting the output. HTTP success establishes that the service returned a Message, and application validation still decides whether the content is usable.
- Iterate over all blocks in order. Map supported block types to internal types, and surface unsupported required content as an explicit unsupported result. Reading only
content[0]can miss text or a tool request later in the response. - For
end_turn, validate the candidate, including any requirement for nonempty content. Forstop_sequence, inspect which stop sequence fired and check that the resulting output is complete for your contract. - Treat
max_tokensandmodel_context_window_exceededas truncation. Mark the result incomplete and choose an allowed continuation or a corrected request if appropriate. - For
tool_use, route the typed request to the appropriate tool handler, which owns validation and authorization for client-executed tools. Forpause_turn, follow the documented server-tool continuation. Forrefusal, use the refusal path defined by your application's policy.
Preserve the response model, Message ID, request ID when available, stop metadata, and usage counters for diagnosis and accounting. Validate the application's expected fields, semantics, and authority before storing results or causing side effects.
Official references
Full explanation
Claude Messages API and SDK Integration Foundations
Study guide · CCDV-F
Read the full explanation