Loading

Stream Claude's replies into your app

Stream Claude's replies from the Messages API so your users can start reading while Claude is still writing.

10 minClaude Platform

Streaming lets your user start reading a reply while Claude is still writing. The reply reaches your app a few words at a time, and your app can show the words as they arrive.

If you save text as it arrives, you can resume the reply after an interruption.

Suppose your app answers questions about networking. Your app sends a user's question with client.messages.create(): "Explain what a load balancer does, in three short paragraphs." The call returns once Claude has written the whole reply, so your app shows a spinner until then. That wait can last several seconds.

In the animation below, streaming shows the first words in less than half the time that client.messages.create() takes to return. The exact timing varies from request to request.

Loading

To stream a reply, ask the API for a stream, then show the text as it arrives. These two steps work the same way in any language, and the examples on this page use the Python SDK:

  1. Ask for a stream. In Python, call client.messages.stream() with the same arguments you gave client.messages.create(), inside a with block.
  2. Show the text as it arrives. In Python, loop over stream.text_stream, which gives you the reply a few words at a time.

Here is the Python code for both steps. client reads your API key from the ANTHROPIC_API_KEY environment variable, and question holds the user's question:

python
import anthropic

client = anthropic.Anthropic()
question = (
    "Explain what a load balancer does, "
    "in three short paragraphs."
)

with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": question}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Each time through the loop, text holds the next few words of Claude's reply. The print call on the last line shows those words and has two extra arguments. end="" leaves out the newline after text, so the words join up into one reply. flush=True puts the words on screen right away. In your app, you can replace print with the call that puts text on your user's screen.

See what a stream is made of

A streamed reply reaches your app as a series of events, and only some of those events carry text. The other events describe the reply, such as where it starts, where it ends, and why Claude stopped. The events of each reply come in this order:

  1. The reply begins with message_start, and its content is still empty.
  2. A content block begins with content_block_start. A content block holds one kind of content in the reply, such as text.
  3. The text of a text block arrives a few words at a time, in one or more content_block_delta events.
  4. The content block ends with content_block_stop. If the reply has another content block, that block begins and ends the same way.
  5. Details about the whole reply, such as the stop reason and the token count, arrive in one or more message_delta events.
  6. The reply ends with message_stop. Once message_stop arrives, you have everything Claude sent.

stream.text_stream reads all of these events and gives your code only the text. The text in one content_block_delta event can end partway through a word.

A row of 35 marks, one for each event of a streamed reply, labeled with the event names. It opens with a tall dark bar, message_start, then a gray bar, content_block_start. Next come 30 short highlighted marks, the content_block_delta events. It closes with three bars: content_block_stop in gray, then message_delta and a tall message_stop in dark. A shaded band, labeled as the text that goes to the screen, leads from the highlighted marks alone down to a screen that is filling with lines of text.

Each mark is one event of a streamed reply, in order from left to right.

The last event, message_stop, tells you the stream is over. To learn why Claude stopped writing, your code can read the reply's stop_reason from stream.get_final_message() once the loop ends.

One reason Claude could stop is length. The max_tokens value in your request limits how long a reply can be. A reply that reaches that limit also ends with message_stop, even though the reply is incomplete.

On Claude Opus 5.5, max_tokens also covers any thinking Claude does before it answers. So the value needs room for both the thinking and the reply.

Quick check

Your app logs the events of a streamed reply, and the last event in the log is "content_block_stop". Can your app treat the reply as complete?

What to do if a stream breaks

Occasionally, a stream is interrupted before the reply is complete, so it's worth having a plan for that possibility. A stream can be interrupted for a few reasons. The connection might drop, or the API might send an error event during periods of high usage.

You can choose what your user sees after an interruption. If you save the reply's text as it arrives, your app can keep that text on screen and ask Claude to finish the reply.

Planning for an interruption takes two steps, in any language:

  1. Save the text as it arrives. In the code below, the loop adds text to a variable named partial.
  2. Catch the errors that an interruption raises. In the code below, the stream goes inside a try block.

Here is the Python code for both steps. The ... stands for the model, max_tokens, and messages arguments from the first example:

python
import httpx2

partial = ""

try:
    with client.messages.stream(...) as stream:
        for text in stream.text_stream:
            partial += text
            print(text, end="", flush=True)
except (anthropic.APIError, httpx2.TransportError) as error:
    print(f"\n[interrupted: {error}]")

The except line catches the two errors that an interruption can raise:

  • anthropic.APIError comes from an error event, or from a request that fails before streaming starts.
  • httpx2.TransportError comes from a dropped connection. The httpx2 library installs with version 1.0 and later of the SDK, and earlier versions use httpx instead.

Your code needs to catch these errors because the HTTP status won't show an interruption. The API returns a 200 success status as soon as a stream starts, before any text arrives.

A stream can also end without an error and still leave the reply incomplete. After the loop, the reply's stop_reason tells your app what happened. These four values matter most here:

  • end_turn means Claude finished the reply.
  • max_tokens means the reply reached your length limit and is incomplete.
  • refusal means Claude declined to respond, so your app should discard the text and clear it from the screen.
  • None means the stream ended early, so your app should treat it as an interruption.

The full script later on this page handles all four of these values.

Quick check

Your app looks only at the HTTP status to decide whether a streamed reply succeeded. The connection drops halfway through a reply. Will your app notice the interruption?

How to resume a reply

To resume an interrupted reply, send Claude the text you saved and ask Claude to continue. The process has four steps:

  1. Keep the text that arrived before the interruption.
  2. Send a new request with two user messages. The first message holds the user's original question. The second message holds the saved text and asks Claude to continue.
  3. Stream the rest of the reply.
  4. Join the saved text and the resumed text into one reply.

How you join the two texts depends on where the interruption fell. Between two words, the texts need a space. Inside a word, a space would split the word.

Two examples of joining saved text and resumed text. In the first, the stream was interrupted between two words. The saved text ends with appears as, the resumed text begins with a single, and adding a space gives appears as a single. In the second, the stream was interrupted inside a word. The saved text ends with and distri, the resumed text begins with butes, and adding nothing gives and distributes.

The right join depends on where the interruption fell.

Quick check

A stream is interrupted after the text "take the cab". Your app resumes the reply, and the resumed text begins with "le car up the hill". How should your app join the saved text and the resumed text?

To avoid guessing whether to add a space, your app can remove the last word of the saved text before it resumes. The saved text then ends with a whole word. Your app can put back the space that came after that word, unless the resumed text starts with a space or punctuation. This approach works in languages that put spaces between words.

The removed word is still on your user's screen, and Claude may continue with that word or a different one. So your app should replace the text on screen with the joined reply.

See the full script

This script interrupts the stream on purpose after 300 characters, resumes the reply, and prints the joined reply. The variable names are only examples, and the comments say what each one holds:

python
import anthropic
import httpx2


class Interrupted(Exception):
    """An error this script raises itself."""


client = anthropic.Anthropic()
question = (
    "Explain what a load balancer does, "
    "in three short paragraphs."
)
partial = ""  # text that arrived before an interruption

try:
    with client.messages.stream(
        model="claude-opus-5-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": question}],
    ) as stream:
        for text in stream.text_stream:
            partial += text
            print(text, end="", flush=True)
            # Remove the next two lines in your app.
            if len(partial) > 300:
                raise Interrupted("on purpose")
        final = stream.get_final_message()
        if final.stop_reason is None:
            raise Interrupted("ended early")
except (
    anthropic.APIError,
    httpx2.TransportError,
    Interrupted,
) as error:
    # With one word or less, there is nothing to resume.
    parts = partial.rsplit(maxsplit=1)
    if len(parts) < 2:
        raise
    print(f"\n[interrupted: {error}]")

    # saved: the text without its last word
    # gap: the space or line break before that word
    saved, last = parts
    gap = partial.rstrip()[len(saved) : -len(last)]

    with client.messages.stream(
        model="claude-opus-5-5",
        max_tokens=1024,
        messages=[
            {"role": "user", "content": question},
            {
                "role": "user",
                "content": (
                    "Your previous response "
                    "was interrupted and ended with "
                    f"{saved} Continue from where "
                    "you left off."
                ),
            },
        ],
    ) as stream:
        rest = ""  # the resumed text
        for text in stream.text_stream:
            rest += text
            print(text, end="", flush=True)
        end = stream.get_final_message().stop_reason
        if end != "end_turn":
            raise RuntimeError(f"incomplete: {end}")

    if not rest:
        reply = partial
    elif rest[0].isspace() or rest[0] in ".,;:!?)":
        reply = saved + rest
    else:
        reply = saved + gap + rest
else:
    if final.stop_reason != "end_turn":
        print(f"\n[incomplete: {final.stop_reason}]")
    refused = final.stop_reason == "refusal"
    reply = "" if refused else partial

# Redraw your user's screen from reply.
print(f"\n\n[reply]\n{reply}")

If the script can't resume the reply, or the resumed stream doesn't finish, the script stops with an error. Your app can then offer to send the user's question again. After a refusal, your app should also clear the text from the screen.

Keep three things in mind when you adapt the script:

  • In a longer chat, the new request also needs the earlier messages.
  • The resumed text can sometimes repeat a phrase, so it's worth testing with your users' kinds of questions.
  • Resuming this way works for text only, on Claude 4.6 and later models. For earlier models, see error recovery in the streaming docs.

Try interrupting a stream

In the explorer below, you can send a question and interrupt the reply while it streams. You can then choose what your code sends next and how it joins the saved and resumed text, and see what your user sees. As in the script, partial is the text that arrived before the interruption, and rest is the resumed text.

Loading

Where to go next

You can now stream Claude's replies so your users start reading sooner, and resume a reply if a stream is interrupted. A good next step is to pick a request in your own app where users wait for a long reply, and stream that reply.

You can also stream tool calls when your app gives Claude tools. The lesson "Streaming tool calls: No more frozen spinners," in the course Tool use with the Messages API, shows how.