Follow Discord
Sweep 20 Nov 2026 · 19:55Z Build v2.1.330 547 read Stable v2.1.323 Latest v2.1.330 Next v2.1.330 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One change · claude-code

Send messages to a running agent changedagent-sdk/streaming-vs-single-mode

Nearest release: v2.1.326, published 3 hours before upstream edited the page. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.

Upstream edited this page at 16 Nov 2026 21:51 UTC, give or take a minute or two: the time comes from Anthropic’s own sitemap rather than from a commit. This site recorded the change at 16 Nov 2026 22:07 UTC.

Upstream edited
Recorded here
Lines+274added
Lines−215removed
From line 1 where the diff opens
First seen 14 Aug 2026 this site's first read of the page
Recorded edits8to this page, all time

# Send messages to a running agent ## Choose single-shot or streaming input ## Send more than one message to a session ### Send a follow-up with an image ### Feed messages from a chat interface in TypeScript ## Read each response ## Interrupt Claude's response ## Next steps # Streaming Input ## Overview ## Streaming Input Mode (Recommended) ### Benefits ### Implementation Example ## Single Message Input ### When to Use Single Message Input ### Limitations ### Implementation Example

The whole hunk

from line 1, old and new numbered
/
lines
from line 1
1# Streaming Input
1# Send messages to a running agent
22 
3> Understanding the two input modes for Claude Agent SDK and when to use each
3> Send follow-up messages and images to one Agent SDK session with streaming input, read each response, and interrupt a response to redirect Claude.
44 
5## Overview
5Streaming 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.
66 
7The Claude Agent SDK supports two distinct input modes for interacting with agents:
7> [!NOTE]
8>
9> Streaming input covers the messages you send. To show Claude's response as it's generated, see [Stream responses in real-time](https://code.claude.com/docs/en/agent-sdk/streaming-output.md).
810 
9* **Streaming Input Mode**: a persistent, interactive session
10* **Single Message Input**: one-shot queries that use session state and resuming
11## Choose single-shot or streaming input
1112 
12## Streaming Input Mode (Recommended)
13Choose 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](https://code.claude.com/docs/en/agent-sdk/configuration.md#change-configuration-mid-session) while the session runs.
1314 
14Streaming 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.
15A 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](https://code.claude.com/docs/en/agent-sdk/sessions.md#continue-resume-and-fork).
1516 
16It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
17## Send more than one message to a session
1718 
18### Benefits
19* **TypeScript**: write an [async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function%2A) that yields [`SDKUserMessage`](https://code.claude.com/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.
20* **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.
1921 
20In streaming input mode, you work in a persistent session with these capabilities:
22To have Claude answer each message in its own response, wait for the previous response's [result message](#read-each-response) before you send the next one:
2123 
22* **Image uploads**: attach images directly to messages for visual analysis and understanding
23* **Queued messages**: send multiple messages that process sequentially, with ability to interrupt
24* **Tool integration**: full access to all tools and custom MCP servers during the session
25* **Real-time feedback**: see responses as they're generated, not just final results
26* **Context persistence**: maintain conversation context across multiple turns naturally
24* **TypeScript**: have your generator await a promise. Resolve it in your `for await` loop over `query()` when the result message arrives.
25* **Python**: call `client.query()` with the next message after your [`receive_response()`](https://code.claude.com/docs/en/agent-sdk/python#claudesdkclient) loop ends.
2726 
28### Implementation Example
27> [!NOTE]
28>
29> 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](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#turns-and-budget).
2930 
30These 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.
31### Send a follow-up with an image
3132 
33This 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:
34 
3235```typescript TypeScript theme={null}
36import { readFile } from "node:fs/promises";
3337import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
34import { readFile } from "fs/promises";
3538 
36async function* generateMessages(): AsyncGenerator<SDKUserMessage> {
37 // First message
39let firstResponseDone!: () => void;
40const firstResponseFinished = new Promise<void>((resolve) => {
41 firstResponseDone = resolve;
42});
43 
44async function* messages(): AsyncGenerator<SDKUserMessage> {
3845 yield {
3946 type: "user",
4047 message: {
4148 role: "user",
42 content: "Analyze this codebase for security issues"
49 content: "Explain in two sentences what a message queue does.",
4350 },
44 parent_tool_use_id: null
51 parent_tool_use_id: null,
4552 };
4653 
47 // Wait for conditions or user input
48 await new Promise((resolve) => setTimeout(resolve, 2000));
54 await firstResponseFinished;
4955 
50 // Follow-up with image
56 const image = await readFile("diagram.png");
5157 yield {
5258 type: "user",
5359 message: {
5460 role: "user",
5561 content: [
62 { type: "text", text: "Describe this image in one sentence." },
5663 {
57 type: "text",
58 text: "Review this architecture diagram"
59 },
60 {
6164 type: "image",
6265 source: {
6366 type: "base64",
6467 media_type: "image/png",
65 data: await readFile("diagram.png", "base64")
66 }
67 }
68 ]
68 data: image.toString("base64"),
69 },
70 },
71 ],
6972 },
70 parent_tool_use_id: null
73 parent_tool_use_id: null,
7174 };
7275}
7376 
74// Process streaming responses
75for await (const message of query({
76 prompt: generateMessages(),
77 options: {
78 maxTurns: 10,
79 allowedTools: ["Read", "Grep"]
77let responses = 0;
78for await (const message of query({ prompt: messages() })) {
79 if (message.type === "assistant") {
80 for (const block of message.message.content) {
81 if (block.type === "text") {
82 console.log(block.text);
83 }
84 }
85 } else if (message.type === "result") {
86 responses += 1;
87 console.log(`Response ${responses} finished: ${message.subtype}`);
88 if (responses === 1) {
89 firstResponseDone();
90 }
8091 }
81})) {
82 if (message.type === "result" && message.subtype === "success") {
83 console.log(message.result);
84 }
8592}
8693```
8794 
8895```python Python theme={null}
89from claude_agent_sdk import (
90 ClaudeSDKClient,
91 ClaudeAgentOptions,
92 AssistantMessage,
93 TextBlock,
94)
9596import asyncio
9697import base64
98from pathlib import Path
9799 
100from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
98101 
99async def streaming_analysis():
100 async def message_generator():
101 # First message
102 yield {
103 "type": "user",
104 "message": {
105 "role": "user",
106 "content": "Analyze this codebase for security issues",
107 },
108 }
109102 
110 # Wait for conditions
111 await asyncio.sleep(2)
112 
113 # Follow-up with image
114 with open("diagram.png", "rb") as f:
115 image_data = base64.b64encode(f.read()).decode()
116 
117 yield {
118 "type": "user",
119 "message": {
120 "role": "user",
121 "content": [
122 {"type": "text", "text": "Review this architecture diagram"},
123 {
124 "type": "image",
125 "source": {
126 "type": "base64",
127 "media_type": "image/png",
128 "data": image_data,
129 },
103async def image_message():
104 image_data = base64.b64encode(Path("diagram.png").read_bytes()).decode()
105 yield {
106 "type": "user",
107 "message": {
108 "role": "user",
109 "content": [
110 {"type": "text", "text": "Describe this image in one sentence."},
111 {
112 "type": "image",
113 "source": {
114 "type": "base64",
115 "media_type": "image/png",
116 "data": image_data,
130117 },
131 ],
132 },
133 }
118 },
119 ],
120 },
121 }
134122 
135 # Use ClaudeSDKClient for streaming input
136 options = ClaudeAgentOptions(max_turns=10, allowed_tools=["Read", "Grep"])
137123 
138 async with ClaudeSDKClient(options) as client:
139 # Send streaming input
140 await client.query(message_generator())
124async def main():
125 async with ClaudeSDKClient() as client:
126 await client.query("Explain in two sentences what a message queue does.")
127 async for message in client.receive_response():
128 if isinstance(message, AssistantMessage):
129 for block in message.content:
130 if isinstance(block, TextBlock):
131 print(block.text)
132 elif isinstance(message, ResultMessage):
133 print(f"Response 1 finished: {message.subtype}")
141134 
142 # Process responses
135 await client.query(image_message())
143136 async for message in client.receive_response():
144137 if isinstance(message, AssistantMessage):
145138 for block in message.content:
146139 if isinstance(block, TextBlock):
147140 print(block.text)
141 elif isinstance(message, ResultMessage):
142 print(f"Response 2 finished: {message.subtype}")
148143 
149144 
150asyncio.run(streaming_analysis())
145asyncio.run(main())
151146```
152147 
153When 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](https://code.claude.com/docs/en/agent-sdk/python.md#example-continuing-a-conversation).
148When you run either version, the example prints `Response 1 finished: success` and `Response 2 finished: success`.
154149 
155If 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.
150If Claude didn't see your image, see [Image could not be processed](https://code.claude.com/docs/en/agent-sdk/troubleshooting.md#image-could-not-be-processed).
156151 
157> [!NOTE]
158>
159> 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.
160>
161> 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.
152### Feed messages from a chat interface in TypeScript
162153 
163## Single Message Input
154Feed your user's messages to your prompt generator through a queue:
164155 
165Single message input is simpler but more limited.
156* **`pushMessage()`**: your interface's input handler calls this for each message the user sends.
157* **`closeInput()`**: the handler calls this when the user closes the chat.
158* **`userMessages()`**: the generator you pass as the `prompt` of `query()`.
166159 
167### When to Use Single Message Input
160`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:
168161 
169Use single message input when:
162```typescript theme={null}
163import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
170164 
171* You need a one-shot response
172* You do not need image attachments or mid-session control methods
173* You need to operate in a stateless environment, such as a lambda function
165const pending: string[] = [];
166let wake: (() => void) | null = null;
167let closed = false;
174168 
175### Limitations
169// The interface's input handler calls this with each message the user sends.
170function pushMessage(text: string): void {
171 pending.push(text);
172 wake?.();
173}
176174 
177> [!WARNING]
178>
179> Single message input mode does **not** support:
180>
181> * Direct image attachments in messages
182> * Dynamic message queueing
183> * Real-time interruption
184> * Natural multi-turn conversations
175// The interface calls this when the user closes the chat.
176function closeInput(): void {
177 closed = true;
178 wake?.();
179}
185180 
186If 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](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result) for the result subtypes.
181async function* userMessages(): AsyncGenerator<SDKUserMessage> {
182 while (true) {
183 const text = pending.shift();
184 if (text !== undefined) {
185 yield { type: "user", message: { role: "user", content: text }, parent_tool_use_id: null };
186 } else if (closed) {
187 return;
188 } else {
189 await new Promise<void>((resolve) => (wake = resolve));
190 wake = null;
191 }
192 }
193}
194```
187195 
188### Implementation Example
196Messages 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`](https://code.claude.com/docs/en/agent-sdk/typescript#sdkusermessage) field.
189197 
198## Read each response
199 
200Claude ends each response with a result message.
201 
202* **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`](https://code.claude.com/docs/en/agent-sdk/typescript#user_message_uuids).
203* **Python**: start a `receive_response()` loop for each response, because each loop stops after the next [`ResultMessage`](https://code.claude.com/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](https://code.claude.com/docs/en/agent-sdk/sessions.md#automatic-session-management).
204 
205The result message's `subtype` field reports how the response ended, such as `success` or `error_during_execution`.
206 
207If the last response ends in an error result:
208 
209* **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](https://code.claude.com/docs/en/agent-sdk/sessions.md#continue-resume-and-fork). While your generator still has messages to send, an error result for an earlier response doesn't throw.
210* **Python**: `receive_response()` on a `ClaudeSDKClient` yields the error result without raising.
211 
212For what each result subtype means, see [Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result).
213 
214## Interrupt Claude's response
215 
216To stop a response partway through and keep the session open, call `interrupt()` on the object that runs the session:
217 
218* **TypeScript**: pass an async generator as `prompt`, save the [`Query` object](https://code.claude.com/docs/en/agent-sdk/typescript#query-object) returned by `query()`, and call `interrupt()` on it.
219* **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.
220 
221When 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](#read-each-response).
222 
223This 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:
224 
190225```typescript TypeScript theme={null}
191import { query } from "@anthropic-ai/claude-agent-sdk";
226import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
192227 
193// Simple one-shot query
194// query() throws after an error result, such as error_max_turns
195try {
196 for await (const message of query({
197 prompt: "Explain the authentication flow",
198 options: {
199 maxTurns: 5,
200 allowedTools: ["Read", "Grep"]
201 }
202 })) {
203 if (message.type === "result" && message.subtype === "success") {
204 console.log(message.result);
205 }
206 }
207} catch (error) {
208 console.error(`Query failed: ${error}`);
228let firstResponseDone!: () => void;
229const firstResponseFinished = new Promise<void>((resolve) => {
230 firstResponseDone = resolve;
231});
232 
233async function* messages(): AsyncGenerator<SDKUserMessage> {
234 yield {
235 type: "user",
236 message: {
237 role: "user",
238 content: "Write a 2,000-word essay on the history of the printing press.",
239 },
240 parent_tool_use_id: null,
241 };
242 
243 await firstResponseFinished;
244 
245 yield {
246 type: "user",
247 message: {
248 role: "user",
249 content: "In one sentence, what is a prime number?",
250 },
251 parent_tool_use_id: null,
252 };
209253}
210254 
211// Continue conversation with session management
212try {
213 for await (const message of query({
214 prompt: "Now explain the authorization process",
215 options: {
216 continue: true,
217 maxTurns: 5
255const conversation = query({ prompt: messages() });
256 
257let responses = 0;
258for await (const message of conversation) {
259 if (message.type === "system" && message.subtype === "init" && responses === 0) {
260 setTimeout(async () => {
261 await conversation.interrupt();
262 console.log("Interrupt sent");
263 }, 3000);
264 } else if (message.type === "assistant") {
265 for (const block of message.message.content) {
266 if (block.type === "text") {
267 console.log(block.text);
268 }
218269 }
219 })) {
220 if (message.type === "result" && message.subtype === "success") {
221 console.log(message.result);
270 } else if (message.type === "result") {
271 responses += 1;
272 console.log(`Response ${responses} finished: ${message.subtype}`);
273 if (responses === 1) {
274 firstResponseDone();
222275 }
223276 }
224} catch (error) {
225 console.error(`Query failed: ${error}`);
226277}
227278```
228279 
229280```python Python theme={null}
230from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
231281import asyncio
232282 
283from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
233284 
234async def single_message_example():
235 # Simple one-shot query using query() function
236 # query() raises ResultError after an error result, such as error_max_turns
237 try:
238 async for message in query(
239 prompt="Explain the authentication flow",
240 options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),
241 ):
242 if isinstance(message, ResultMessage) and message.subtype == "success":
243 print(message.result)
244 except Exception as e:
245 print(f"Query failed: {e}")
246285 
247 # Continue conversation with session management
248 try:
249 async for message in query(
250 prompt="Now explain the authorization process",
251 options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),
252 ):
253 if isinstance(message, ResultMessage) and message.subtype == "success":
254 print(message.result)
255 except Exception as e:
256 print(f"Query failed: {e}")
286async def main():
287 async with ClaudeSDKClient() as client:
288 await client.query("Write a 2,000-word essay on the history of the printing press.")
289 await asyncio.sleep(3)
290 await client.interrupt()
291 print("Interrupt sent")
292 async for message in client.receive_response():
293 if isinstance(message, AssistantMessage):
294 for block in message.content:
295 if isinstance(block, TextBlock):
296 print(block.text)
297 elif isinstance(message, ResultMessage):
298 print(f"Response 1 finished: {message.subtype}")
257299 
300 await client.query("In one sentence, what is a prime number?")
301 async for message in client.receive_response():
302 if isinstance(message, AssistantMessage):
303 for block in message.content:
304 if isinstance(block, TextBlock):
305 print(block.text)
306 elif isinstance(message, ResultMessage):
307 print(f"Response 2 finished: {message.subtype}")
258308 
259asyncio.run(single_message_example())
309 
310asyncio.run(main())
260311```
261312 
262When you run the example, each query prints its final result text: first the authentication explanation, then the authorization explanation.
313When 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`.
314 
315## Next steps
316 
317* [Stream responses in real-time](https://code.claude.com/docs/en/agent-sdk/streaming-output.md): show text and tool calls as Claude generates them
318* [Handle approvals and user input](https://code.claude.com/docs/en/agent-sdk/user-input.md): answer Claude's permission requests and clarifying questions
319* [Change configuration mid-session](https://code.claude.com/docs/en/agent-sdk/configuration.md#change-configuration-mid-session): switch the model or permission mode while the session runs
320* [`Query` object](https://code.claude.com/docs/en/agent-sdk/typescript#query-object) in TypeScript and [`ClaudeSDKClient`](https://code.claude.com/docs/en/agent-sdk/python#claudesdkclient) in Python: the methods that send messages to a running session or control it
321* [Work with sessions](https://code.claude.com/docs/en/agent-sdk/sessions.md): resume, continue, or fork a conversation
263322 
Feedback