Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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.

One streamed reply, event by event message_start empty content, starting usage (not the final count) content_block_start index 0: a text block, or a tool_use block content_block_delta x N text_delta: a few words of text input_json_delta: a piece of tool JSON content_block_stop this block is done; another block can follow message_delta stop_reason and the cumulative usage message_stop the only terminal event A ping can show up anywhere in between. Ignore event types you don't know.
Where each fact lives: text and tool arguments in the deltas, the stop reason and the real usage in message_delta, the end in message_stop.

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 eventsWebSocket
HopClaude API to our serverOur server to the browser
DirectionOne way, server to clientBoth ways on one connection
Built onA normal HTTP response that stays openAn open socket after an HTTP upgrade
Who provides itThe Messages API, with stream: trueWe 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 is message_stop.
  • Reading tool input at content_block_start. Collect the input_json_delta pieces and parse at the block's stop.
  • Never checking stop_reason. max_tokens and refusal need their own handling.
  • Billing from message_start usage. Use the last message_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

SymptomEvent to look atFix
A tool call is missingmessage_stopRead up to the terminal event
Tool input is emptyinput_json_deltaJoin partial_json, parse at content_block_stop
Every reply says completemessage_deltaRead stop_reason; handle max_tokens and refusal
Token count is 1message_deltaTake the cumulative usage, last one wins
Words must appear in the pagecontent_block_deltaRelay 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.)

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 15 of 66

Previous
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Next post
Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out

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.

On this page

  • A tap, not a jug
  • The event flow, in order
  • wire.py: the raw wire and what the SDK hands you
  • relay.py: SSE in, WebSocket frames out
  • Reading a stream log: four handlers, four defects
  • Drill 1: the reply that ended early
  • Drill 2: the tool call with empty input
  • Drill 3: every reply says complete
  • Drill 4: the bill that says one token
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.