Skip to content
Academy ofAI Learning

~/academy $ claude learn streaming-responses

Streaming Claude responses

Why and how to stream Claude API responses with the Python SDK, what the server-sent events look like, and when a plain request is fine. 6 min

Watch it done: stream a Claude response as it is written

$

Step 1 of 6

Start from the same setup as your first API call: the SDK installed in a virtual environment and your own key in this variable.

  1. Start from the same setup as your first API call: the SDK installed in a virtual environment and your own key in this variable. Type: export ANTHROPIC_API_KEY="your-api-key-here".
  2. Create stream.py. messages.stream opens the stream, and text_stream hands you each new piece of text as soon as it arrives. Create stream.py containing: import anthropic client = anthropic.Anthropic() with client.messages.stream( model="claude-opus-5-5", max_tokens=4096, messages=[{"role": "user", "content": "Draft a welcome email for new members."}], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) print()
  3. Run it and watch the text build up. This is what makes a chat window feel quick. Type: python stream.py. the email appears a few words at a time instead of all at once at the end.
  4. For long output nobody watches, stream anyway and call get_final_message. It returns the same complete Message that messages.create would, without the timeout risk. Create long_report.py containing: import anthropic client = anthropic.Anthropic() with client.messages.stream( model="claude-opus-5-5", max_tokens=64000, messages=[{"role": "user", "content": "Write a detailed onboarding guide for a new office manager."}], ) as stream: message = stream.get_final_message() for block in message.content: if block.type == "text": print(block.text) print(message.stop_reason, message.usage.output_tokens)
  5. Run it. The SDK refuses a non-streaming request it expects to take longer than about 10 minutes, so large max_tokens values need streaming. Type: python long_report.py. prints the finished guide, then the stop reason and how many output tokens it used.
  6. See what the SDK handles for you by asking for a raw stream with curl and "stream": true. Type: curl https://api.anthropic.com/v1/messages -H "anthropic-version: 2026-10-21" -H "content-type: application/json" -H "Authorization: Bearer $ANTHROPIC_API_KEY" -d '{"model": "claude-opus-5-5", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 256, "stream": true}'. the reply arrives as events in this order: message_start, content_block_start, content_block_delta events carrying text_delta pieces, content_block_stop, message_delta with the stop reason and usage, then message_stop. ping events can appear in between.

Code from the official Claude API streaming docs and Python SDK docs, checked 18 November 2026. The key shown is a placeholder. Lines marked Note describe what happens and are not real output.

Step 1 of 6

$ Read

Why stream

A normal request returns nothing until Claude has finished. For a long answer that can be a long, silent wait. Streaming sends the response as server-sent events while it is being written, so your interface can show text immediately.

Streaming also keeps long requests alive. The Python SDK raises an error if a non-streaming request is expected to take longer than about 10 minutes, and the docs recommend streaming for any large max_tokens. Current models can write up to 128K tokens in one response, and the SDK needs streaming for values that large.

Lesson notes: Streaming Claude responses

Everything in this lesson as text, for revision or to read without the interactive steps. By the end you will be able to: You stream text to users as it is written and use the SDK helper to collect long responses without timeouts.

  1. Step 1 of 6 · Read

    Why stream

    A normal request returns nothing until Claude has finished. For a long answer that can be a long, silent wait. Streaming sends the response as server-sent events while it is being written, so your interface can show text immediately.

    Streaming also keeps long requests alive. The Python SDK raises an error if a non-streaming request is expected to take longer than about 10 minutes, and the docs recommend streaming for any large max_tokens. Current models can write up to 128K tokens in one response, and the SDK needs streaming for values that large.

  2. Step 2 of 6 · Read

    The SDK helpers

    client.messages.stream(...) is a context manager. Loop over stream.text_stream to get text as it arrives. When you only want the finished result but need streaming to avoid a timeout, call stream.get_final_message(): it returns the same complete Message object that messages.create would.

    You can also pass stream=True to messages.create. That gives you the raw events and uses less memory, but you have to assemble the message yourself.

    Show text as it is written
    import anthropic
    
    client = anthropic.Anthropic()
    
    with client.messages.stream(
        model="claude-opus-5-5",
        max_tokens=4096,
        messages=[{"role": "user", "content": "Draft a welcome email for new members."}],
    ) as stream:
        for text in stream.text_stream:
            print(text, end="", flush=True)
    Long output, no progress needed
    with client.messages.stream(
        model="claude-opus-5-5",
        max_tokens=64000,
        messages=[{"role": "user", "content": "Write a detailed migration plan..."}],
    ) as stream:
        message = stream.get_final_message()
    
    print(message.usage.output_tokens)
  3. Step 3 of 6 · Read

    What arrives on the wire

    Each stream follows the same order: message_start, then for each content block a content_block_start, some content_block_delta events and a content_block_stop, then one or more message_delta events (which carry stop_reason and usage) and a final message_stop. ping events can appear anywhere.

    Text arrives as text_delta, tool inputs as input_json_delta (partial JSON you only parse once the block stops) and thinking as thinking_delta. Usage counts in message_delta are cumulative. An error can arrive mid-stream after a 200 response, for example an overloaded_error, so handle error events, and ignore event types you do not recognise because new ones can be added.

    Raw stream with curl
    curl https://api.anthropic.com/v1/messages \
      -H "content-type: application/json" \
      -H "Authorization: Bearer $ANTHROPIC_API_KEY" \
      -H "anthropic-version: 2026-10-21" \
      -d '{
        "model": "claude-opus-5-5",
        "max_tokens": 256,
        "stream": true,
        "messages": [{"role": "user", "content": "Hello"}]
      }'
  4. Step 4 of 6 · Quiz

    Check your understanding

    A nightly job asks Claude for a 60,000-token report. Nobody watches it run, but the request keeps timing out. What is the simplest fix?

    • Use `client.messages.stream(...)` and call `get_final_message()`.
    • Lower `max_tokens` to 4,000.
    • Set `temperature` lower so it writes faster.
    Show the answer

    Use `client.messages.stream(...)` and call `get_final_message()`. The stream keeps the connection alive, and the helper hands you the complete Message object, so the rest of your code does not change.

  5. Step 5 of 6 · Sort

    Stream it or not?

    Decide whether each feature should stream its response.

    • A chat window where a customer waits for the answer
    • A one-word sentiment label with max_tokens of 256
    • Generating a long report with max_tokens of 64,000
    • A quick yes or no check inside a backend job
    • A voice assistant that starts speaking as the answer forms
    • Pulling three fields from a short form
    Show the answers
    • A chat window where a customer waits for the answer: Stream it. People see text immediately instead of a spinner.
    • A one-word sentiment label with max_tokens of 256: A plain request is fine. The answer is tiny and arrives quickly anyway.
    • Generating a long report with max_tokens of 64,000: Stream it. Large outputs need streaming to avoid HTTP timeouts.
    • A quick yes or no check inside a backend job: A plain request is fine. Short, nobody watching, nothing to gain.
    • A voice assistant that starts speaking as the answer forms: Stream it. It needs text as soon as it exists.
    • Pulling three fields from a short form: A plain request is fine. A small, fast response. A plain call is simpler.
  6. Step 6 of 6 · Quiz

    Check your understanding

    Your streamed answers from `claude-opus-5-5` start with a long pause before any text appears. Why?

    • Streaming is broken for Opus models.
    • The model is thinking first, and on current models thinking text is omitted by default, so nothing visible streams until the answer starts.
    • Your max_tokens is too high.
    Show the answer

    The model is thinking first, and on current models thinking text is omitted by default, so nothing visible streams until the answer starts. Thinking is always on for Opus 5.5 and `display` defaults to `omitted`. Set `thinking={"type": "adaptive", "display": "summarized"}` to stream a summary of the reasoning, or lower effort for faster starts.