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# 串流輸入5# 傳送訊息給執行中的 agent
6 6
7> 了解 Claude Agent SDK 的兩種輸入模式及何時使用各種模式7> 使用串流輸入向單一 Agent SDK 工作階段傳送後續訊息和影像、讀取每個回應,並中斷回應以重新引導 Claude。
8 8
9## 概述9串流輸入會讓 Agent SDK 工作階段保持開啟,讓您的應用程式可以在工作階段執行期間傳送多則訊息給它。您也可以將影像附加到訊息中,並在回應進行到一半時停止它,以重新引導 Claude。
10 10
11Claude Agent SDK 支援兩種不同的輸入模式來與代理互動:11> [!NOTE]
12>
13> 串流輸入涵蓋的是您傳送的訊息。若要在 Claude 產生回應時即時顯示回應,請參閱[即時串流回應](https://code.claude.com/docs/zh-TW/agent-sdk/streaming-output.md)。
14
15## 選擇單次或串流輸入
12 16
13* **串流輸入模式**:持久的互動式工作階段17對於與 Claude 進行對話的應用程式(例如聊天介面),請選擇串流輸入。使用串流輸入可以將影像附加到訊息、中斷回應,或在工作階段執行期間[切換模型或權限模式](https://code.claude.com/docs/zh-TW/agent-sdk/configuration.md#change-configuration-mid-session)。
14* **單一訊息輸入**:使用工作階段狀態和恢復的一次性查詢
15 18
16## 串流輸入模式(推薦)19單次呼叫會將一個提示詞字串傳遞給 `query()`。該呼叫會在 Claude 回答後結束。單次呼叫適合單一任務,例如 serverless 函式。若要在該呼叫結束後繼續追問,請啟動一個恢復該工作階段的新呼叫。如需詳細資訊,請參閱[繼續、恢復與分叉](https://code.claude.com/docs/zh-TW/agent-sdk/sessions.md#continue-resume-and-fork)。
17 20
18串流輸入模式是使用 Claude Agent SDK 的**首選**方式。它提供對代理功能的完整存取,並啟用豐富的互動式體驗。21## 向工作階段傳送多則訊息
19 22
20它允許代理作為長期執行的程序運作,接收使用者輸入、處理中斷、顯示權限請求,以及處理工作階段管理。23* **TypeScript**:撰寫一個會 yield [`SDKUserMessage`](https://code.claude.com/docs/zh-TW/agent-sdk/typescript#sdkusermessage) 物件的 [async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function%2A),並將其作為 `query()` 的 `prompt` 傳入。讓產生器在每次 yield 之間等待來自使用者的下一則訊息。
24* **Python**:開啟一個 `ClaudeSDKClient`,並將每則訊息傳遞給 `client.query()`。對於文字訊息,請傳入字串。若要附加影像,請傳入一個會 yield 使用者訊息 dict 的 [async generator](https://docs.python.org/3/glossary.html#term-asynchronous-generator)。
21 25
22### 優點26若要讓 Claude 以各自獨立的回應回答每則訊息,請在傳送下一則訊息之前,等待前一個回應的[結果訊息](#read-each-response):
23 27
24在串流輸入模式中,您在具有這些功能的持久工作階段中工作:28* **TypeScript**:讓您的產生器 await 一個 promise。在您對 `query()` 執行的 `for await` 迴圈中,於結果訊息到達時 resolve 該 promise。
29* **Python**:在您的 [`receive_response()`](https://code.claude.com/docs/zh-TW/agent-sdk/python#claudesdkclient) 迴圈結束後,使用下一則訊息呼叫 `client.query()`。
25 30
26* **影像上傳**:直接將影像附加到訊息中以進行視覺分析和理解31> [!NOTE]
27* **佇列訊息**:傳送多個訊息以順序處理,並能夠中斷32>
28* **工具整合**:在工作階段期間完整存取所有工具和自訂 MCP 伺服器33> 您在工具呼叫期間傳送的訊息,會在那些工具呼叫完成後才送達 Claude。接著 Claude 會在一個回應中同時回答該訊息和您先前的訊息。如果回合先結束,Claude 會為該訊息開始一個新的回合。如需詳細資訊,請參閱[回合與預算](https://code.claude.com/docs/zh-TW/agent-sdk/agent-loop.md#turns-and-budget)。
29* **即時回饋**:查看產生的回應,而不僅僅是最終結果
30* **內容持久性**:自然地在多個回合中維持對話內容
31 34
32### 實作範例35### 傳送附帶影像的後續訊息
33 36
34這些範例從工作目錄讀取名為 `diagram.png` 的影像。請先在該處建立一個,或變更檔案名稱以指向您自己的影像。37此範例會先傳送一個文字問題,接著傳送一則附帶影像的後續訊息,並列印 Claude 對每則訊息的回應。執行之前,請在您的工作目錄中將一張 PNG 影像儲存為 `diagram.png`:
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
157當您執行範例時,TypeScript 版本會在每個回應完成時列印它。Python 版本的 `receive_response()` 迴圈在第一個結果訊息處結束,因此它會列印安全性分析;若要讀取兩個回應,請使用一個 `query()` 和 `receive_response()` 配對,如 [Python 參考的繼續對話範例](https://code.claude.com/docs/zh-TW/agent-sdk/python.md#example-continuing-a-conversation) 所示。152無論執行哪個版本,範例都會列印 `Response 1 finished: success` 和 `Response 2 finished: success`。
158 153
159如果影像區塊的 `source` 遺失或不是物件,SDK 不會回報錯誤。Claude Code 會以一則文字說明取代該影像傳送給 Claude,例如 `[Image could not be processed: image block has no source object]`,而工作階段會繼續進行。154如果 Claude 沒有看到您的影像,請參閱[影像無法處理](https://code.claude.com/docs/zh-TW/agent-sdk/troubleshooting.md#image-could-not-be-processed)。
160 155
161> [!NOTE]156### 在 TypeScript 中從聊天介面提供訊息
162>
163> 在 TypeScript SDK 中,如果您的訊息產生器拋出例外,例如當它讀取的檔案遺失時,串流會以錯誤結束,該錯誤顯示為 `Claude Code process aborted by user`,而不是原始錯誤,因此當您看到該訊息時,請先檢查產生器內的程式碼。該錯誤前面也可能會有一長行的最小化捆綁 SDK 原始碼,因此請閱讀輸出末尾以取得錯誤文字。
164>
165> 在 Python SDK 中,產生器例外會在偵錯層級記錄,工作階段會停滯而不會引發,因此如果串流工作階段掛起且沒有輸出,請啟用偵錯記錄並檢查您的產生器。
166 157
167## 單一訊息輸入158透過佇列將使用者的訊息提供給您的提示詞產生器:
168 159
169單一訊息輸入更簡單但功能更受限。160* **`pushMessage()`**:您介面的輸入處理常式會針對使用者傳送的每則訊息呼叫此函式。
161* **`closeInput()`**:處理常式會在使用者關閉聊天時呼叫此函式。
162* **`userMessages()`**:您作為 `query()` 的 `prompt` 傳入的產生器。
170 163
171### 何時使用單一訊息輸入164`pushMessage()` 會將每則訊息加入陣列,而產生器會從該陣列讀取。當陣列為空時,產生器會等待,直到有訊息到達或聊天關閉:
172 165
173在以下情況下使用單一訊息輸入:166```typescript theme={null}
167import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
174 168
175* 您需要一次性回應169const pending: string[] = [];
176* 您不需要影像附件或中途工作階段控制方法170let wake: (() => void) | null = null;
177* 您需要在無狀態環境中運作,例如 lambda 函式171let closed = false;
178 172
179### 限制173// 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> 單一訊息輸入模式**不**支援:181 closed = true;
184>182 wake?.();
185> * 訊息中的直接影像附件183}
186> * 動態訊息佇列184
187> * 即時中斷185async function* userMessages(): AsyncGenerator<SDKUserMessage> {
188> * 自然的多回合對話186 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
200您在回應期間推入的訊息可能會共用同一個回應。若要選擇 Claude 何時讀取您在回應期間推入的訊息,請設定該訊息的 [`priority`](https://code.claude.com/docs/zh-TW/agent-sdk/typescript#sdkusermessage) 欄位。
201
202## 讀取每個回應
203
204Claude 會以一則結果訊息結束每個回應。
205
206* **TypeScript**:對 `query()` 執行的 `for await` 迴圈會依序 yield 每個回應的訊息。在您的產生器 return 之後,迴圈會在最後一個回應的結果訊息之後結束。若要將結果與其所回答的訊息配對,請在您傳送的每則訊息上設定 `uuid`,並讀取結果的 [`user_message_uuids`](https://code.claude.com/docs/zh-TW/agent-sdk/typescript#user_message_uuids)。
207* **Python**:為每個回應啟動一個 `receive_response()` 迴圈,因為每個迴圈都會在下一個 [`ResultMessage`](https://code.claude.com/docs/zh-TW/agent-sdk/python#resultmessage) 之後停止。用戶端會在訊息之間保留對話的上下文。如需詳細資訊,請參閱[自動工作階段管理](https://code.claude.com/docs/zh-TW/agent-sdk/sessions.md#automatic-session-management)。
189 208
190如果查詢以錯誤結果結束,例如 `error_max_turns`,單一訊息 `query()` 呼叫會引發一個錯誤,該錯誤在產生最終結果訊息後包含失敗文字,因此如果您的程式碼需要繼續執行,請將迴圈包裝在 try 區塊中。請參閱 [處理結果](https://code.claude.com/docs/zh-TW/agent-sdk/agent-loop.md#handle-the-result) 以了解結果子類型。209結果訊息的 `subtype` 欄位會回報回應的結束方式,例如 `success` 或 `error_during_execution`。
191 210
192### 實作範例211如果最後一個回應以錯誤結果結束:
212
213* **TypeScript**:對 `query()` 執行的迴圈會 yield 該結果,然後拋出例外。請將迴圈包裝在 `try`/`catch` 中以處理該例外。若要在拋出例外後繼續對話,請啟動一個[恢復該工作階段](https://code.claude.com/docs/zh-TW/agent-sdk/sessions.md#continue-resume-and-fork)的新 `query()` 呼叫。當您的產生器仍有訊息要傳送時,較早回應的錯誤結果不會拋出例外。
214* **Python**:`ClaudeSDKClient` 上的 `receive_response()` 會 yield 錯誤結果,而不會引發例外。
215
216如需了解每個結果子類型的意義,請參閱[處理結果](https://code.claude.com/docs/zh-TW/agent-sdk/agent-loop.md#handle-the-result)。
217
218## 中斷 Claude 的回應
219
220若要在回應進行到一半時停止它並保持工作階段開啟,請在執行該工作階段的物件上呼叫 `interrupt()`:
221
222* **TypeScript**:將 async generator 作為 `prompt` 傳入,儲存 `query()` 傳回的 [`Query` 物件](https://code.claude.com/docs/zh-TW/agent-sdk/typescript#query-object),並在其上呼叫 `interrupt()`。
223* **Python**:在 `ClaudeSDKClient` 上呼叫 `interrupt()`。如果有 `receive_response()` 迴圈正在讀取該回應,該迴圈會在被中斷回應的 `ResultMessage` 處結束。請在該結果到達後再傳送下一則訊息。
224
225當您在回應期間呼叫 `interrupt()` 時,該回應會以 `error_during_execution` 結果結束。您在中斷前傳送、但 Claude 尚未讀取的訊息,仍會在被中斷的回應結束後送達 Claude。如需了解當最後一個回應為錯誤結果時 TypeScript 迴圈的行為,請參閱[讀取每個回應](#read-each-response)。
226
227此範例要求 Claude 撰寫一篇長文。範例會在工作階段開始三秒後呼叫 `interrupt()`,然後在被中斷的回應結束後,向同一個工作階段傳送第二則訊息:
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
266當您執行此範例時,每個查詢都會列印其最終結果文字:首先是驗證說明,然後是授權說明。317無論執行哪個版本,第一個回應都會在文章寫到一半時停止,範例會列印 `Response 1 finished: error_during_execution`。接著 Claude 會回答第二則訊息。輸出最後會是 `Response 2 finished: success`。
318
319## 後續步驟
320
321* [即時串流回應](https://code.claude.com/docs/zh-TW/agent-sdk/streaming-output.md):在 Claude 產生文字和工具呼叫時即時顯示
322* [處理核准與使用者輸入](https://code.claude.com/docs/zh-TW/agent-sdk/user-input.md):回答 Claude 的權限請求和釐清問題
323* [在工作階段中途變更設定](https://code.claude.com/docs/zh-TW/agent-sdk/configuration.md#change-configuration-mid-session):在工作階段執行期間切換模型或權限模式
324* TypeScript 中的 [`Query` 物件](https://code.claude.com/docs/zh-TW/agent-sdk/typescript#query-object)和 Python 中的 [`ClaudeSDKClient`](https://code.claude.com/docs/zh-TW/agent-sdk/python#claudesdkclient):向執行中的工作階段傳送訊息或控制它的方法
325* [使用工作階段](https://code.claude.com/docs/zh-TW/agent-sdk/sessions.md):恢復、繼續或分叉對話