Reading the Response
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 4 of 22.
The reply is a Message object. Its content is a list of blocks, and every block has a type. A "text" block holds the answer in .text. When the model thinks first, a "thinking" block comes before it, so code that reads content[0].text breaks. Look for the block by its type instead:
for block in response.content:
if block.type == "text":
print(block.text)
print(response.stop_reason)
print(response.usage.input_tokens, response.usage.output_tokens)For What is the capital of Canada? this prints the answer, then end_turn, then 15 8.
stop_reason says why the model stopped: "end_turn" means it finished on its own. usage counts the tokens you sent (input_tokens) and the tokens it wrote (output_tokens), which is what you pay for. model and id name the model and the request, which helps when you log calls.
Challenge
EasyPrint everything a program needs from a reply. The starter already sends the question with high effort, so the model thinks first.
- Print
Blocks:and the type of every block inresponse.content, joined by a comma and a space. - Print
Answer:and the text of the text block. - Print
Stop:and the stop reason. - Print
Tokens: <input> in, <output> outwith the two counts fromusage.
For example, for the input What is the capital of Egypt? the program prints:
Blocks: thinking, text
Answer: The capital of Egypt is Cairo.
Stop: end_turn
Tokens: 15 in, 72 outTry it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
question = input()
# High effort makes the model think before it answers (the next chapter explains effort)
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
output_config={"effort": "high"},
messages=[{"role": "user", "content": question}],
)
# Print the block types, the answer, the stop reason and the token counts
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
1First Model Calls
Your First Model CallMessages and RolesSystem PromptsReading the ResponseRecap: Shop Help DeskPractice on your own: Online Python compiler