Reading the API Response Shape
Explore the structure of Claude's API response including key fields like stop_reason and content blocks. Understand how each response type affects the agent loop's next step, enabling accurate control flow decisions in production AI systems.
In the last lesson, we traced a full conversation and noted that stop_reason drives every branching decision in the agent loop. Now we slow down and read the response envelope carefully: what each top-level field contains, all four stop_reason values, what the loop must do for each one, and what the content array can hold beyond a simple text reply.
By the end of this lesson, we will be able to read any API response and immediately know what the loop should do next.
The full response envelope
Every call to client.messages.create() returns an object with the same top-level shape, regardless of whether Claude replied with text, requested a tool, or stopped unexpectedly:
{"id": "msg_01XYZabc","type": "message","role": "assistant","model": "claude-opus-4-8","content": [...],"stop_reason": "end_turn","stop_sequence": None,"usage": {"input_tokens": 120,"output_tokens": 44}}
Line 2:
"id"is a unique identifier for this response object. Log it on every call; it is the only stable reference for correlating a request to its response when debugging multi-turn failures.Line 3:
"type"is always"message"for the Messages API. It exists to distinguish responses from other future object types that the API may introduce.Line 4:
"role"is always"assistant". When we append this response to the messages array, we use this value as therolekey.Line 5:
"model"echoes back the model that actually handled the request. In production systems, this is useful for confirming routing when multiple models are in play.Line 6:
"content"is an array of content blocks. We will dissect the full range of block types in the next section.Line 7:
"stop_reason"tells the loop why Claude stopped generating. This single field drives every branching decision in the agent loop. We will cover all four possible values in detail below.Line 8:
"stop_sequence"contains the stop sequence string that triggered the stop ifstop_reasonis"stop_sequence". It isNonefor all other stop reasons.Line 9:
"usage"contains the token counts for this round trip.input_tokensis the size of the full messages array we sent.output_tokensis the size of Claudes response. Together, they tell us how quickly the context window is filling up. ...