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
MediumStream an answer and report on it. The starter reads the question.
- Print
Answer:without a newline (end=""). - Stream the reply with
model="claude-opus-5-5"andmax_tokens=200. Print each piece of text on the same line and count the pieces. - After the stream, get the final message and print an empty line to end the answer's line.
- 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: 8Try 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
2Controlling the Output
Max Tokens and Stop ReasonsVaried AnswersEffort and ThinkingStreaming ResponsesRecap: Answer BudgetPractice on your own: Online Python compiler