Read the Response
The model answers with a JSON object, and the SDK hands it back as a response with a content list, a stop_reason, and a usage block. The important surprise for beginners: content is a list of blocks, not a single string. Most replies are one text block, but a reply can carry several blocks (for example a bit of text, then a tool request), so you cannot assume the answer is always at index zero.
In real code you reach into it like this (illustrative only):
resp = client.messages.create(model="claude-sonnet-4-6", max_tokens=1024,
messages=[{"role": "user", "content": "Hi"}])
print(resp.content[0].text) # the first block's text
print(resp.stop_reason) # "end_turn", "max_tokens", "tool_use", ...
print(resp.usage.input_tokens, resp.usage.output_tokens)Reaching for content[0].text works for the simple case, but it crashes if the first block is not text (say it is a tool_use block). The robust move is to walk every block and concatenate the ones that are actually text. We model that response JSON as a plain dict so it runs offline:
{
"content": [{"type": "text", "text": "Hello there."}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 12, "output_tokens": 5}
}You are building get_text(resp). Walk resp["content"] and join the text of every block whose type is "text", in order. Skip any block whose type is not "text" (a tool_use block has no text for the user). If content is empty or missing, return the empty string "" -> a clean, safe default rather than a crash.
Build it so a single-block response returns just that text, a multi-block response returns the text blocks joined in order, a non-text block is skipped, and an empty or missing content returns "".
Write get_text(resp) where resp models the API response {"content": [ {"type": "text", "text": ...}, ... ], "stop_reason": ..., "usage": {...}}. Concatenate, in order, the text of every block whose type == "text", skipping any other block type (like tool_use). Return "" when content is empty or missing.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.