Claude Streaming in Python: Events, message_stop and Stop Reasons
👋 In plain words: Streaming shows Claude’s answer word by word as it is written, instead of making the user wait for the whole thing. It arrives as a series of small events. This lesson walks through those events one by one, so your code shows complete answers and spots the ones that were cut off.
Streaming is how every chat interface feels fast, and it is also where many production bugs hide: answers that stop mid-sentence with no error, empty replies when Claude thinks first, and truncated output shown as complete. In this lesson you will stream with the SDK helper, read the raw event sequence, reproduce the classic “first content_block_stop” bug, fix it, and detect cut-off answers reliably.
🔑 Key terms
- Streaming: receiving the reply in small pieces while it is generated, over server-sent events (SSE).
- Event: one piece of the stream, with a type such as
message_startorcontent_block_delta. - Content block: one part of the reply (thinking, text or tool_use). A reply can have several.
- Terminal event: the event that marks the end of the whole message:
message_stop.
🪜 Step 1: Stream text with the SDK helper
client.messages.stream() is the recommended way. It gives you text_stream for printing and get_final_message() for the complete result.
📄 stream_basic.py
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=2000,
messages=[{"role": "user", "content": "Explain test pyramids in two sentences."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print("\n---")
print("stop_reason:", final.stop_reason, "| output tokens:", final.usage.output_tokens)⌨️ Terminal
python stream_basic.py🖥️ Output (sample run)
A test pyramid has many fast unit tests at the bottom, fewer integration tests in the middle and only a few slow end-to-end tests at the top. This shape keeps feedback fast while still checking that the whole system works together.
---
stop_reason: end_turn | output tokens: 69
text_streamyields only text pieces, so you can print them straight to a terminal or push them to a web page.get_final_message()returns the sameMessageobject a non-streaming call would, withstop_reasonandusage. Always readstop_reasonfrom it before treating the answer as complete.
max_tokens. It avoids HTTP timeouts, and the SDK requires it for very large max_tokens values.🪜 Step 2: Learn the event sequence
Under the helper, the API sends these events, in this order:
message_start: aMessagewith empty content.- For each content block, in order:
–
content_block_startwith the block’s type and index; – one or morecontent_block_deltaevents (text_delta,thinking_delta,input_json_deltafor tool input,signature_delta); –content_block_stopfor that index. message_delta: carries thestop_reasonand final output-token usage.message_stop: the terminal event. The message is finished.
The SDK also handles ping events and in-stream error events for you. Print the raw sequence with stream=True:
📄 raw_events.py
import anthropic
client = anthropic.Anthropic()
events = client.messages.create(
model="claude-opus-5-5",
max_tokens=2000,
stream=True,
messages=[{"role": "user", "content": "Is 404 a client or server error? One sentence."}],
)
for event in events:
line = event.type
if event.type == "content_block_start":
line += f" index={event.index} block={event.content_block.type}"
elif event.type == "content_block_delta":
line += f" index={event.index} {event.delta.type}"
elif event.type == "message_delta":
line += f" stop_reason={event.delta.stop_reason}"
print(line)⌨️ Terminal
python raw_events.py🖥️ Output (sample run)
message_start
content_block_start index=0 block=thinking
content_block_delta index=0 signature_delta
content_block_stop
content_block_start index=1 block=text
content_block_delta index=1 text_delta
content_block_delta index=1 text_delta
content_block_delta index=1 text_delta
content_block_delta index=1 text_delta
content_block_delta index=1 text_delta
content_block_stop
message_delta stop_reason=end_turn
message_stop
Notice there are two content blocks: a thinking block (index 0) and a text block (index 1). On current models, thinking runs by default and its text is omitted, but the block still arrives in the stream.
🪜 Step 3: Reproduce the “first content_block_stop” bug
A common hand-written handler appends text deltas and stops at the first content_block_stop. It never reads the stop reason. Run it on the same request:
📄 buggy_handler.py
import anthropic
client = anthropic.Anthropic()
def stream_answer_buggy(question: str) -> str:
answer = ""
for event in client.messages.create(
model="claude-opus-5-5", max_tokens=2000, stream=True,
messages=[{"role": "user", "content": question}],
):
if event.type == "content_block_delta" and event.delta.type == "text_delta":
answer += event.delta.text
if event.type == "content_block_stop":
break # BUG: this only closes ONE block, not the message
return answer
print(repr(stream_answer_buggy("Is 404 a client or server error? One sentence.")))⌨️ Terminal
python buggy_handler.py🖥️ Output (sample run)
''
The user sees an empty answer. The loop stopped when the thinking block closed, before the text block started. With replies that have several text or tool blocks, the same bug shows as answers that end mid-way with no error.
content_block_stop closes a single block; message_stop ends the message. The correct fix is to treat message_stop as terminal and read the stop reason from message_delta. Raising max_tokens, switching to non-streaming or retrying all treat the symptom.🪜 Step 4: Fix the handler
Keep reading until message_stop, and record the stop reason from message_delta:
📄 fixed_handler.py
import anthropic
client = anthropic.Anthropic()
def stream_answer(question: str, max_tokens: int = 2000) -> tuple[str, str]:
answer, stop_reason = "", None
for event in client.messages.create(
model="claude-opus-5-5", max_tokens=max_tokens, stream=True,
messages=[{"role": "user", "content": question}],
):
if event.type == "content_block_delta" and event.delta.type == "text_delta":
answer += event.delta.text
elif event.type == "message_delta":
stop_reason = event.delta.stop_reason
elif event.type == "message_stop":
break # the whole message is finished
return answer, stop_reason
text, reason = stream_answer("Is 404 a client or server error? One sentence.")
print(repr(text))
print("stop_reason:", reason)⌨️ Terminal
python fixed_handler.py🖥️ Output (sample run)
'404 Not Found is a client error, because the requested resource does not exist on the server.'
stop_reason: end_turn
🪜 Step 5: Flag answers that were cut off
If generation hits max_tokens, the stream still ends normally with message_stop, and nothing raises an error. The only signal is stop_reason == "max_tokens". Show that to the user instead of presenting a partial answer as complete:
📄 truncation.py
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=60,
messages=[{"role": "user", "content": "Write a detailed test plan for a checkout page."}],
) as stream:
text = "".join(stream.text_stream)
final = stream.get_final_message()
if final.stop_reason == "max_tokens":
print("PARTIAL ANSWER (hit max_tokens):")
print(text + " [...]")
print("-> show a 'continue' button, raise max_tokens, or ask for a shorter answer")
else:
print(text)⌨️ Terminal
python truncation.py🖥️ Output (sample run)
PARTIAL ANSWER (hit max_tokens):
Test plan: checkout page. 1. Scope: cart summary, address form, shipping options, payment, order confirmation. 2. Functional cases: valid card payment, declined card, expired card, coupon applied [...]
-> show a 'continue' button, raise max_tokens, or ask for a shorter answer
max_tokensis deterministic: retrying the same request hits the same limit. Do not retry; change the request.- For long outputs, raise
max_tokens(streaming makes large values safe) or split the task.
🪜 Step 6: Handle interrupted streams and errors
Streams can fail part-way: an overloaded error can arrive inside the stream, or the connection can drop. The SDK raises an exception from the iterator in both cases. Wrap the stream, keep what you received for logging, and retry the whole request:
📄 stream_errors.py
import anthropic
client = anthropic.Anthropic(max_retries=0) # show the raw error in this demo
def ask(question: str) -> str:
try:
with client.messages.stream(
model="claude-opus-5-5", max_tokens=1000,
messages=[{"role": "user", "content": question}],
) as stream:
return stream.get_final_message().content[0].text
except anthropic.APIStatusError as e:
return f"stream failed with {e.status_code} {e.body['error']['type']}: retry the whole request later"
except anthropic.APIConnectionError:
return "connection lost: retry the whole request"
print(ask("Summarise the release notes."))⌨️ Terminal
python stream_errors.py🖥️ Output (sample run)
stream failed with 529 overloaded_error: retry the whole request later
🌍 Real-world example: Ravi’s support widget
Ravi’s team saw “short answers with no error” in their support widget. The logs showed stop_reason was never recorded. After switching to get_final_message() and showing a “continue” button for max_tokens, complaints stopped. A second bug, empty replies after a model upgrade, was the first-content_block_stop bug meeting thinking blocks.
🧪 Practice Questions
Question 1. A streaming handler shows empty replies after the team upgrades to a model where thinking is on by default. The handler stops at the first content_block_stop. What is the fix?
- A. Disable thinking
- B. Continue until message_stop and collect text from every text block
- C. Raise max_tokens
- D. Switch to non-streaming requests
Show answer
Answer: B. The first block is now a thinking block, so stopping at its content_block_stop ends before the text block. message_stop is the terminal event.
Question 2. Where do you read the stop reason in a raw event stream?
- A. content_block_start
- B. content_block_stop
- C. message_delta
- D. ping
Show answer
Answer: C. message_delta carries the stop_reason and final usage, just before message_stop.
Question 3. A streamed answer stops mid-sentence, the stream ends normally and stop_reason is “max_tokens”. Which two responses are correct? (Choose 2.)
- A. Flag the answer as partial instead of showing it as complete
- B. Retry the identical request with exponential backoff
- C. Raise max_tokens or ask for a shorter answer
- D. Treat it as an overloaded error
Show answer
Answer: A and C. max_tokens is a deterministic limit, so retrying the same request produces the same cut-off. Detect it and change the request.
Question 4. An overloaded error arrives in the middle of a stream. What should the client do?
- A. Continue reading events; the stream will recover
- B. Send the partial text back as an assistant prefill
- C. Catch the exception, log what was received, and retry the whole request with backoff
- D. Switch off streaming permanently
Show answer
Answer: C. In-stream errors end the stream. The safe recovery is to retry the request. Prefill continuation is not supported on current models.
📝 Assignment
- Task 1: Run
raw_events.pywith your own key and save the printed event sequence.
✅ Done when: you can point to message_start, each block’s start/delta/stop, message_delta and message_stop. - Task 2: Write a pytest test that feeds a list of fake events (plain objects with
type,delta,index) into a version ofstream_answerand asserts it returns all text from two text blocks.
✅ Done when: the test fails on the buggy handler and passes on the fixed one. - Stretch: Build a tiny FastAPI endpoint that streams Claude’s text to the browser and sends a final
[TRUNCATED]marker whenstop_reasonismax_tokens.
✅ Done when: a request with a smallmax_tokensends with the marker.
❓ Frequently Asked Questions
🤔 What is the difference between content_block_stop and message_stop?
content_block_stop ends one content block, such as a thinking or text block. message_stop ends the whole message and is the terminal event.
🤔 How do I get the full message after streaming?
With the SDK helper, call stream.get_final_message(). It returns the complete Message, including stop_reason and usage.
🤔 Should I always stream Claude responses?
Stream when users wait for the answer, or when input, output or max_tokens is large. Short background calls can use non-streaming requests.
🤔 Does streaming cost more?
No. You pay for the same input and output tokens whether or not you stream.
🏁 Summary
- Use
client.messages.stream()withtext_streamandget_final_message(). - Event order: message_start → per block start/delta/stop → message_delta → message_stop.
content_block_stopcloses one block;message_stopends the message.- Read
stop_reasonfrommessage_delta(or the final message) and flagmax_tokensas partial. - On in-stream errors or dropped connections, retry the whole request.
Next, continue with Claude Vision, PDFs and the Files API in Python.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.