2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3> Use this file to discover all available pages before exploring further.3> Use this file to discover all available pages before exploring further.
4 4
5# Streaming Input5# Send messages to a running agent
6 6
7> Understanding the two input modes for Claude Agent SDK and when to use each7> Send follow-up messages and images to one Agent SDK session with streaming input, read each response, and interrupt a response to redirect Claude.
8 8
9## Overview9Streaming 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.
10 10
11The Claude Agent SDK supports two distinct input modes for interacting with agents:11> [!NOTE]
12>
13> 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).
14
15## Choose single-shot or streaming input
12 16
13* **Streaming Input Mode**: a persistent, interactive session17Choose 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.
14* **Single Message Input**: one-shot queries that use session state and resuming
15 18
16## Streaming Input Mode (Recommended)19A 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).
17 20
18Streaming 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.21## Send more than one message to a session
19 22
20It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.23* **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.
24* **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.
21 25
22### Benefits26To 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:
23 27
24In streaming input mode, you work in a persistent session with these capabilities:28* **TypeScript**: have your generator await a promise. Resolve it in your `for await` loop over `query()` when the result message arrives.
29* **Python**: call `client.query()` with the next message after your [`receive_response()`](https://code.claude.com/docs/en/agent-sdk/python#claudesdkclient) loop ends.
25 30
26* **Image uploads**: attach images directly to messages for visual analysis and understanding31> [!NOTE]
27* **Queued messages**: send multiple messages that process sequentially, with ability to interrupt32>
28* **Tool integration**: full access to all tools and custom MCP servers during the session33> 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).
29* **Real-time feedback**: see responses as they're generated, not just final results
30* **Context persistence**: maintain conversation context across multiple turns naturally
31 34
32### Implementation Example35### Send a follow-up with an image
33 36
34These 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.37This 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:
35 38
36```typescript TypeScript theme={null}39```typescript TypeScript theme={null}
40import { readFile } from "node:fs/promises";
37import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";41import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
38import { readFile } from "fs/promises";
39 42
40async function* generateMessages(): AsyncGenerator<SDKUserMessage> {43let firstResponseDone!: () => void;
41 // First message44const firstResponseFinished = new Promise<void>((resolve) => {
45 firstResponseDone = resolve;
46});
47
48async function* messages(): AsyncGenerator<SDKUserMessage> {
42 yield {49 yield {
43 type: "user",50 type: "user",
44 message: {51 message: {
45 role: "user",52 role: "user",
46 content: "Analyze this codebase for security issues"53 content: "Explain in two sentences what a message queue does.",
47 },54 },
48 parent_tool_use_id: null55 parent_tool_use_id: null,
49 };56 };
50 57
51 // Wait for conditions or user input58 await firstResponseFinished;
52 await new Promise((resolve) => setTimeout(resolve, 2000));
53 59
54 // Follow-up with image60 const image = await readFile("diagram.png");
55 yield {61 yield {
56 type: "user",62 type: "user",
57 message: {63 message: {
58 role: "user",64 role: "user",
59 content: [65 content: [
60 {66 { type: "text", text: "Describe this image in one sentence." },
61 type: "text",
62 text: "Review this architecture diagram"
63 },
64 {67 {
65 type: "image",68 type: "image",
66 source: {69 source: {
67 type: "base64",70 type: "base64",
68 media_type: "image/png",71 media_type: "image/png",
69 data: await readFile("diagram.png", "base64")72 data: image.toString("base64"),
70 }73 },
71 }
72 ]
73 },74 },
74 parent_tool_use_id: null75 ],
76 },
77 parent_tool_use_id: null,
75 };78 };
76}79}
77 80
78// Process streaming responses81let responses = 0;
79for await (const message of query({82for await (const message of query({ prompt: messages() })) {
80 prompt: generateMessages(),83 if (message.type === "assistant") {
81 options: {84 for (const block of message.message.content) {
82 maxTurns: 10,85 if (block.type === "text") {
83 allowedTools: ["Read", "Grep"]86 console.log(block.text);
87 }
88 }
89 } else if (message.type === "result") {
90 responses += 1;
91 console.log(`Response ${responses} finished: ${message.subtype}`);
92 if (responses === 1) {
93 firstResponseDone();
84 }94 }
85})) {
86 if (message.type === "result" && message.subtype === "success") {
87 console.log(message.result);
88 }95 }
89}96}
90```97```
91 98
92```python Python theme={null}99```python Python theme={null}
93from claude_agent_sdk import (
94 ClaudeSDKClient,
95 ClaudeAgentOptions,
96 AssistantMessage,
97 TextBlock,
98)
99import asyncio100import asyncio
100import base64101import base64
102from pathlib import Path
101 103
104from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
102 105
103async def streaming_analysis():
104 async def message_generator():
105 # First message
106 yield {
107 "type": "user",
108 "message": {
109 "role": "user",
110 "content": "Analyze this codebase for security issues",
111 },
112 }
113
114 # Wait for conditions
115 await asyncio.sleep(2)
116
117 # Follow-up with image
118 with open("diagram.png", "rb") as f:
119 image_data = base64.b64encode(f.read()).decode()
120 106
107async def image_message():
108 image_data = base64.b64encode(Path("diagram.png").read_bytes()).decode()
121 yield {109 yield {
122 "type": "user",110 "type": "user",
123 "message": {111 "message": {
124 "role": "user",112 "role": "user",
125 "content": [113 "content": [
126 {"type": "text", "text": "Review this architecture diagram"},114 {"type": "text", "text": "Describe this image in one sentence."},
127 {115 {
128 "type": "image",116 "type": "image",
129 "source": {117 "source": {
136 },124 },
137 }125 }
138 126
139 # Use ClaudeSDKClient for streaming input
140 options = ClaudeAgentOptions(max_turns=10, allowed_tools=["Read", "Grep"])
141 127
142 async with ClaudeSDKClient(options) as client:128async def main():
143 # Send streaming input129 async with ClaudeSDKClient() as client:
144 await client.query(message_generator())130 await client.query("Explain in two sentences what a message queue does.")
131 async for message in client.receive_response():
132 if isinstance(message, AssistantMessage):
133 for block in message.content:
134 if isinstance(block, TextBlock):
135 print(block.text)
136 elif isinstance(message, ResultMessage):
137 print(f"Response 1 finished: {message.subtype}")
145 138
146 # Process responses139 await client.query(image_message())
147 async for message in client.receive_response():140 async for message in client.receive_response():
148 if isinstance(message, AssistantMessage):141 if isinstance(message, AssistantMessage):
149 for block in message.content:142 for block in message.content:
150 if isinstance(block, TextBlock):143 if isinstance(block, TextBlock):
151 print(block.text)144 print(block.text)
145 elif isinstance(message, ResultMessage):
146 print(f"Response 2 finished: {message.subtype}")
152 147
153 148
154asyncio.run(streaming_analysis())149asyncio.run(main())
155```150```
156 151
157When 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).152When you run either version, the example prints `Response 1 finished: success` and `Response 2 finished: success`.
158 153
159If 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.154If 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).
160 155
161> [!NOTE]156### Feed messages from a chat interface in TypeScript
162>
163> 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.
164>
165> 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.
166 157
167## Single Message Input158Feed your user's messages to your prompt generator through a queue:
168 159
169Single message input is simpler but more limited.160* **`pushMessage()`**: your interface's input handler calls this for each message the user sends.
161* **`closeInput()`**: the handler calls this when the user closes the chat.
162* **`userMessages()`**: the generator you pass as the `prompt` of `query()`.
170 163
171### When to Use Single Message Input164`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:
172 165
173Use single message input when:166```typescript theme={null}
167import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
174 168
175* You need a one-shot response169const pending: string[] = [];
176* You do not need image attachments or mid-session control methods170let wake: (() => void) | null = null;
177* You need to operate in a stateless environment, such as a lambda function171let closed = false;
178 172
179### Limitations173// The interface's input handler calls this with each message the user sends.
174function pushMessage(text: string): void {
175 pending.push(text);
176 wake?.();
177}
180 178
181> [!WARNING]179// The interface calls this when the user closes the chat.
182>180function closeInput(): void {
183> Single message input mode does **not** support:181 closed = true;
184>182 wake?.();
185> * Direct image attachments in messages183}
186> * Dynamic message queueing184
187> * Real-time interruption185async function* userMessages(): AsyncGenerator<SDKUserMessage> {
188> * Natural multi-turn conversations186 while (true) {
187 const text = pending.shift();
188 if (text !== undefined) {
189 yield { type: "user", message: { role: "user", content: text }, parent_tool_use_id: null };
190 } else if (closed) {
191 return;
192 } else {
193 await new Promise<void>((resolve) => (wake = resolve));
194 wake = null;
195 }
196 }
197}
198```
199
200Messages 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.
201
202## Read each response
203
204Claude ends each response with a result message.
205
206* **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).
207* **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).
189 208
190If 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.209The result message's `subtype` field reports how the response ended, such as `success` or `error_during_execution`.
191 210
192### Implementation Example211If the last response ends in an error result:
212
213* **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.
214* **Python**: `receive_response()` on a `ClaudeSDKClient` yields the error result without raising.
215
216For what each result subtype means, see [Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result).
217
218## Interrupt Claude's response
219
220To stop a response partway through and keep the session open, call `interrupt()` on the object that runs the session:
221
222* **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.
223* **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.
224
225When 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).
226
227This 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:
193 228
194```typescript TypeScript theme={null}229```typescript TypeScript theme={null}
195import { query } from "@anthropic-ai/claude-agent-sdk";230import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
196 231
197// Simple one-shot query232let firstResponseDone!: () => void;
198// query() throws after an error result, such as error_max_turns233const firstResponseFinished = new Promise<void>((resolve) => {
199try {234 firstResponseDone = resolve;
200 for await (const message of query({235});
201 prompt: "Explain the authentication flow",236
202 options: {237async function* messages(): AsyncGenerator<SDKUserMessage> {
203 maxTurns: 5,238 yield {
204 allowedTools: ["Read", "Grep"]239 type: "user",
205 }240 message: {
206 })) {241 role: "user",
207 if (message.type === "result" && message.subtype === "success") {242 content: "Write a 2,000-word essay on the history of the printing press.",
208 console.log(message.result);243 },
209 }244 parent_tool_use_id: null,
210 }245 };
211} catch (error) {246
212 console.error(`Query failed: ${error}`);247 await firstResponseFinished;
248
249 yield {
250 type: "user",
251 message: {
252 role: "user",
253 content: "In one sentence, what is a prime number?",
254 },
255 parent_tool_use_id: null,
256 };
213}257}
214 258
215// Continue conversation with session management259const conversation = query({ prompt: messages() });
216try {260
217 for await (const message of query({261let responses = 0;
218 prompt: "Now explain the authorization process",262for await (const message of conversation) {
219 options: {263 if (message.type === "system" && message.subtype === "init" && responses === 0) {
220 continue: true,264 setTimeout(async () => {
221 maxTurns: 5265 await conversation.interrupt();
266 console.log("Interrupt sent");
267 }, 3000);
268 } else if (message.type === "assistant") {
269 for (const block of message.message.content) {
270 if (block.type === "text") {
271 console.log(block.text);
272 }
222 }273 }
223 })) {274 } else if (message.type === "result") {
224 if (message.type === "result" && message.subtype === "success") {275 responses += 1;
225 console.log(message.result);276 console.log(`Response ${responses} finished: ${message.subtype}`);
277 if (responses === 1) {
278 firstResponseDone();
226 }279 }
227 }280 }
228} catch (error) {
229 console.error(`Query failed: ${error}`);
230}281}
231```282```
232 283
233```python Python theme={null}284```python Python theme={null}
234from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
235import asyncio285import asyncio
236 286
287from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
288
289
290async def main():
291 async with ClaudeSDKClient() as client:
292 await client.query("Write a 2,000-word essay on the history of the printing press.")
293 await asyncio.sleep(3)
294 await client.interrupt()
295 print("Interrupt sent")
296 async for message in client.receive_response():
297 if isinstance(message, AssistantMessage):
298 for block in message.content:
299 if isinstance(block, TextBlock):
300 print(block.text)
301 elif isinstance(message, ResultMessage):
302 print(f"Response 1 finished: {message.subtype}")
303
304 await client.query("In one sentence, what is a prime number?")
305 async for message in client.receive_response():
306 if isinstance(message, AssistantMessage):
307 for block in message.content:
308 if isinstance(block, TextBlock):
309 print(block.text)
310 elif isinstance(message, ResultMessage):
311 print(f"Response 2 finished: {message.subtype}")
312
237 313
238async def single_message_example():314asyncio.run(main())
239 # Simple one-shot query using query() function
240 # query() raises ResultError after an error result, such as error_max_turns
241 try:
242 async for message in query(
243 prompt="Explain the authentication flow",
244 options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),
245 ):
246 if isinstance(message, ResultMessage) and message.subtype == "success":
247 print(message.result)
248 except Exception as e:
249 print(f"Query failed: {e}")
250
251 # Continue conversation with session management
252 try:
253 async for message in query(
254 prompt="Now explain the authorization process",
255 options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),
256 ):
257 if isinstance(message, ResultMessage) and message.subtype == "success":
258 print(message.result)
259 except Exception as e:
260 print(f"Query failed: {e}")
261
262
263asyncio.run(single_message_example())
264```315```
265 316
266When you run the example, each query prints its final result text: first the authentication explanation, then the authorization explanation.317When 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`.
318
319## Next steps
320
321* [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
322* [Handle approvals and user input](https://code.claude.com/docs/en/agent-sdk/user-input.md): answer Claude's permission requests and clarifying questions
323* [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
324* [`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
325* [Work with sessions](https://code.claude.com/docs/en/agent-sdk/sessions.md): resume, continue, or fork a conversation