Day 6, 25 minutes · beginner
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:
message_start: a message with empty content.- For each content block:
content_block_start, then any number ofcontent_block_deltaevents with the next piece of text, thencontent_block_stop. message_delta: changes to the message as a whole, including thestop_reasonand theusage. Its token counts are running totals.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 itstype, 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
- Create the streaming script with the SDK's stream helper and an error check.
- Run it and watch the reply arrive in pieces.
- Print the raw events once with a second, tiny script.
- Force a cut-off with a tiny
max_tokensand read the stop reason. - Set it back and confirm the stop reason is
end_turn.
Follow the steps below.
Today's actions
Ticks are not saved without an accountDo it in Claude API
Claude API
- In your harbour-lane-replies folder, with the virtual environment on, create
stream_reply.pywith 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.") - Run
python stream_reply.pyand watch the reply appear in pieces. At the end you see the stop reason and the output tokens. - To see the events themselves, create
stream_events.pywith 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) - In
stream_reply.py, changemax_tokens=1000tomax_tokens=20and run it again. The reply stops early, the stop reason ismax_tokensand the script warns you. - Change it back to
max_tokens=1000, run it once more and check that the stop reason isend_turnagain. - For Node instead of Python: save this as
stream_reply.mjsand runnode --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.
Create a free account to save your progress
Free, and no payment details. Your ticks and finished lessons are kept, on every device.
Create a free account I already have an accountCreate a free account to save your progress. Sign in or sign up