Send messages to a running agent
Show diff (516 lines)
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -1,244 +1,298 @@
-## Overview
-
-The Claude Agent SDK supports two distinct input modes for interacting with agents:
-
- * **Streaming Input Mode** : a persistent, interactive session
- * **Single Message Input** : one-shot queries that use session state and resuming
-
-## Streaming Input Mode (Recommended)
-
-Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent’s capabilities and enables rich, interactive experiences. It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
-
-### Benefits
-
-In streaming input mode, you work in a persistent session with these capabilities:
-
- * **Image uploads** : attach images directly to messages for visual analysis and understanding
- * **Queued messages** : send multiple messages that process sequentially, with ability to interrupt
- * **Tool integration** : full access to all tools and custom MCP servers during the session
- * **Real-time feedback** : see responses as they’re generated, not just final results
- * **Context persistence** : maintain conversation context across multiple turns naturally
-
-### Implementation Example
-
-These examples read an image named `diagram.png` from the working directory. Create one there first, or change the filename to point at your own image.
+Streaming input keeps an Agent SDK session open so your application can send it more than one message while it runs. You can also attach images to a message and stop a response partway through to redirect Claude.
+
+Streaming input covers the messages you send. To show Claude’s response as it’s generated, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>).
+
+## Choose single-shot or streaming input
+
+Choose streaming input for an application that holds a conversation with Claude, such as a chat interface. Use streaming input to attach images to a message, interrupt a response, or [switch the model or permission mode](</docs/en/agent-sdk/configuration#change-configuration-mid-session>) while the session runs. A single-shot call passes one prompt string to `query()`. The call ends after Claude answers it. Single-shot fits a single task, such as a serverless function. To follow up after that call ends, start a new call that resumes the session. For more information, see [Continue, resume, and fork](</docs/en/agent-sdk/sessions#continue-resume-and-fork>).
+
+## Send more than one message to a session
+
+ * **TypeScript** : write an [async generator](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function%2A>) that yields [`SDKUserMessage`](</docs/en/agent-sdk/typescript#sdkusermessage>) objects, and pass it as the `prompt` of `query()`. Make the generator wait between yields for the next message from your user.
+ * **Python** : open a `ClaudeSDKClient` and pass each message to `client.query()`. Pass a string for a text message. To attach an image, pass an [async generator](<https://docs.python.org/3/glossary.html#term-asynchronous-generator>) that yields user message dicts.
+
+To have Claude answer each message in its own response, wait for the previous response’s result message before you send the next one:
+
+ * **TypeScript** : have your generator await a promise. Resolve it in your `for await` loop over `query()` when the result message arrives.
+ * **Python** : call `client.query()` with the next message after your [`receive_response()`](</docs/en/agent-sdk/python#claudesdkclient>) loop ends.
+
+A message you send during tool calls reaches Claude after those tool calls finish. Claude then answers it and your earlier message in one response. If the turn ends first, Claude starts a new turn for it. For details, see [Turns and budget](</docs/en/agent-sdk/agent-loop#turns-and-budget>).
+
+### Send a follow-up with an image
+
+This example sends a text question, then a follow-up with an image, and prints Claude’s response to each. Before you run it, save a PNG image as `diagram.png` in your working directory:
TypeScript
Python
+ import { readFile } from "node:fs/promises";
import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
- import { readFile } from "fs/promises";
-
- async function* generateMessages(): AsyncGenerator<SDKUserMessage> {
- // First message
- yield {
- type: "user",
- message: {
- role: "user",
- content: "Analyze this codebase for security issues"
- },
- parent_tool_use_id: null
- };
-
- // Wait for conditions or user input
- await new Promise((resolve) => setTimeout(resolve, 2000));
-
- // Follow-up with image
+
+ let firstResponseDone!: () => void;
+ const firstResponseFinished = new Promise<void>((resolve) => {
+ firstResponseDone = resolve;
+ });
+
+ async function* messages(): AsyncGenerator<SDKUserMessage> {
+ yield {
+ type: "user",
+ message: {
+ role: "user",
+ content: "Explain in two sentences what a message queue does.",
+ },
+ parent_tool_use_id: null,
+ };
+
+ await firstResponseFinished;
+
+ const image = await readFile("diagram.png");
yield {
type: "user",
message: {
role: "user",
content: [
- {
- type: "text",
- text: "Review this architecture diagram"
- },
+ { type: "text", text: "Describe this image in one sentence." },
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
- data: await readFile("diagram.png", "base64")
- }
- }
- ]
- },
- parent_tool_use_id: null
- };
- }
-
- // Process streaming responses
- for await (const message of query({
- prompt: generateMessages(),
- options: {
- maxTurns: 10,
- allowedTools: ["Read", "Grep"]
+ data: image.toString("base64"),
+ },
+ },
+ ],
+ },
+ parent_tool_use_id: null,
+ };
+ }
+
+ let responses = 0;
+ for await (const message of query({ prompt: messages() })) {
+ if (message.type === "assistant") {
+ for (const block of message.message.content) {
+ if (block.type === "text") {
+ console.log(block.text);
+ }
+ }
+ } else if (message.type === "result") {
+ responses += 1;
+ console.log(`Response ${responses} finished: ${message.subtype}`);
+ if (responses === 1) {
+ firstResponseDone();
+ }
}
- })) {
- if (message.type === "result" && message.subtype === "success") {
- console.log(message.result);
- }
- }
-
- from claude_agent_sdk import (
- ClaudeSDKClient,
- ClaudeAgentOptions,
- AssistantMessage,
- TextBlock,
- )
+ }
+
import asyncio
import base64
-
- async def streaming_analysis():
- async def message_generator():
- # First message
- yield {
- "type": "user",
- "message": {
- "role": "user",
- "content": "Analyze this codebase for security issues",
- },
- }
-
- # Wait for conditions
- await asyncio.sleep(2)
-
- # Follow-up with image
- with open("diagram.png", "rb") as f:
- image_data = base64.b64encode(f.read()).decode()
-
- yield {
- "type": "user",
- "message": {
- "role": "user",
- "content": [
- {"type": "text", "text": "Review this architecture diagram"},
- {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": "image/png",
- "data": image_data,
- },
+ from pathlib import Path
+
+ from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
+
+ async def image_message():
+ image_data = base64.b64encode(Path("diagram.png").read_bytes()).decode()
+ yield {
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Describe this image in one sentence."},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": image_data,
},
- ],
- },
- }
-
- # Use ClaudeSDKClient for streaming input
- options = ClaudeAgentOptions(max_turns=10, allowed_tools=["Read", "Grep"])
-
- async with ClaudeSDKClient(options) as client:
- # Send streaming input
- await client.query(message_generator())
-
- # Process responses
- async for message in client.receive_response():
- if isinstance(message, AssistantMessage):
- for block in message.content:
- if isinstance(block, TextBlock):
- print(block.text)
-
- asyncio.run(streaming_analysis())
-
-When you run the example, the TypeScript version prints each response as it completes. The Python version’s `receive_response()` loop ends at the first result message, so it prints the security analysis; to read both responses, use one `query()` and `receive_response()` pair per message as shown in the [Python reference’s example of continuing a conversation](</docs/en/agent-sdk/python#example-continuing-a-conversation>). If an image block’s `source` is missing or isn’t an object, the SDK doesn’t report an error. Claude Code sends Claude a text note in place of the image, such as `[Image could not be processed: image block has no source object]`, and the session continues.
-
-In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
-
-## Single Message Input
-
-Single message input is simpler but more limited.
-
-### When to Use Single Message Input
-
-Use single message input when:
-
- * You need a one-shot response
- * You do not need image attachments or mid-session control methods
- * You need to operate in a stateless environment, such as a lambda function
-
-### Limitations
-
-Single message input mode does **not** support:
-
- * Direct image attachments in messages
- * Dynamic message queueing
- * Real-time interruption
- * Natural multi-turn conversations
-
-If a query ends with an error result, such as `error_max_turns`, a single message `query()` call raises an error that includes the failure text after yielding the final result message, so wrap the loop in a try block if your code needs to continue. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the result subtypes.
-
-### Implementation Example
+ },
+ ],
+ },
+ }
+
+ async def main():
+ async with ClaudeSDKClient() as client:
+ await client.query("Explain in two sentences what a message queue does.")
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+ elif isinstance(message, ResultMessage):
+ print(f"Response 1 finished: {message.subtype}")
+
+ await client.query(image_message())
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+ elif isinstance(message, ResultMessage):
+ print(f"Response 2 finished: {message.subtype}")
+
+ asyncio.run(main())
+
+When you run either version, the example prints `Response 1 finished: success` and `Response 2 finished: success`. If Claude didn’t see your image, see [Image could not be processed](</docs/en/agent-sdk/troubleshooting#image-could-not-be-processed>).
+
+### Feed messages from a chat interface in TypeScript
+
+Feed your user’s messages to your prompt generator through a queue:
+
+ * **`pushMessage()`** : your interface’s input handler calls this for each message the user sends.
+ * **`closeInput()`** : the handler calls this when the user closes the chat.
+ * **`userMessages()`** : the generator you pass as the `prompt` of `query()`.
+
+`pushMessage()` adds each message to an array, and the generator reads from that array. When the array is empty, the generator waits until a message arrives or the chat closes:
+
+ import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
+
+ const pending: string[] = [];
+ let wake: (() => void) | null = null;
+ let closed = false;
+
+ // The interface's input handler calls this with each message the user sends.
+ function pushMessage(text: string): void {
+ pending.push(text);
+ wake?.();
+ }
+
+ // The interface calls this when the user closes the chat.
+ function closeInput(): void {
+ closed = true;
+ wake?.();
+ }
+
+ async function* userMessages(): AsyncGenerator<SDKUserMessage> {
+ while (true) {
+ const text = pending.shift();
+ if (text !== undefined) {
+ yield { type: "user", message: { role: "user", content: text }, parent_tool_use_id: null };
+ } else if (closed) {
+ return;
+ } else {
+ await new Promise<void>((resolve) => (wake = resolve));
+ wake = null;
+ }
+ }
+ }
+
+Messages you push during a response can share one response. To choose when Claude reads a message you push during a response, set the message’s [`priority`](</docs/en/agent-sdk/typescript#sdkusermessage>) field.
+
+## Read each response
+
+Claude ends each response with a result message.
+
+ * **TypeScript** : the `for await` loop over `query()` yields each response’s messages in order. The loop ends after the last response’s result message, once your generator has returned. To match a result to the messages it answers, set a `uuid` on each message you send, and read the result’s [`user_message_uuids`](</docs/en/agent-sdk/typescript#user_message_uuids>).
+ * **Python** : start a `receive_response()` loop for each response, because each loop stops after the next [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>). The client keeps the conversation’s context from one message to the next. For more information, see [Automatic session management](</docs/en/agent-sdk/sessions#automatic-session-management>).
+
+The result message’s `subtype` field reports how the response ended, such as `success` or `error_during_execution`. If the last response ends in an error result:
+
+ * **TypeScript** : the loop over `query()` yields that result and then throws. Wrap the loop in `try`/`catch` to handle the exception. To keep the conversation going after the throw, start a new `query()` call that [resumes the session](</docs/en/agent-sdk/sessions#continue-resume-and-fork>). While your generator still has messages to send, an error result for an earlier response doesn’t throw.
+ * **Python** : `receive_response()` on a `ClaudeSDKClient` yields the error result without raising.
+
+For what each result subtype means, see [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>).
+
+## Interrupt Claude’s response
+
+To stop a response partway through and keep the session open, call `interrupt()` on the object that runs the session:
+
+ * **TypeScript** : pass an async generator as `prompt`, save the [`Query` object](</docs/en/agent-sdk/typescript#query-object>) returned by `query()`, and call `interrupt()` on it.
+ * **Python** : call `interrupt()` on the `ClaudeSDKClient`. If a `receive_response()` loop is reading the response, that loop ends at the interrupted response’s `ResultMessage`. Send your next message after that result arrives.
+
+When you call `interrupt()` during a response, that response ends with an `error_during_execution` result. Messages you sent before the interrupt that Claude hadn’t read yet still reach Claude once the interrupted response ends. For what the TypeScript loop does when the last response is an error result, see Read each response. This example asks Claude for a long essay. The example calls `interrupt()` three seconds after the session starts, then sends a second message to the same session once the interrupted response ends:
TypeScript
Python
- import { query } from "@anthropic-ai/claude-agent-sdk";
-
- // Simple one-shot query
- // query() throws after an error result, such as error_max_turns
- try {
- for await (const message of query({
- prompt: "Explain the authentication flow",
- options: {
- maxTurns: 5,
- allowedTools: ["Read", "Grep"]
- }
- })) {
- if (message.type === "result" && message.subtype === "success") {
- console.log(message.result);
+ import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
+
+ let firstResponseDone!: () => void;
+ const firstResponseFinished = new Promise<void>((resolve) => {
+ firstResponseDone = resolve;
+ });
+
+ async function* messages(): AsyncGenerator<SDKUserMessage> {
+ yield {
+ type: "user",
+ message: {
+ role: "user",
+ content: "Write a 2,000-word essay on the history of the printing press.",
+ },
+ parent_tool_use_id: null,
+ };
+
+ await firstResponseFinished;
+
+ yield {
+ type: "user",
+ message: {
+ role: "user",
+ content: "In one sentence, what is a prime number?",
+ },
+ parent_tool_use_id: null,
+ };
+ }
+
+ const conversation = query({ prompt: messages() });
+
+ let responses = 0;
+ for await (const message of conversation) {
+ if (message.type === "system" && message.subtype === "init" && responses === 0) {
+ setTimeout(async () => {
+ await conversation.interrupt();
+ console.log("Interrupt sent");
+ }, 3000);
+ } else if (message.type === "assistant") {
+ for (const block of message.message.content) {
+ if (block.type === "text") {
+ console.log(block.text);
+ }
+ }
+ } else if (message.type === "result") {
+ responses += 1;
+ console.log(`Response ${responses} finished: ${message.subtype}`);
+ if (responses === 1) {
+ firstResponseDone();
}
}
- } catch (error) {
- console.error(`Query failed: ${error}`);
- }
-
- // Continue conversation with session management
- try {
- for await (const message of query({
- prompt: "Now explain the authorization process",
- options: {
- continue: true,
- maxTurns: 5
- }
- })) {
- if (message.type === "result" && message.subtype === "success") {
- console.log(message.result);
- }
- }
- } catch (error) {
- console.error(`Query failed: ${error}`);
- }
-
- from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+ }
+
import asyncio
- async def single_message_example():
- # Simple one-shot query using query() function
- # query() raises ResultError after an error result, such as error_max_turns
- try:
- async for message in query(
- prompt="Explain the authentication flow",
- options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),
- ):
- if isinstance(message, ResultMessage) and message.subtype == "success":
- print(message.result)
- except Exception as e:
- print(f"Query failed: {e}")
-
- # Continue conversation with session management
- try:
- async for message in query(
- prompt="Now explain the authorization process",
- options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),
- ):
- if isinstance(message, ResultMessage) and message.subtype == "success":
- print(message.result)
- except Exception as e:
- print(f"Query failed: {e}")
-
- asyncio.run(single_message_example())
-
-When you run the example, each query prints its final result text: first the authentication explanation, then the authorization explanation.
+ from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
+
+ async def main():
+ async with ClaudeSDKClient() as client:
+ await client.query("Write a 2,000-word essay on the history of the printing press.")
+ await asyncio.sleep(3)
+ await client.interrupt()
+ print("Interrupt sent")
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+ elif isinstance(message, ResultMessage):
+ print(f"Response 1 finished: {message.subtype}")
+
+ await client.query("In one sentence, what is a prime number?")
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+ elif isinstance(message, ResultMessage):
+ print(f"Response 2 finished: {message.subtype}")
+
+ asyncio.run(main())
+
+When you run either version, the first response stops partway through the essay, and the example prints `Response 1 finished: error_during_execution`. Claude then answers the second message. The output ends with `Response 2 finished: success`.
+
+## Next steps
+
+ * [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>): show text and tool calls as Claude generates them
+ * [Handle approvals and user input](</docs/en/agent-sdk/user-input>): answer Claude’s permission requests and clarifying questions
+ * [Change configuration mid-session](</docs/en/agent-sdk/configuration#change-configuration-mid-session>): switch the model or permission mode while the session runs
+ * [`Query` object](</docs/en/agent-sdk/typescript#query-object>) in TypeScript and [`ClaudeSDKClient`](</docs/en/agent-sdk/python#claudesdkclient>) in Python: the methods that send messages to a running session or control it
+ * [Work with sessions](</docs/en/agent-sdk/sessions>): resume, continue, or fork a conversation
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -1,27 +1,15 @@
-##
-
-
-
-Overview
+## Overview
The Claude Agent SDK supports two distinct input modes for interacting with agents:
* **Streaming Input Mode** : a persistent, interactive session
* **Single Message Input** : one-shot queries that use session state and resuming
-##
-
-
-
-Streaming Input Mode (Recommended)
+## Streaming Input Mode (Recommended)
Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent’s capabilities and enables rich, interactive experiences. It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
-###
-
-
-
-Benefits
+### Benefits
In streaming input mode, you work in a persistent session with these capabilities:
@@ -31,11 +19,7 @@
* **Real-time feedback** : see responses as they’re generated, not just final results
* **Context persistence** : maintain conversation context across multiple turns naturally
-###
-
-
-
-Implementation Example
+### Implementation Example
These examples read an image named `diagram.png` from the working directory. Create one there first, or change the filename to point at your own image.
@@ -162,19 +146,11 @@
In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
-##
-
-
-
-Single Message Input
+## Single Message Input
Single message input is simpler but more limited.
-###
-
-
-
-When to Use Single Message Input
+### When to Use Single Message Input
Use single message input when:
@@ -182,11 +158,7 @@
* You do not need image attachments or mid-session control methods
* You need to operate in a stateless environment, such as a lambda function
-###
-
-
-
-Limitations
+### Limitations
Single message input mode does **not** support:
@@ -197,11 +169,7 @@
If a query ends with an error result, such as `error_max_turns`, a single message `query()` call raises an error that includes the failure text after yielding the final result message, so wrap the loop in a try block if your code needs to continue. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the result subtypes.
-###
-
-
-
-Implementation Example
+### Implementation Example
TypeScript
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -158,7 +158,7 @@
asyncio.run(streaming_analysis())
-When you run the example, the TypeScript version prints each response as it completes. The Python version’s `receive_response()` loop ends at the first result message, so it prints the security analysis; to read both responses, use one `query()` and `receive_response()` pair per message as shown in the [Python reference’s example of continuing a conversation](</docs/en/agent-sdk/python#example-continuing-a-conversation>).
+When you run the example, the TypeScript version prints each response as it completes. The Python version’s `receive_response()` loop ends at the first result message, so it prints the security analysis; to read both responses, use one `query()` and `receive_response()` pair per message as shown in the [Python reference’s example of continuing a conversation](</docs/en/agent-sdk/python#example-continuing-a-conversation>). If an image block’s `source` is missing or isn’t an object, the SDK doesn’t report an error. Claude Code sends Claude a text note in place of the image, such as `[Image could not be processed: image block has no source object]`, and the session continues.
In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -16,12 +16,6 @@
Streaming Input Mode (Recommended)
Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent’s capabilities and enables rich, interactive experiences. It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
-
-###
-
-
-
-How It Works
###
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -255,7 +255,7 @@
async def single_message_example():
# Simple one-shot query using query() function
- # query() raises after an error result, such as error_max_turns
+ # query() raises ResultError after an error result, such as error_max_turns
try:
async for message in query(
prompt="Explain the authentication flow",
@@ -263,7 +263,6 @@
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
- # The SDK raises a plain Exception for error results, so match Exception here
except Exception as e:
print(f"Query failed: {e}")
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -9,8 +9,6 @@
* **Streaming Input Mode** : a persistent, interactive session
* **Single Message Input** : one-shot queries that use session state and resuming
-This guide explains the differences, benefits, and use cases for each mode to help you choose the right approach for your application.
-
##
@@ -31,25 +29,13 @@
Benefits
-## Image Uploads
-
-Attach images directly to messages for visual analysis and understanding
-
-## Queued Messages
-
-Send multiple messages that process sequentially, with ability to interrupt
-
-## Tool Integration
-
-Full access to all tools and custom MCP servers during the session
-
-## Real-time Feedback
-
-See responses as they’re generated, not just final results
-
-## Context Persistence
-
-Maintain conversation context across multiple turns naturally
+In streaming input mode, you work in a persistent session with these capabilities:
+
+ * **Image uploads** : attach images directly to messages for visual analysis and understanding
+ * **Queued messages** : send multiple messages that process sequentially, with ability to interrupt
+ * **Tool integration** : full access to all tools and custom MCP servers during the session
+ * **Real-time feedback** : see responses as they’re generated, not just final results
+ * **Context persistence** : maintain conversation context across multiple turns naturally
###
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -6,8 +6,8 @@
The Claude Agent SDK supports two distinct input modes for interacting with agents:
- * **Streaming Input Mode** (Default & Recommended) - A persistent, interactive session
- * **Single Message Input** \- One-shot queries that use session state and resuming
+ * **Streaming Input Mode** : a persistent, interactive session
+ * **Single Message Input** : one-shot queries that use session state and resuming
This guide explains the differences, benefits, and use cases for each mode to help you choose the right approach for your application.
Show diff (121 lines)
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -56,6 +56,8 @@
Implementation Example
+
+These examples read an image named `diagram.png` from the working directory. Create one there first, or change the filename to point at your own image.
TypeScript
@@ -176,6 +178,8 @@
asyncio.run(streaming_analysis())
+When you run the example, the TypeScript version prints each response as it completes. The Python version’s `receive_response()` loop ends at the first result message, so it prints the security analysis; to read both responses, use one `query()` and `receive_response()` pair per message as shown in the [Python reference’s example of continuing a conversation](</docs/en/agent-sdk/python#example-continuing-a-conversation>).
+
In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
##
@@ -226,29 +230,38 @@
import { query } from "@anthropic-ai/claude-agent-sdk";
// Simple one-shot query
- for await (const message of query({
- prompt: "Explain the authentication flow",
- options: {
- maxTurns: 1,
- allowedTools: ["Read", "Grep"]
- }
- })) {
- if (message.type === "result" && message.subtype === "success") {
- console.log(message.result);
- }
+ // query() throws after an error result, such as error_max_turns
+ try {
+ for await (const message of query({
+ prompt: "Explain the authentication flow",
+ options: {
+ maxTurns: 5,
+ allowedTools: ["Read", "Grep"]
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
+ } catch (error) {
+ console.error(`Query failed: ${error}`);
}
// Continue conversation with session management
- for await (const message of query({
- prompt: "Now explain the authorization process",
- options: {
- continue: true,
- maxTurns: 1
- }
- })) {
- if (message.type === "result" && message.subtype === "success") {
- console.log(message.result);
- }
+ try {
+ for await (const message of query({
+ prompt: "Now explain the authorization process",
+ options: {
+ continue: true,
+ maxTurns: 5
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
+ } catch (error) {
+ console.error(`Query failed: ${error}`);
}
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
@@ -256,19 +269,29 @@
async def single_message_example():
# Simple one-shot query using query() function
- async for message in query(
- prompt="Explain the authentication flow",
- options=ClaudeAgentOptions(max_turns=1, allowed_tools=["Read", "Grep"]),
- ):
- if isinstance(message, ResultMessage):
- print(message.result)
+ # query() raises after an error result, such as error_max_turns
+ try:
+ async for message in query(
+ prompt="Explain the authentication flow",
+ options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+ # The SDK raises a plain Exception for error results, so match Exception here
+ except Exception as e:
+ print(f"Query failed: {e}")
# Continue conversation with session management
- async for message in query(
- prompt="Now explain the authorization process",
- options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
- ):
- if isinstance(message, ResultMessage):
- print(message.result)
+ try:
+ async for message in query(
+ prompt="Now explain the authorization process",
+ options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+ except Exception as e:
+ print(f"Query failed: {e}")
asyncio.run(single_message_example())
+
+When you run the example, each query prints its final result text: first the authentication explanation, then the authorization explanation.
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -115,6 +115,67 @@
}
}
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ AssistantMessage,
+ TextBlock,
+ )
+ import asyncio
+ import base64
+
+ async def streaming_analysis():
+ async def message_generator():
+ # First message
+ yield {
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": "Analyze this codebase for security issues",
+ },
+ }
+
+ # Wait for conditions
+ await asyncio.sleep(2)
+
+ # Follow-up with image
+ with open("diagram.png", "rb") as f:
+ image_data = base64.b64encode(f.read()).decode()
+
+ yield {
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Review this architecture diagram"},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": image_data,
+ },
+ },
+ ],
+ },
+ }
+
+ # Use ClaudeSDKClient for streaming input
+ options = ClaudeAgentOptions(max_turns=10, allowed_tools=["Read", "Grep"])
+
+ async with ClaudeSDKClient(options) as client:
+ # Send streaming input
+ await client.query(message_generator())
+
+ # Process responses
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+
+ asyncio.run(streaming_analysis())
+
In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
##
@@ -189,3 +250,25 @@
console.log(message.result);
}
}
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+ import asyncio
+
+ async def single_message_example():
+ # Simple one-shot query using query() function
+ async for message in query(
+ prompt="Explain the authentication flow",
+ options=ClaudeAgentOptions(max_turns=1, allowed_tools=["Read", "Grep"]),
+ ):
+ if isinstance(message, ResultMessage):
+ print(message.result)
+
+ # Continue conversation with session management
+ async for message in query(
+ prompt="Now explain the authorization process",
+ options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
+ ):
+ if isinstance(message, ResultMessage):
+ print(message.result)
+
+ asyncio.run(single_message_example())
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -115,6 +115,8 @@
}
}
+In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
+
##
@@ -147,6 +149,8 @@
* Dynamic message queueing
* Real-time interruption
* Natural multi-turn conversations
+
+If a query ends with an error result, such as `error_max_turns`, a single message `query()` call raises an error that includes the failure text after yielding the final result message, so wrap the loop in a try block if your code needs to continue. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the result subtypes.
###
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.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.
-
##
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -48,10 +48,6 @@
## Tool Integration
Full access to all tools and custom MCP servers during the session
-
-## Hooks Support
-
-Use lifecycle hooks to customize behavior at various points
## Real-time Feedback
@@ -142,7 +138,7 @@
Use single message input when:
* You need a one-shot response
- * You do not need image attachments, hooks, etc.
+ * You do not need image attachments or mid-session control methods
* You need to operate in a stateless environment, such as a lambda function
###
@@ -156,7 +152,6 @@
* Direct image attachments in messages
* Dynamic message queueing
* Real-time interruption
- * Hook integration
* Natural multi-turn conversations
###
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -71,17 +71,18 @@
Python
- import { query } from "@anthropic-ai/claude-agent-sdk";
+ import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
import { readFile } from "fs/promises";
- async function* generateMessages() {
+ async function* generateMessages(): AsyncGenerator<SDKUserMessage> {
// First message
yield {
- type: "user" as const,
+ type: "user",
message: {
- role: "user" as const,
+ role: "user",
content: "Analyze this codebase for security issues"
- }
+ },
+ parent_tool_use_id: null
};
// Wait for conditions or user input
@@ -89,9 +90,9 @@
// Follow-up with image
yield {
- type: "user" as const,
+ type: "user",
message: {
- role: "user" as const,
+ role: "user",
content: [
{
type: "text",
@@ -106,7 +107,8 @@
}
}
]
- }
+ },
+ parent_tool_use_id: null
};
}
@@ -118,7 +120,7 @@
allowedTools: ["Read", "Grep"]
}
})) {
- if (message.type === "result") {
+ if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
@@ -177,7 +179,7 @@
allowedTools: ["Read", "Grep"]
}
})) {
- if (message.type === "result") {
+ if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
@@ -190,7 +192,7 @@
maxTurns: 1
}
})) {
- if (message.type === "result") {
+ if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.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.
+
##
Show diff (193 lines)
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -0,0 +1,190 @@
+##
+
+
+
+Overview
+
+The Claude Agent SDK supports two distinct input modes for interacting with agents:
+
+ * **Streaming Input Mode** (Default & Recommended) - A persistent, interactive session
+ * **Single Message Input** \- One-shot queries that use session state and resuming
+
+This guide explains the differences, benefits, and use cases for each mode to help you choose the right approach for your application.
+
+##
+
+
+
+Streaming Input Mode (Recommended)
+
+Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent’s capabilities and enables rich, interactive experiences. It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
+
+###
+
+
+
+How It Works
+
+###
+
+
+
+Benefits
+
+## Image Uploads
+
+Attach images directly to messages for visual analysis and understanding
+
+## Queued Messages
+
+Send multiple messages that process sequentially, with ability to interrupt
+
+## Tool Integration
+
+Full access to all tools and custom MCP servers during the session
+
+## Hooks Support
+
+Use lifecycle hooks to customize behavior at various points
+
+## Real-time Feedback
+
+See responses as they’re generated, not just final results
+
+## Context Persistence
+
+Maintain conversation context across multiple turns naturally
+
+###
+
+
+
+Implementation Example
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+ import { readFile } from "fs/promises";
+
+ async function* generateMessages() {
+ // First message
+ yield {
+ type: "user" as const,
+ message: {
+ role: "user" as const,
+ content: "Analyze this codebase for security issues"
+ }
+ };
+
+ // Wait for conditions or user input
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ // Follow-up with image
+ yield {
+ type: "user" as const,
+ message: {
+ role: "user" as const,
+ content: [
+ {
+ type: "text",
+ text: "Review this architecture diagram"
+ },
+ {
+ type: "image",
+ source: {
+ type: "base64",
+ media_type: "image/png",
+ data: await readFile("diagram.png", "base64")
+ }
+ }
+ ]
+ }
+ };
+ }
+
+ // Process streaming responses
+ for await (const message of query({
+ prompt: generateMessages(),
+ options: {
+ maxTurns: 10,
+ allowedTools: ["Read", "Grep"]
+ }
+ })) {
+ if (message.type === "result") {
+ console.log(message.result);
+ }
+ }
+
+##
+
+
+
+Single Message Input
+
+Single message input is simpler but more limited.
+
+###
+
+
+
+When to Use Single Message Input
+
+Use single message input when:
+
+ * You need a one-shot response
+ * You do not need image attachments, hooks, etc.
+ * You need to operate in a stateless environment, such as a lambda function
+
+###
+
+
+
+Limitations
+
+Single message input mode does **not** support:
+
+ * Direct image attachments in messages
+ * Dynamic message queueing
+ * Real-time interruption
+ * Hook integration
+ * Natural multi-turn conversations
+
+###
+
+
+
+Implementation Example
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Simple one-shot query
+ for await (const message of query({
+ prompt: "Explain the authentication flow",
+ options: {
+ maxTurns: 1,
+ allowedTools: ["Read", "Grep"]
+ }
+ })) {
+ if (message.type === "result") {
+ console.log(message.result);
+ }
+ }
+
+ // Continue conversation with session management
+ for await (const message of query({
+ prompt: "Now explain the authorization process",
+ options: {
+ continue: true,
+ maxTurns: 1
+ }
+ })) {
+ if (message.type === "result") {
+ console.log(message.result);
+ }
+ }