Streaming responses

Claude API · Essentials · 8 min

Streaming makes apps feel fast and is required in practice for very long responses.

Without streaming, your program waits until Claude has written the entire answer, then gets it all at once. For a long answer that can mean many seconds of a blank screen. Streaming sends the answer in small pieces as it is produced, the way a chat app shows words appearing.

The Python SDK gives you a helper, client.messages.stream(...), used with a with block. Inside, stream.text_stream yields each new piece of text; print it with end="" and flush=True so it appears immediately. After the loop, stream.get_final_message() returns the complete message object, the same shape as messages.create returns, including stop_reason and usage.

Under the hood the API sends server-sent events: a stream of named events such as message_start, content_block_delta (a new piece of text) and message_stop. The helper handles them for you; you only need the raw events for custom UIs.

Streaming also matters for reliability. Very long requests (large max_tokens) can run past HTTP timeouts, and the SDK refuses non-streaming requests that it expects to take more than about ten minutes. Using stream(...) plus get_final_message() avoids that even when you do not display text live.

Errors can arrive in the middle of a stream (for example an overload), so be ready to keep what you received and ask Claude to continue.

Example

import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=800,
    messages=[{"role": "user", "content": "Write a short poem about rain."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)   # appears word by word
    final = stream.get_final_message()

print()
print(final.stop_reason, final.usage.output_tokens)

Remember

  • messages.stream() + text_stream shows text as it arrives
  • get_final_message() gives the complete message afterwards
  • Stream long requests to avoid HTTP timeouts

Watch out for

  • Forgetting flush=True, so nothing appears until the buffer fills.

Check yourself

  1. You don't need live text but your request has a very large max_tokens. What should you do?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: platform.claude.com/docs/en/build-with-claude/streaming

Builds on

Unlocks

Nothing builds on this yet.