Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
Read one streamed Claude reply event by event, relay its text deltas to a browser over a WebSocket, then fix four stream handlers from their event logs: the terminal event, tool arguments, stop reasons and the real token count.
What you will learn
- List the server-sent events of one streamed Claude reply in order, and say where the text, the tool arguments, the stop reason and the usage arrive
- Relay Claude's SSE stream to a browser over your own WebSocket, one frame per text delta
- Fix four stream handler defects from the event log: the wrong terminal event, lost input_json_delta pieces, an ignored stop_reason, usage read from message_start
- Tell server-sent events and WebSockets apart and keep the API key on the server
Before you start
- Claude client SDKs wrap one REST API
- Streaming and error handling for LLM calls
A support chat where the answer fills in as Claude writes it. Wait for the whole answer and the box stays blank while the model writes, then everything lands at once. Stream it and each small piece shows up as it comes, so the reader starts reading right away. Streaming doesn't make the answer shorter. It lets the reader start sooner.
Two transports make that chat work. Claude streams to our server using server-sent events (SSE). Our server streams to the browser over a WebSocket we build. In this article we look at both hops, and then read four stream handlers that look fine but each mishandle one event.
The output comes from the lecture projects. A stand-in model (an httpx mock transport) sends scripted event streams in the Messages API format; replies start with test model reply and the token numbers are made up for the demo.
A tap, not a jug
Think of water. You can fill a jug and carry it over: nothing to drink until the jug is full. That is stream: false. You can open a tap, and water arrives as it is made. That is server-sent events. Or you can pour for a guest from your own tap as it runs: a pipe you build yourself, the WebSocket. Claude runs the tap. We run the second pipe, the one to the guest.
The event flow, in order
Ask with stream: true and one reply arrives as a sequence of events. On the wire each event is an event: line, a data: line with JSON, and a blank line.
wire.py: the raw wire and what the SDK hands you
The first file reads one answer two ways: the raw event: lines, then the SDK's typed events, then the text_stream helper.
"""One answer, seen two ways: the raw SSE lines, then what the SDK gives us."""
from stand_in import MODEL, URL, make_http
ASK = [{"role": "user", "content": "T-201: Where is my refund?"}]
def wire_names():
"""POST with stream true and read the event: lines as they arrive."""
body = {"model": MODEL, "max_tokens": 256, "stream": True,
"messages": ASK}
names = []
with make_http().stream("POST", URL, json=body) as r:
for line in r.iter_lines():
if line.startswith("event: "):
names.append(line[len("event: "):])
return names
def sdk_names(client):
"""The SDK parses each event into a typed object."""
stream = client.messages.create(model=MODEL, max_tokens=256,
stream=True, messages=ASK)
return [event.type for event in stream]
def whole_answer(client):
"""The helper joins the deltas for us."""
with client.messages.stream(model=MODEL, max_tokens=256,
messages=ASK) as stream:
text = "".join(stream.text_stream)
final = stream.get_final_message()
return text, final
wire (event: lines, in order)
1 message_start
2 content_block_start
3 ping
4 content_block_delta
5 content_block_delta
6 content_block_delta
7 content_block_delta
8 content_block_stop
9 message_delta
10 message_stop
sdk (stream=True): 9 events, ping is not among them
text_stream: test model reply: your refund was sent on Monday. [end_turn]
Ten events on the wire, in the documented order. The third is a ping, a keep-alive. The SDK hands you nine: the ping is for the connection, so it never reaches your loop. And text_stream joins the four text deltas into one sentence, while get_final_message() gives the whole message, stop reason included.
relay.py: SSE in, WebSocket frames out
Now our own server. One WebSocket per browser, each question arriving on that same socket. For each question we ask Claude with stream=True, turn every text delta into a frame, and turn the message_delta into a done frame.
"""Our own server: Claude's SSE stream in, WebSocket frames out."""
import json
from aiohttp import WSMsgType, web
from stand_in import MODEL
async def relay(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
client = request.app["claude"]
async for msg in ws:
if msg.type != WSMsgType.TEXT:
continue
ask = json.loads(msg.data)["text"]
stream = await client.messages.create(
model=MODEL, max_tokens=256, stream=True,
messages=[{"role": "user", "content": ask}])
async for event in stream:
frame = to_frame(event)
if frame:
await ws.send_json(frame)
return ws
def to_frame(event):
if event.type == "content_block_delta":
return {"type": "delta", "text": event.delta.text}
if event.type == "message_delta":
return {"type": "done",
"stop_reason": event.delta.stop_reason,
"output_tokens": event.usage.output_tokens}
def make_app(client):
app = web.Application()
app["claude"] = client
app.add_routes([web.get("/stream", relay)])
return app
A small browser.py stands in for the page: it opens one WebSocket and asks two questions over it.
relay (WebSocket frames the browser receives)
asks 'T-201: Where is my refund?'
delta 'test model reply: '
delta 'your refund '
delta 'was sent '
delta 'on Monday.'
done end_turn | output_tokens 4
asks 'T-202: When does my parcel arrive?'
delta 'test model reply: '
delta 'your parcel '
delta 'arrives on Friday.'
done end_turn | output_tokens 3
One frame out for each text delta in, then a done frame. The second question goes over the same open socket. The relay translates; the browser never sees the API key.
| Server-sent events | WebSocket | |
|---|---|---|
| Hop | Claude API to our server | Our server to the browser |
| Direction | One way, server to client | Both ways on one connection |
| Built on | A normal HTTP response that stays open | An open socket after an HTTP upgrade |
| Who provides it | The Messages API, with stream: true | We build it (here in relay.py) |
Reading a stream log: four handlers, four defects
A stream is a log of events, and a handler can read it wrong while the reply on screen looks fine. Think of a parcel tracker: a scan when the label is created, another when it is out for delivery, a last one when it is delivered. Out for delivery is not the end of the trip. In a stream, the last scan is message_stop.
The CourierHub project has four drill files, each with a broken handle_before and a fixed handle_after. Every drill uses the same streamed request:
def ask(client, job):
"""One streamed request, the same for every drill: the raw events come back."""
return client.messages.create(model=MODEL, max_tokens=MAX_TOKENS, stream=True,
messages=[{"role": "user", "content": job}])
Drill 1: the reply that ended early
The handler collects tool calls, but it leaves the loop on the first content_block_stop:
def handle_before(client, job):
tools, last = [], ""
for event in ask(client, job):
last = event.type
if event.type == "content_block_start":
if event.content_block.type == "tool_use":
tools.append(event.content_block.name)
if event.type == "content_block_stop":
break
return {"tools": tools, "last": last}
The fix changes one line: if event.type == "message_stop": break.
drill 1 | J-311
1 message_start out 1
2 content_block_start 0 text
3 content_block_delta 0 text_delta
4 content_block_delta 0 text_delta
5 content_block_stop 0
6 content_block_start 1 tool_use
7 content_block_delta 1 input_json_delta
8 content_block_stop 1
9 message_delta tool_use out 31
10 message_stop
before: {'tools': [], 'last': 'content_block_stop'}
after: {'tools': ['look_up_parcel'], 'last': 'message_stop'}
The clue is last: content_block_stop. A block can stop and another can follow; here a tool_use block came second. Only message_stop ends the message.
Drill 2: the tool call with empty input
The broken handler reads block.input when the tool block starts (it is still empty then), and only handles text_delta, so every input_json_delta falls through. The fix joins the pieces and parses once, when the block stops:
def handle_after(client, job):
call, raw = {}, ""
for event in ask(client, job):
if event.type == "content_block_start":
block = event.content_block
if block.type == "tool_use":
call, raw = {"name": block.name}, ""
elif event.type == "content_block_delta":
if event.delta.type == "input_json_delta":
raw += event.delta.partial_json
elif event.type == "content_block_stop" and call:
call["input"] = json.loads(raw)
return call
drill 2 | J-312
1 message_start out 1
2 content_block_start 0 text
3 content_block_delta 0 text_delta
4 content_block_stop 0
5 content_block_start 1 tool_use
6 content_block_delta 1 input_json_delta
7 content_block_delta 1 input_json_delta
8 content_block_delta 1 input_json_delta
9 content_block_stop 1
10 message_delta tool_use out 38
11 message_stop
before: {'name': 'book_courier', 'input': {}}
after: {'name': 'book_courier', 'input': {'parcel': 'P-5521', 'slot': 'Thursday'}}
Tool arguments arrive as pieces of JSON. Join them, then parse.
Drill 3: every reply says complete
Three jobs finished three different ways, and the broken handler called all of them complete because it never read the stop reason. The fix reads it from message_delta and maps it:
NEXT = {"complete": "show it",
"truncated": "continue or raise the limit",
"declined": "hand it to a person"}
STATUS = {"end_turn": "complete",
"max_tokens": "truncated",
"refusal": "declined"}
def handle_after(client, job):
text, reason = "", ""
for event in ask(client, job):
if event.type == "content_block_delta":
text += event.delta.text
elif event.type == "message_delta":
reason = event.delta.stop_reason
return {"status": STATUS[reason], "text": text}
drill 3 | J-313, J-314, J-315
J-313 max_tokens before: complete after: truncated, continue or raise the limit
J-314 refusal before: complete after: declined, hand it to a person
J-315 end_turn before: complete after: complete, show it
A cut-off reply and a refusal are not complete. The reason arrives in message_delta.
Drill 4: the bill that says one token
The cost log said the reply used a single output token. The handler read the usage from message_start, where the count is only a starting value. The fix reads it from message_delta, and the last one wins:
def handle_after(client, job):
used = 0
for event in ask(client, job):
if event.type == "message_delta":
used = event.usage.output_tokens
return {"output_tokens": used}
drill 4 | J-316
1 message_start out 1
2 content_block_start 0 text
3 content_block_delta 0 text_delta
4 content_block_stop 0
5 message_delta end_turn out 37
6 message_stop
before: {'output_tokens': 1}
after: {'output_tokens': 37}
The usage in message_delta is cumulative, so the last one is the real count.
Common mistakes
- Polling the API for new text, or waiting for the whole answer and splitting it. Neither is streaming; the reader still waits. Use
stream: true. - Giving the browser the API key so it can stream directly. Stream to your server and relay.
- Treating the stream as one JSON document. It is many events. Buffering it all and parsing once misreads it.
- Ending on
content_block_stop. The terminal event ismessage_stop. - Reading tool input at
content_block_start. Collect theinput_json_deltapieces and parse at the block's stop. - Never checking
stop_reason.max_tokensandrefusalneed their own handling. - Billing from
message_startusage. Use the lastmessage_delta. - Crashing on an unknown event type. New types may be added; ignore the ones you don't know.
- Swapping to a different SDK helper or adding logging instead of fixing the event. Match the symptom to the event, then fix the handler there.
Quick recap
| Symptom | Event to look at | Fix |
|---|---|---|
| A tool call is missing | message_stop | Read up to the terminal event |
| Tool input is empty | input_json_delta | Join partial_json, parse at content_block_stop |
| Every reply says complete | message_delta | Read stop_reason; handle max_tokens and refusal |
| Token count is 1 | message_delta | Take the cumulative usage, last one wins |
| Words must appear in the page | content_block_delta | Relay one WebSocket frame per text delta |
For the basics of streaming and retries, see Streaming and error handling for LLM calls. For a provider-neutral SSE endpoint and a browser reading the stream, see Streaming LLM answers over SSE and WebSockets. Tool calls themselves are covered in Claude tool use.
Try it yourself
Add a refusal branch to to_frame in relay.py so the browser gets a different done frame when Claude declines. Then add a job to the CourierHub stand-in whose reply has two tool blocks, and check that the drill 2 handler still returns both inputs. (Hint: it keeps only one call.)
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.