Stream responses in real-time
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -1,6 +1,9 @@
By default, the Agent SDK yields a complete `AssistantMessage` for each non-empty content block, such as a text block or a tool call, after Claude finishes generating that block. To receive incremental updates as text and tool calls are generated, enable partial message streaming.
-This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
+These cases are covered on other pages:
+
+ * **Sending messages to a running session** : see [Send messages to a running agent](</docs/en/agent-sdk/streaming-vs-single-mode>)
+ * **Streaming responses from the CLI** : see [stream responses using the Agent SDK via the CLI](</docs/en/headless>)
## Enable streaming output
@@ -301,6 +304,6 @@
Now that you can stream text and tool calls in real-time, explore these related topics:
- * [Interactive vs one-shot queries](</docs/en/agent-sdk/streaming-vs-single-mode>): choose between input modes for your use case
+ * [Send messages to a running agent](</docs/en/agent-sdk/streaming-vs-single-mode>): interrupt Claude’s response or attach an image to a message
* [Structured outputs](</docs/en/agent-sdk/structured-outputs>): get typed JSON responses from the agent
* [Permissions](</docs/en/agent-sdk/permissions>): control which tools the agent can use
Show diff (102 lines)
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -2,11 +2,7 @@
This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
-##
-
-
-
-Enable streaming output
+## Enable streaming output
To enable streaming, set `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options. This causes the SDK to yield `StreamEvent` messages containing raw API events as they arrive, in addition to the usual `AssistantMessage` and `ResultMessage`. Your code then needs to:
@@ -59,11 +55,7 @@
}
}
-##
-
-
-
-StreamEvent reference
+## StreamEvent reference
When partial messages are enabled, you receive raw Claude API streaming events wrapped in an object. The type has different names in each SDK:
@@ -81,11 +73,7 @@
`message_delta`| Message-level updates (stop reason, usage)
`message_stop`| End of the message
-##
-
-
-
-Message flow
+## Message flow
Claude Code emits an `AssistantMessage` as each non-empty content block completes, so a response with a text block and a tool call yields two `AssistantMessage` objects. Each one carries only its own content block, and both share the same message ID, which you read as `message.message.id` in TypeScript and `message.message_id` in Python. With partial messages enabled, each `AssistantMessage` arrives before that block’s `content_block_stop` event, and you receive messages in this order:
@@ -106,11 +94,7 @@
Without partial messages enabled, you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete content blocks), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
-###
-
-
-
-Handle a stream that’s cut off
+### Handle a stream that’s cut off
If a stream is cut off mid-message, you still receive that message’s `message_stop` before the turn ends. Causes of a cut-off stream include an interrupted turn, a dropped connection, and a fallback to a non-streaming request. `content_block_stop` and `message_delta` can be missing before that `message_stop`:
@@ -119,11 +103,7 @@
Before Claude Code v2.1.290, a cut stream could end the turn without `message_stop`, so a reply you render from stream events could stay shown as in progress. The TypeScript Agent SDK bundles Claude Code v2.1.290 or later from v0.3.290, and the Python Agent SDK from v0.2.164. If a reply stays shown as in progress after the turn ends, update the SDK.
-##
-
-
-
-Stream tool calls
+## Stream tool calls
Tool calls also stream incrementally. You can track when tools start, receive their input as it’s generated, and see when they complete. The example below tracks the current tool being called and accumulates the JSON input as it streams in. It uses three event types:
@@ -218,11 +198,7 @@
}
}
-##
-
-
-
-Build a streaming UI
+## Build a streaming UI
This example combines text and tool streaming into a cohesive UI. It tracks whether the agent is currently executing a tool (using an `in_tool` flag) to show status indicators like `[Using Read...]` while tools run. Text streams normally when not in a tool, and tool completion triggers a “done” message. This pattern is useful for chat interfaces that need to show progress during multi-step agent tasks.
@@ -317,19 +293,11 @@
}
}
-##
-
-
-
-Known limitations
+## Known limitations
* **Structured output** : with partial messages enabled, the JSON streams as a tool call’s unvalidated `input_json_delta` chunks, and only the validated result reaches the final `ResultMessage.structured_output`. [Recognize the StructuredOutput tool call](</docs/en/agent-sdk/structured-outputs#recognize-the-structuredoutput-tool-call>) covers how that call appears in your stream.
-##
-
-
-
-Next steps
+## Next steps
Now that you can stream text and tool calls in real-time, explore these related topics:
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -112,7 +112,12 @@
Handle a stream that’s cut off
-If a stream is cut off mid-message, such as when you interrupt the turn or the connection drops, you still receive that message’s `message_stop` before the turn ends. A cut text or thinking block also gets its `content_block_stop`. A cut tool call doesn’t, so if `message_stop` arrives while a tool call’s block is still open, treat that call’s input as incomplete. Before Claude Code v2.1.290, a cut stream could end the turn without `message_stop`, so a reply you render from stream events could stay shown as in progress. The TypeScript Agent SDK bundles Claude Code v2.1.290 or later from v0.3.290, and the Python Agent SDK from v0.2.164. If a reply stays shown as in progress after the turn ends, update the SDK.
+If a stream is cut off mid-message, you still receive that message’s `message_stop` before the turn ends. Causes of a cut-off stream include an interrupted turn, a dropped connection, and a fallback to a non-streaming request. `content_block_stop` and `message_delta` can be missing before that `message_stop`:
+
+ * **`content_block_stop`** : arrives for the block that was open, unless that block is a tool call. If `message_stop` arrives while a tool call’s block is still open, treat that call’s input as incomplete.
+ * **`message_delta`** : arrives when you interrupt the turn, and can be missing after a dropped connection or a fallback to non-streaming, so don’t wait for one on a cut message.
+
+Before Claude Code v2.1.290, a cut stream could end the turn without `message_stop`, so a reply you render from stream events could stay shown as in progress. The TypeScript Agent SDK bundles Claude Code v2.1.290 or later from v0.3.290, and the Python Agent SDK from v0.2.164. If a reply stays shown as in progress after the turn ends, update the SDK.
##
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -318,7 +318,7 @@
Known limitations
- * **Structured output** : with partial messages enabled, the JSON streams as a tool call’s unvalidated `input_json_delta` chunks, and only the validated result reaches the final `ResultMessage.structured_output`. See [structured outputs](</docs/en/agent-sdk/structured-outputs>) for details.
+ * **Structured output** : with partial messages enabled, the JSON streams as a tool call’s unvalidated `input_json_delta` chunks, and only the validated result reaches the final `ResultMessage.structured_output`. [Recognize the StructuredOutput tool call](</docs/en/agent-sdk/structured-outputs#recognize-the-structuredoutput-tool-call>) covers how that call appears in your stream.
##
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -106,6 +106,14 @@
Without partial messages enabled, you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete content blocks), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
+###
+
+
+
+Handle a stream that’s cut off
+
+If a stream is cut off mid-message, such as when you interrupt the turn or the connection drops, you still receive that message’s `message_stop` before the turn ends. A cut text or thinking block also gets its `content_block_stop`. A cut tool call doesn’t, so if `message_stop` arrives while a tool call’s block is still open, treat that call’s input as incomplete. Before Claude Code v2.1.290, a cut stream could end the turn without `message_stop`, so a reply you render from stream events could stay shown as in progress. The TypeScript Agent SDK bundles Claude Code v2.1.290 or later from v0.3.290, and the Python Agent SDK from v0.2.164. If a reply stays shown as in progress after the turn ends, update the SDK.
+
##
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -310,7 +310,7 @@
Known limitations
- * **Structured output** : the JSON result appears only in the final `ResultMessage.structured_output`, not as streaming deltas. See [structured outputs](</docs/en/agent-sdk/structured-outputs>) for details.
+ * **Structured output** : with partial messages enabled, the JSON streams as a tool call’s unvalidated `input_json_delta` chunks, and only the validated result reaches the final `ResultMessage.structured_output`. See [structured outputs](</docs/en/agent-sdk/structured-outputs>) for details.
##
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -67,33 +67,10 @@
When partial messages are enabled, you receive raw Claude API streaming events wrapped in an object. The type has different names in each SDK:
- * **Python** : `StreamEvent` (import from `claude_agent_sdk.types`)
- * **TypeScript** : `SDKPartialAssistantMessage` with `type: 'stream_event'`
-
-Both contain raw Claude API events, not accumulated text. You need to extract and accumulate text deltas yourself. Here’s the structure of each type:
-
-Python
-
-TypeScript
-
- @dataclass
- class StreamEvent:
- uuid: str # Unique identifier for this event
- session_id: str # Session identifier
- event: dict[str, Any] # The raw Claude API stream event
- parent_tool_use_id: str | None # Always None
-
- type SDKPartialAssistantMessage = {
- type: "stream_event";
- event: BetaRawMessageStreamEvent; // From Anthropic SDK
- parent_tool_use_id: string | null;
- uuid: UUID;
- session_id: string;
- ttft_ms?: number; // Time to first token in ms, present only on message_start events
- user_message_uuid?: string;
- };
-
-The `parent_tool_use_id` field is always `None` in Python and `null` in TypeScript. Stream events are emitted for the main session only; token-level deltas from subagents aren’t forwarded. To attribute output to a subagent, use complete messages, which carry `parent_tool_use_id`. See [Detect subagent invocation](</docs/en/agent-sdk/subagents#detect-subagent-invocation>). Claude Code sets `user_message_uuid` on the turn’s first non-ping stream event, and again when the message the turn is answering changes, under the conditions in [`user_message_uuid`](</docs/en/agent-sdk/typescript#user_message_uuid>). The Python `StreamEvent` doesn’t expose this field. The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
+ * **Python** : [`StreamEvent`](</docs/en/agent-sdk/python#streamevent>) (import from `claude_agent_sdk.types`)
+ * **TypeScript** : [`SDKPartialAssistantMessage`](</docs/en/agent-sdk/typescript#sdkpartialassistantmessage>) with `type: 'stream_event'`
+
+Both contain raw Claude API events, not accumulated text. You need to extract and accumulate text deltas yourself. The `parent_tool_use_id` field is always `None` in Python and `null` in TypeScript. Stream events are emitted for the main session only; token-level deltas from subagents aren’t forwarded. To attribute output to a subagent, use complete messages, which carry `parent_tool_use_id`. See [Detect subagent invocation](</docs/en/agent-sdk/subagents#detect-subagent-invocation>). Claude Code sets `user_message_uuid` on the turn’s first non-ping stream event, and again when the message the turn is answering changes, under the conditions in [`user_message_uuid`](</docs/en/agent-sdk/typescript#user_message_uuid>). The Python `StreamEvent` doesn’t expose this field. The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
Event Type| Description
---|---
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -1,4 +1,4 @@
-By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming.
+By default, the Agent SDK yields a complete `AssistantMessage` for each non-empty content block, such as a text block or a tool call, after Claude finishes generating that block. To receive incremental updates as text and tool calls are generated, enable partial message streaming.
This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
@@ -90,9 +90,10 @@
uuid: UUID;
session_id: string;
ttft_ms?: number; // Time to first token in ms, present only on message_start events
+ user_message_uuid?: string;
};
-The `parent_tool_use_id` field is always `None` in Python and `null` in TypeScript. Stream events are emitted for the main session only; token-level deltas from subagents aren’t forwarded. To attribute output to a subagent, use complete messages, which carry `parent_tool_use_id`. See [Detect subagent invocation](</docs/en/agent-sdk/subagents#detect-subagent-invocation>). The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
+The `parent_tool_use_id` field is always `None` in Python and `null` in TypeScript. Stream events are emitted for the main session only; token-level deltas from subagents aren’t forwarded. To attribute output to a subagent, use complete messages, which carry `parent_tool_use_id`. See [Detect subagent invocation](</docs/en/agent-sdk/subagents#detect-subagent-invocation>). Claude Code sets `user_message_uuid` on the turn’s first non-ping stream event, and again when the message the turn is answering changes, under the conditions in [`user_message_uuid`](</docs/en/agent-sdk/typescript#user_message_uuid>). The Python `StreamEvent` doesn’t expose this field. The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
Event Type| Description
---|---
@@ -109,23 +110,24 @@
Message flow
-With partial messages enabled, you receive messages in this order:
+Claude Code emits an `AssistantMessage` as each non-empty content block completes, so a response with a text block and a tool call yields two `AssistantMessage` objects. Each one carries only its own content block, and both share the same message ID, which you read as `message.message.id` in TypeScript and `message.message_id` in Python. With partial messages enabled, each `AssistantMessage` arrives before that block’s `content_block_stop` event, and you receive messages in this order:
StreamEvent (message_start)
StreamEvent (content_block_start) - text block
StreamEvent (content_block_delta) - text chunks...
+ AssistantMessage - complete text block
StreamEvent (content_block_stop)
StreamEvent (content_block_start) - tool_use block
StreamEvent (content_block_delta) - tool input chunks...
+ AssistantMessage - complete tool_use block
StreamEvent (content_block_stop)
StreamEvent (message_delta)
StreamEvent (message_stop)
- AssistantMessage - complete message with all content
... tool executes ...
... more streaming events for next turn ...
ResultMessage - final result
-Without partial messages enabled, you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete responses), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
+Without partial messages enabled, you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete content blocks), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
##
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -1,4 +1,4 @@
-By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming by setting `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options.
+By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming.
This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
@@ -125,55 +125,7 @@
... more streaming events for next turn ...
ResultMessage - final result
-Without partial messages enabled (`include_partial_messages` in Python, `includePartialMessages` in TypeScript), you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete responses), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
-
-##
-
-
-
-Stream text responses
-
-To display text as it’s generated, look for `content_block_delta` events where `delta.type` is `text_delta`. These contain the incremental text chunks. The example below prints each chunk as it arrives:
-
-Python
-
-TypeScript
-
- from claude_agent_sdk import query, ClaudeAgentOptions
- from claude_agent_sdk.types import StreamEvent
- import asyncio
-
- async def stream_text():
- options = ClaudeAgentOptions(include_partial_messages=True)
-
- async for message in query(prompt="Explain how databases work", options=options):
- if isinstance(message, StreamEvent):
- event = message.event
- if event.get("type") == "content_block_delta":
- delta = event.get("delta", {})
- if delta.get("type") == "text_delta":
- # Print each text chunk as it arrives
- print(delta.get("text", ""), end="", flush=True)
-
- print() # Final newline
-
- asyncio.run(stream_text())
-
- import { query } from "@anthropic-ai/claude-agent-sdk";
-
- for await (const message of query({
- prompt: "Explain how databases work",
- options: { includePartialMessages: true }
- })) {
- if (message.type === "stream_event") {
- const event = message.event;
- if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
- process.stdout.write(event.delta.text);
- }
- }
- }
-
- console.log(); // Final newline
+Without partial messages enabled, you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete responses), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
##
Show diff (160 lines)
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -40,6 +40,25 @@
asyncio.run(stream_response())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "List the files in my project",
+ options: {
+ includePartialMessages: true,
+ allowedTools: ["Bash", "Read"]
+ }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+ if (event.type === "content_block_delta") {
+ if (event.delta.type === "text_delta") {
+ process.stdout.write(event.delta.text);
+ }
+ }
+ }
+ }
+
##
@@ -63,6 +82,15 @@
session_id: str # Session identifier
event: dict[str, Any] # The raw Claude API stream event
parent_tool_use_id: str | None # Always None
+
+ type SDKPartialAssistantMessage = {
+ type: "stream_event";
+ event: BetaRawMessageStreamEvent; // From Anthropic SDK
+ parent_tool_use_id: string | null;
+ uuid: UUID;
+ session_id: string;
+ ttft_ms?: number; // Time to first token in ms, present only on message_start events
+ };
The `parent_tool_use_id` field is always `None` in Python and `null` in TypeScript. Stream events are emitted for the main session only; token-level deltas from subagents aren’t forwarded. To attribute output to a subagent, use complete messages, which carry `parent_tool_use_id`. See [Detect subagent invocation](</docs/en/agent-sdk/subagents#detect-subagent-invocation>). The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
@@ -131,6 +159,22 @@
asyncio.run(stream_text())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Explain how databases work",
+ options: { includePartialMessages: true }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+ if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
+ process.stdout.write(event.delta.text);
+ }
+ }
+ }
+
+ console.log(); // Final newline
+
##
@@ -190,6 +234,46 @@
asyncio.run(stream_tool_calls())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Track the current tool and accumulate its input JSON
+ let currentTool: string | null = null;
+ let toolInput = "";
+
+ for await (const message of query({
+ prompt: "Read the README.md file",
+ options: {
+ includePartialMessages: true,
+ allowedTools: ["Read", "Bash"]
+ }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+
+ if (event.type === "content_block_start") {
+ // New tool call is starting
+ if (event.content_block.type === "tool_use") {
+ currentTool = event.content_block.name;
+ toolInput = "";
+ console.log(`Starting tool: ${currentTool}`);
+ }
+ } else if (event.type === "content_block_delta") {
+ if (event.delta.type === "input_json_delta") {
+ // Accumulate JSON input as it streams in
+ const chunk = event.delta.partial_json;
+ toolInput += chunk;
+ console.log(` Input chunk: ${chunk}`);
+ }
+ } else if (event.type === "content_block_stop") {
+ // Tool call complete - show final input
+ if (currentTool) {
+ console.log(`Tool ${currentTool} called with: ${toolInput}`);
+ currentTool = null;
+ }
+ }
+ }
+ }
+
##
@@ -250,6 +334,45 @@
asyncio.run(streaming_ui())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Track whether we're currently in a tool call
+ let inTool = false;
+
+ for await (const message of query({
+ prompt: "Find all TODO comments in the codebase",
+ options: {
+ includePartialMessages: true,
+ allowedTools: ["Read", "Bash", "Grep"]
+ }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+
+ if (event.type === "content_block_start") {
+ if (event.content_block.type === "tool_use") {
+ // Tool call is starting - show status indicator
+ process.stdout.write(`\n[Using ${event.content_block.name}...]`);
+ inTool = true;
+ }
+ } else if (event.type === "content_block_delta") {
+ // Only stream text when not executing a tool
+ if (event.delta.type === "text_delta" && !inTool) {
+ process.stdout.write(event.delta.text);
+ }
+ } else if (event.type === "content_block_stop") {
+ if (inTool) {
+ // Tool call finished
+ console.log(" done");
+ inTool = false;
+ }
+ }
+ } else if (message.type === "result") {
+ // Agent finished all work
+ console.log("\n\n--- Complete ---");
+ }
+ }
+
##
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -62,9 +62,9 @@
uuid: str # Unique identifier for this event
session_id: str # Session identifier
event: dict[str, Any] # The raw Claude API stream event
- parent_tool_use_id: str | None # Parent tool ID if from a subagent
-
-The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
+ parent_tool_use_id: str | None # Always None
+
+The `parent_tool_use_id` field is always `None` in Python and `null` in TypeScript. Stream events are emitted for the main session only; token-level deltas from subagents aren’t forwarded. To attribute output to a subagent, use complete messages, which carry `parent_tool_use_id`. See [Detect subagent invocation](</docs/en/agent-sdk/subagents#detect-subagent-invocation>). The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
Event Type| Description
---|---
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -1,9 +1,3 @@
-> ## Documentation Index
->
-> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
->
-> Use this file to discover all available pages before exploring further.
-
By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming by setting `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options.
This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -262,9 +262,6 @@
Known limitations
-Some SDK features are incompatible with streaming:
-
- * **Extended thinking** : when you explicitly set `max_thinking_tokens` (Python) or `maxThinkingTokens` (TypeScript), `StreamEvent` messages are not emitted. You’ll only receive complete messages after each turn. Note that thinking is disabled by default in the SDK, so streaming works unless you enable it.
* **Structured output** : the JSON result appears only in the final `ResultMessage.structured_output`, not as streaming deltas. See [structured outputs](</docs/en/agent-sdk/structured-outputs>) for details.
##
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -1,3 +1,9 @@
+> ## Documentation Index
+>
+> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
+>
+> Use this file to discover all available pages before exploring further.
+
By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming by setting `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options.
This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
Show diff (277 lines)
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -0,0 +1,274 @@
+By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming by setting `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options.
+
+This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
+
+##
+
+
+
+Enable streaming output
+
+To enable streaming, set `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options. This causes the SDK to yield `StreamEvent` messages containing raw API events as they arrive, in addition to the usual `AssistantMessage` and `ResultMessage`. Your code then needs to:
+
+ 1. Check each message’s type to distinguish `StreamEvent` from other message types
+ 2. For `StreamEvent`, extract the `event` field and check its `type`
+ 3. Look for `content_block_delta` events where `delta.type` is `text_delta`, which contain the actual text chunks
+
+The example below enables streaming and prints text chunks as they arrive. Notice the nested type checks: first for `StreamEvent`, then for `content_block_delta`, then for `text_delta`:
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+
+ async def stream_response():
+ options = ClaudeAgentOptions(
+ include_partial_messages=True,
+ allowed_tools=["Bash", "Read"],
+ )
+
+ async for message in query(prompt="List the files in my project", options=options):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ if event.get("type") == "content_block_delta":
+ delta = event.get("delta", {})
+ if delta.get("type") == "text_delta":
+ print(delta.get("text", ""), end="", flush=True)
+
+ asyncio.run(stream_response())
+
+##
+
+
+
+StreamEvent reference
+
+When partial messages are enabled, you receive raw Claude API streaming events wrapped in an object. The type has different names in each SDK:
+
+ * **Python** : `StreamEvent` (import from `claude_agent_sdk.types`)
+ * **TypeScript** : `SDKPartialAssistantMessage` with `type: 'stream_event'`
+
+Both contain raw Claude API events, not accumulated text. You need to extract and accumulate text deltas yourself. Here’s the structure of each type:
+
+Python
+
+TypeScript
+
+ @dataclass
+ class StreamEvent:
+ uuid: str # Unique identifier for this event
+ session_id: str # Session identifier
+ event: dict[str, Any] # The raw Claude API stream event
+ parent_tool_use_id: str | None # Parent tool ID if from a subagent
+
+The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
+
+Event Type| Description
+---|---
+`message_start`| Start of a new message
+`content_block_start`| Start of a new content block (text or tool use)
+`content_block_delta`| Incremental update to content
+`content_block_stop`| End of a content block
+`message_delta`| Message-level updates (stop reason, usage)
+`message_stop`| End of the message
+
+##
+
+
+
+Message flow
+
+With partial messages enabled, you receive messages in this order:
+
+ StreamEvent (message_start)
+ StreamEvent (content_block_start) - text block
+ StreamEvent (content_block_delta) - text chunks...
+ StreamEvent (content_block_stop)
+ StreamEvent (content_block_start) - tool_use block
+ StreamEvent (content_block_delta) - tool input chunks...
+ StreamEvent (content_block_stop)
+ StreamEvent (message_delta)
+ StreamEvent (message_stop)
+ AssistantMessage - complete message with all content
+ ... tool executes ...
+ ... more streaming events for next turn ...
+ ResultMessage - final result
+
+Without partial messages enabled (`include_partial_messages` in Python, `includePartialMessages` in TypeScript), you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete responses), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
+
+##
+
+
+
+Stream text responses
+
+To display text as it’s generated, look for `content_block_delta` events where `delta.type` is `text_delta`. These contain the incremental text chunks. The example below prints each chunk as it arrives:
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+
+ async def stream_text():
+ options = ClaudeAgentOptions(include_partial_messages=True)
+
+ async for message in query(prompt="Explain how databases work", options=options):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ if event.get("type") == "content_block_delta":
+ delta = event.get("delta", {})
+ if delta.get("type") == "text_delta":
+ # Print each text chunk as it arrives
+ print(delta.get("text", ""), end="", flush=True)
+
+ print() # Final newline
+
+ asyncio.run(stream_text())
+
+##
+
+
+
+Stream tool calls
+
+Tool calls also stream incrementally. You can track when tools start, receive their input as it’s generated, and see when they complete. The example below tracks the current tool being called and accumulates the JSON input as it streams in. It uses three event types:
+
+ * `content_block_start`: tool begins
+ * `content_block_delta` with `input_json_delta`: input chunks arrive
+ * `content_block_stop`: tool call complete
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+
+ async def stream_tool_calls():
+ options = ClaudeAgentOptions(
+ include_partial_messages=True,
+ allowed_tools=["Read", "Bash"],
+ )
+
+ # Track the current tool and accumulate its input JSON
+ current_tool = None
+ tool_input = ""
+
+ async for message in query(prompt="Read the README.md file", options=options):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ event_type = event.get("type")
+
+ if event_type == "content_block_start":
+ # New tool call is starting
+ content_block = event.get("content_block", {})
+ if content_block.get("type") == "tool_use":
+ current_tool = content_block.get("name")
+ tool_input = ""
+ print(f"Starting tool: {current_tool}")
+
+ elif event_type == "content_block_delta":
+ delta = event.get("delta", {})
+ if delta.get("type") == "input_json_delta":
+ # Accumulate JSON input as it streams in
+ chunk = delta.get("partial_json", "")
+ tool_input += chunk
+ print(f" Input chunk: {chunk}")
+
+ elif event_type == "content_block_stop":
+ # Tool call complete - show final input
+ if current_tool:
+ print(f"Tool {current_tool} called with: {tool_input}")
+ current_tool = None
+
+ asyncio.run(stream_tool_calls())
+
+##
+
+
+
+Build a streaming UI
+
+This example combines text and tool streaming into a cohesive UI. It tracks whether the agent is currently executing a tool (using an `in_tool` flag) to show status indicators like `[Using Read...]` while tools run. Text streams normally when not in a tool, and tool completion triggers a “done” message. This pattern is useful for chat interfaces that need to show progress during multi-step agent tasks.
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+ import sys
+
+ async def streaming_ui():
+ options = ClaudeAgentOptions(
+ include_partial_messages=True,
+ allowed_tools=["Read", "Bash", "Grep"],
+ )
+
+ # Track whether we're currently in a tool call
+ in_tool = False
+
+ async for message in query(
+ prompt="Find all TODO comments in the codebase", options=options
+ ):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ event_type = event.get("type")
+
+ if event_type == "content_block_start":
+ content_block = event.get("content_block", {})
+ if content_block.get("type") == "tool_use":
+ # Tool call is starting - show status indicator
+ tool_name = content_block.get("name")
+ print(f"\n[Using {tool_name}...]", end="", flush=True)
+ in_tool = True
+
+ elif event_type == "content_block_delta":
+ delta = event.get("delta", {})
+ # Only stream text when not executing a tool
+ if delta.get("type") == "text_delta" and not in_tool:
+ sys.stdout.write(delta.get("text", ""))
+ sys.stdout.flush()
+
+ elif event_type == "content_block_stop":
+ if in_tool:
+ # Tool call finished
+ print(" done", flush=True)
+ in_tool = False
+
+ elif isinstance(message, ResultMessage):
+ # Agent finished all work
+ print(f"\n\n--- Complete ---")
+
+ asyncio.run(streaming_ui())
+
+##
+
+
+
+Known limitations
+
+Some SDK features are incompatible with streaming:
+
+ * **Extended thinking** : when you explicitly set `max_thinking_tokens` (Python) or `maxThinkingTokens` (TypeScript), `StreamEvent` messages are not emitted. You’ll only receive complete messages after each turn. Note that thinking is disabled by default in the SDK, so streaming works unless you enable it.
+ * **Structured output** : the JSON result appears only in the final `ResultMessage.structured_output`, not as streaming deltas. See [structured outputs](</docs/en/agent-sdk/structured-outputs>) for details.
+
+##
+
+
+
+Next steps
+
+Now that you can stream text and tool calls in real-time, explore these related topics:
+
+ * [Interactive vs one-shot queries](</docs/en/agent-sdk/streaming-vs-single-mode>): choose between input modes for your use case
+ * [Structured outputs](</docs/en/agent-sdk/structured-outputs>): get typed JSON responses from the agent
+ * [Permissions](</docs/en/agent-sdk/permissions>): control which tools the agent can use