Documentation Index
Fetch the complete documentation index at: https://docs.claude.com/llms.txt
Use this file to discover all available pages before exploring further.
Claude Agent SDK 支援兩種不同的輸入模式來與代理程式互動:
- 串流輸入模式(預設且推薦)- 持續的互動式會話
- 單一訊息輸入 - 使用會話狀態和恢復的一次性查詢
本指南說明每種模式的差異、優點和使用案例,幫助您為應用程式選擇正確的方法。
串流輸入模式(推薦)
串流輸入模式是使用 Claude Agent SDK 的首選方式。它提供對代理程式功能的完整存取,並實現豐富的互動體驗。
它允許代理程式作為長期運行的程序運作,接收使用者輸入、處理中斷、顯示權限請求,並處理會話管理。
運作方式
工具整合
在會話期間完整存取所有工具和自訂 MCP 伺服器
實作範例
import { query } from "@anthropic-ai/claude-agent-sdk";
import { readFileSync } from "fs";
async function* generateMessages() {
// 第一個訊息
yield {
type: "user" as const,
message: {
role: "user" as const,
content: "分析此程式碼庫的安全問題"
}
};
// 等待條件或使用者輸入
await new Promise(resolve => setTimeout(resolve, 2000));
// 後續附加圖片
yield {
type: "user" as const,
message: {
role: "user" as const,
content: [
{
type: "text",
text: "檢視此架構圖"
},
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: readFileSync("diagram.png", "base64")
}
}
]
}
};
}
// 處理串流回應
for await (const message of query({
prompt: generateMessages(),
options: {
maxTurns: 10,
allowedTools: ["Read", "Grep"]
}
})) {
if (message.type === "result") {
console.log(message.result);
}
}
單一訊息輸入
單一訊息輸入較為簡單但功能有限。
何時使用單一訊息輸入
在以下情況下使用單一訊息輸入:
- 您需要一次性回應
- 您不需要圖片附件、鉤子等功能
- 您需要在無狀態環境中運作,例如 lambda 函數
單一訊息輸入模式不支援:
- 訊息中的直接圖片附件
- 動態訊息排隊
- 即時中斷
- 鉤子整合
- 自然的多輪對話
實作範例
import { query } from "@anthropic-ai/claude-agent-sdk";
// 簡單的一次性查詢
for await (const message of query({
prompt: "解釋身份驗證流程",
options: {
maxTurns: 1,
allowedTools: ["Read", "Grep"]
}
})) {
if (message.type === "result") {
console.log(message.result);
}
}
// 透過會話管理繼續對話
for await (const message of query({
prompt: "現在解釋授權程序",
options: {
continue: true,
maxTurns: 1
}
})) {
if (message.type === "result") {
console.log(message.result);
}
}