Claude Agent SDKclaude-agent-sdk 0.2.157 · Python 3.10+
Dashboard
0%

Streaming output

Streaming output is the SDK yielding raw API stream events while Claude is still writing, so your program can show text a chunk at a time instead of waiting for the finished block.

Last updated: 20 Oct, 2026 · Claude Agent SDK

The runs so far printed an answer all at once, because that is what the SDK does by default: the streaming page says a complete assistant message arrives for each non-empty content block, after Claude has finished generating that block. One option changes it.

Turning on include_partial_messages

python
options = ClaudeAgentOptions(include_partial_messages=True)

With that set, the stream gains StreamEvent messages carrying raw API events as they arrive, in addition to the usual assistant and result messages. Nothing is taken away, so code written before the option was turned on keeps working.

Adding the delta branch to the stand-in

The stand-in has to earn the option rather than ignore it. This version replaces say in shop_desk.py: when partial messages are on it sends one stream event per word first, then the whole message as before.

python
    async def say(self, text):
        # with include_partial_messages on, the text goes out a word at a time
        if self.options.include_partial_messages:
            for word in text.split(" "):
                delta = {"type": "text_delta", "text": word + " "}
                await self.send({"type": "stream_event", "uuid": f"ev_{next(self.ids)}",
                                 "session_id": self.session_id, "event": {
                                     "type": "content_block_delta", "index": 0,
                                     "delta": delta}})

        # the whole message still follows, so code written earlier keeps working
        await self.send(self.message("assistant", [{"type": "text", "text": text}]))

The event shape is the one the documentation describes: a content_block_delta event whose delta has the type text_delta and the text itself. A real session sends several more event types around those, listed further down this page.

Project files used on this pageThis lesson builds on a project from earlier lessons. The code below imports this file. Click a file to see its code, or follow the link to the lesson that wrote it. To run the code yourself, keep it in the same folder.
View the code here
shop_desk.py
import asyncio
import itertools
import json
import re

from claude_agent_sdk import ClaudeAgentOptions, Transport

ORDER = re.compile(r"\b[A-Z]\d+\b")
SESSIONS = itertools.count(1)


class ShopModel:
    """Stands in for Claude: reads the conversation, picks the next step."""

    def __init__(self, script=None):
        self.script = list(script or [])

    def reply(self, said, results):
        # a scripted reply lets a lesson force a step the stand-in would not pick
        if self.script:
            return self.script.pop(0)
        if results:
            return {"text": " ".join(results)}

        # the newest message first, then the last id named earlier in the chat
        orders = ORDER.findall(said[-1]) or ORDER.findall(" ".join(said))[-1:]
        return {"text": f"I cannot help with order {orders[0]} yet." if orders
                else "Which order is this about?"}


class ShopDesk(Transport):
    """Stands in for the Claude Code binary: it runs the loop over JSON lines."""

    def __init__(self, options=None, model=None):
        self.options = options or ClaudeAgentOptions()
        self.model = model or ShopModel()

        # a counted id, not a UUID, so the printed output is the same every run
        self.session_id = f"session-{next(SESSIONS)}"
        self.inbox, self.outbox = asyncio.Queue(), asyncio.Queue()
        self.prompts, self.said = asyncio.Queue(), []
        self.ids, self.setup = itertools.count(1), {}
        self.ready = False

    async def connect(self):
        self.ready = True

    def is_ready(self):
        return self.ready

    async def write(self, data):
        # one JSON line at a time, which is what the SDK writes to a real process
        await self.inbox.put(json.loads(data))

    async def end_input(self):
        # for a real process this would close its standard input
        await self.inbox.put(None)

    async def close(self):
        self.ready = False

    async def send(self, message):
        await self.outbox.put(message)

    async def read_messages(self):
        # the listener and the worker run alongside the SDK's own read loop
        asyncio.create_task(self.listen())
        self.worker = asyncio.create_task(self.work())

        while (message := await self.outbox.get()) is not None:
            if isinstance(message, Exception):
                raise message
            yield message

    async def listen(self):
        while (message := await self.inbox.get()) is not None:
            # a control request is the SDK asking a question; initialize is first
            if message["type"] == "control_request":
                if message["request"]["subtype"] == "initialize":
                    self.setup = message["request"]
                await self.respond(message["request_id"])
            elif message["type"] == "user":
                await self.prompts.put(message["message"]["content"])

        # the input has ended: finish the work in hand, then close the stream
        await self.prompts.put(None)
        await self.worker
        await self.send(None)

    async def respond(self, request_id):
        # the stand-in says yes to every request the SDK makes of it
        await self.send({"type": "control_response", "response": {
            "subtype": "success", "request_id": request_id, "response": {}}})

    async def work(self):
        while (prompt := await self.prompts.get()) is not None:
            await self.turn(prompt)

    async def turn(self, prompt):
        self.said.append(prompt)
        await self.send({"type": "system", "subtype": "init", "model": "shop-desk",
                         "session_id": self.session_id, "tools": []})

        # one round only for now: the tool-calling rounds arrive with the tools
        step = self.model.reply(self.said, [])
        await self.say(step["text"])
        await self.finish("success", 1, step["text"])

    async def say(self, text):
        # with include_partial_messages on, the text goes out a word at a time
        if self.options.include_partial_messages:
            for word in text.split(" "):
                delta = {"type": "text_delta", "text": word + " "}
                await self.send({"type": "stream_event", "uuid": f"ev_{next(self.ids)}",
                                 "session_id": self.session_id, "event": {
                                     "type": "content_block_delta", "index": 0,
                                     "delta": delta}})

        # the whole message still follows, so code written earlier keeps working
        await self.send(self.message("assistant", [{"type": "text", "text": text}]))

    async def finish(self, subtype, turns, text):
        ok = subtype == "success"
        result = {"type": "result", "subtype": subtype, "is_error": not ok,
                  "duration_ms": 0, "duration_api_ms": 0, "num_turns": turns,
                  "session_id": self.session_id, "total_cost_usd": 0.0,
                  "usage": {"input_tokens": len(" ".join(self.said).split()),
                            "output_tokens": len(text.split())}}

        # cost is zero and usage counts words, because no model was called
        result.update({"result": text} if ok else {"errors": [text]})
        await self.send(result)

    def message(self, kind, content, parent=None):
        body = {"role": kind, "content": content}
        if kind == "assistant":
            body.update(model="shop-desk", id=f"msg_{next(self.ids)}")
        return {"type": kind, "message": body, "parent_tool_use_id": parent,
                "session_id": self.session_id}

Comparing the stream with and without the option

Example
from claude_agent_sdk import ClaudeAgentOptions, query
from shop_desk import ShopDesk

for partial in (False, True):
    options = ClaudeAgentOptions(include_partial_messages=partial)
    kinds = []

    # the same question twice, so the only difference is the option
    async for message in query(prompt="Where is my order A17?", options=options,
                               transport=ShopDesk(options)):
        kinds.append(type(message).__name__)
    print(partial, kinds)
  • Off, the run is three messages, which is every run so far in this course.
  • On, seven stream events appear between the system message and the assistant message, one per word of the answer.
  • The assistant message is still there, and so is the result. The events are an addition, not a replacement, which is what makes the option safe to turn on in code that already works.
  • Seven events for seven words is this stand-in's choice. A real session chunks by whatever the API sends, which is neither words nor characters.

Printing the text as it is written

Reading the events means three checks, nested: the message is a StreamEvent, its event is a content_block_delta, and that delta is a text_delta.

Example
from claude_agent_sdk import ClaudeAgentOptions, StreamEvent, query
from shop_desk import ShopDesk

options = ClaudeAgentOptions(include_partial_messages=True)
async for message in query(prompt="Where is my order A17?", options=options,
                           transport=ShopDesk(options)):
    if isinstance(message, StreamEvent):
        event = message.event

        # the event dictionaries are raw API events, so read them with .get
        if event.get("type") == "content_block_delta":
            delta = event.get("delta", {})
            if delta.get("type") == "text_delta":
                print(delta.get("text", ""), end="", flush=True)
  • The chunks join into the finished sentence, because end="" keeps them on one line.
  • Your code does the joining. The documentation is explicit that stream events carry raw API events and not accumulated text, so nothing hands you the sentence.
  • event is a plain dictionary, not a typed object, which is why every read above goes through .get. A newer Claude Code can add an event type without breaking this loop.
  • The same three checks work unchanged against a real session. This is the one place in the course where the stand-in's output is shaped exactly like the real thing by design, because the shape is the lesson.

The other event types a real session sends

The streaming page lists six event types, and names the order they arrive in: message_start, then a content_block_start and a run of content_block_delta events per block, the complete assistant message, a content_block_stop, and finally message_delta and message_stop. Tool calls stream the same way, with a delta type of input_json_delta carrying the arguments as partial JSON.

Two behaviours are worth knowing before you build an interface on this. A stream that is cut off mid-message still gets its message_stop, and a cut text block still gets its content_block_stop, but a cut tool call does not: if message_stop arrives while a tool call's block is still open, treat that call's arguments as incomplete.

A complete message against a stream event

AssistantMessageStreamEvent
When it arrivesAfter the block is finishedWhile the block is being written
What it holdsTyped content blocksA raw API event, as a dictionary
TextCompleteOne delta, which you accumulate
Needs an optionNoYes, include_partial_messages
Subagent outputCarries parent_tool_use_idNever: main session only
Good forLogging and auditing a runA typing-as-it-goes interface

Where streaming output changes the interface

  • A chat window, where the wait before the first word is the whole impression the agent makes.
  • A long-running task with a progress line, where the tool-input deltas let you say which file is being read before the read finishes.
  • A terminal tool of your own, where the events are the only way to write output as it is produced rather than in blocks.
Watch out. Stream events come from the main session only. The streaming page states that parent_tool_use_id is always None in Python, and that token-level deltas from subagents are not forwarded, so an interface built on deltas alone goes quiet while a subagent works. Attribute output to a subagent from the complete messages, which do carry the field.
Try it yourself
  • Collect the deltas into a list instead of printing them, and compare "".join(...) with the assistant message's own text.
  • Print message.uuid and message.session_id for each event, and check that every event of one run shares the session id.
  • Set include_partial_messages=False in the printing example and watch the output disappear, since nothing in it handles the complete message.

You understood something today that you didn't yesterday.