Menu
CoddyTech

Streaming Responses

Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 9 of 22.

A long answer can take many seconds to write. With create, your program waits for all of it. With streaming, the text arrives in small pieces as the model writes them, so a chat window can show words right away.

with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=200,
    messages=[{"role": "user", "content": "What is the largest ocean?"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    message = stream.get_final_message()
print()
print(message.stop_reason)

client.messages.stream takes the same arguments as create and is used in a with block. stream.text_stream yields the pieces of text. print(text, end="", flush=True) keeps them on one line and shows each one at once. After the loop, stream.get_final_message() returns the whole Message, with its stop_reason and usage. Streaming is also the safe choice for requests with a large max_tokens, which can take too long for one waiting call. The stand-in yields one token per piece; real pieces are often longer.

challenge icon

Challenge

Medium

Stream an answer and report on it. The starter reads the question.

  1. Print Answer: without a newline (end="").
  2. Stream the reply with model="claude-opus-5-5" and max_tokens=200. Print each piece of text on the same line and count the pieces.
  3. After the stream, get the final message and print an empty line to end the answer's line.
  4. Print Chunks: and the number of pieces, Stop: and the stop reason, Output tokens: and the output token count.

For example, for the input What is the capital of France? the program prints:

Answer: The capital of France is Paris.
Chunks: 8
Stop: end_turn
Output tokens: 8

Try it yourself

import coddy_ai as anthropic  # in production: import anthropic

client = anthropic.Anthropic()

question = input()

# Stream the answer after "Answer: ", then print the number of chunks,
# the stop reason and the output tokens of the final message
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