How to stream Claude API responses and read the stop reason

Day 6, 25 minutes · beginner

Goal of this lessonStream a Claude reply word by word, read the events of a stream, and spot a reply that max_tokens cut off.

Why it matters

Until now your scripts sat silent until the whole reply was ready. For a two-line answer that is fine. For a longer one it feels broken, and for a very long one the request can even time out before anything comes back.

Streaming fixes both: Claude's reply arrives in small pieces while it is being written, the way you see it in the Claude app. Today you stream Linde's review replies, look at what a stream is made of, and learn the field that tells you whether a reply is complete. At the end you have a streaming reply script that also tells you when a reply was cut off.

What streaming is

A stream is a response that comes in pieces over one open connection, instead of in one go at the end. The Claude API uses server-sent events for this: the server sends a series of small named messages, called events, until it is done.

Why bother:

  • People see progress. Text that appears straight away feels fast, even when the full reply takes the same time.
  • Long replies need it. The Python SDK docs advise streaming for long requests, and the SDK refuses a request without streaming when it expects it to take longer than about 10 minutes. Some networks also drop a connection that stays quiet too long.

The events in a stream

The streaming page lists the order:

  1. message_start: a message with empty content.
  2. For each content block: content_block_start, then any number of content_block_delta events with the next piece of text, then content_block_stop.
  3. message_delta: changes to the message as a whole, including the stop_reason and the usage. Its token counts are running totals.
  4. message_stop: the end.

There can also be ping events, which you can ignore, and new event types may be added later, so code that reads raw events should skip types it does not know.

You rarely need the raw events. The SDK's stream helper hands you just the text pieces and, at the end, the complete message, with the same fields as a normal response. Today's main script uses that helper; a second, tiny script prints the raw event types once, so you have seen them.

Stop reasons: is the reply complete?

Every response says why Claude stopped, in stop_reason. In a stream it is empty at the start and arrives in the message_delta event; the helper's final message has it too. The values on the stop reasons page:

stop_reason What it means What to do
end_turn Claude finished on its own use the reply
max_tokens the reply hit your max_tokens ceiling raise max_tokens, or ask Claude to continue
stop_sequence Claude wrote one of your stop sequences see which one in stop_sequence
tool_use Claude wants to use a tool for later, not in this course
pause_turn a server tool loop hit its limit send the content back to continue
refusal Claude declined to answer read stop_details
model_context_window_exceeded the reply filled the context window treat it as cut off

For Linde the important one is max_tokens. A cut-off reply can look fine at first glance and stop mid-sentence. Never post a reply without checking that the stop reason is end_turn. One more detail from the docs: when Claude thinks before it answers, those thinking tokens count toward max_tokens as well, so a very low ceiling can leave almost no room for the answer.

When a stream breaks halfway

A stream can fail after it has started, for example with an overloaded_error when the API is very busy. Without a stream that would be a 529 error. Two things the docs say about this:

  • The SDK does not retry an error in a stream. It ends the stream and your code gets an error instead. In Python that is an APIStatusError, and you check its type, as today's script does.
  • You can pick up where it stopped. Save the text you already received, then send a new request with a user message that contains that text and asks Claude to continue from where it left off.

For a short review reply it is simpler to just run the request again.

The steps

  1. Create the streaming script with the SDK's stream helper and an error check.
  2. Run it and watch the reply arrive in pieces.
  3. Print the raw events once with a second, tiny script.
  4. Force a cut-off with a tiny max_tokens and read the stop reason.
  5. Set it back and confirm the stop reason is end_turn.

Follow the steps below.

Today's actions

Ticks are not saved without an account

Do it in Claude API

Claude API

  1. In your harbour-lane-replies folder, with the virtual environment on, create stream_reply.py with this code. It prints the text as it arrives and catches an error that comes in the middle of the stream.
    from dotenv import load_dotenv
    import anthropic
    
    load_dotenv()
    client = anthropic.Anthropic()
    
    REVIEW = "Lovely smoky tea, but the parcel took nine days."
    
    try:
        with client.messages.stream(
            model="claude-sonnet-5-5",
            max_tokens=1000,
            system="You write short, warm replies to customer reviews for Harbour Lane Tea Co.",
            messages=[{"role": "user", "content": "Write a reply to this review: " + REVIEW}],
        ) as stream:
            for text in stream.text_stream:
                print(text, end="", flush=True)
            message = stream.get_final_message()
    except anthropic.APIStatusError as e:
        print("\nThe stream stopped with an error:", e.type, e.api_message)
        raise SystemExit(1)
    
    print()
    print("stop_reason:", message.stop_reason)
    print("output tokens:", message.usage.output_tokens)
    if message.stop_reason == "max_tokens":
        print("Cut off: the reply is not complete. Raise max_tokens.")
  2. Run python stream_reply.py and watch the reply appear in pieces. At the end you see the stop reason and the output tokens.
  3. To see the events themselves, create stream_events.py with this code and run it. It prints the type of every event instead of the text.
    from dotenv import load_dotenv
    import anthropic
    
    load_dotenv()
    client = anthropic.Anthropic()
    
    stream = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=300,
        messages=[{"role": "user", "content": "Thank a tea customer in one sentence."}],
        stream=True,
    )
    for event in stream:
        print(event.type)
  4. In stream_reply.py, change max_tokens=1000 to max_tokens=20 and run it again. The reply stops early, the stop reason is max_tokens and the script warns you.
  5. Change it back to max_tokens=1000, run it once more and check that the stop reason is end_turn again.
  6. For Node instead of Python: save this as stream_reply.mjs and run node --env-file=.env stream_reply.mjs.
    import Anthropic from "@anthropic-ai/sdk";
    
    const client = new Anthropic();
    
    const REVIEW = "Lovely smoky tea, but the parcel took nine days.";
    
    let message;
    try {
      message = await client.messages
        .stream({
          model: "claude-sonnet-5-5",
          max_tokens: 1000,
          system: "You write short, warm replies to customer reviews for Harbour Lane Tea Co.",
          messages: [{ role: "user", content: "Write a reply to this review: " + REVIEW }]
        })
        .on("text", (text) => process.stdout.write(text))
        .finalMessage();
    } catch (err) {
      if (err instanceof Anthropic.APIError) {
        console.log("\nThe stream stopped with an error:", err.type, err.apiMessage);
        process.exit(1);
      }
      throw err;
    }
    
    console.log();
    console.log("stop_reason:", message.stop_reason);
    console.log("output tokens:", message.usage.output_tokens);
    if (message.stop_reason === "max_tokens") {
      console.log("Cut off: the reply is not complete. Raise max_tokens.");
    }

Note: With max_tokens at 20 you may see very little text, or none: thinking tokens count toward max_tokens too. The stop reason still says max_tokens. You may also see ping events in the event list; they carry no text.

Paid planPay as you go: buy prepaid credits in the Claude Console (minimum 5 US dollars). There is no free tier. Max, Ultra and Team plans include monthly API credits.

Checked on 4 December 2026 · Source: Claude API docs: Streaming messages (opens in a new tab)

Create a free account to save your progress. Sign in or sign up