Menu
CoddyTech

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 icon

Challenge

Easy

Print everything a program needs from a reply. The starter already sends the question with high effort, so the model thinks first.

  1. Print Blocks: and the type of every block in response.content, joined by a comma and a space.
  2. Print Answer: and the text of the text block.
  3. Print Stop: and the stop reason.
  4. Print Tokens: <input> in, <output> out with the two counts from usage.

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 out

Try 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Calling Models From Code

Practice on your own: Online Python compiler