Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Agent SDK 支援兩種不同的輸入模式來與代理互動:
本指南說明每種模式的差異、優點和使用案例,幫助您為應用程式選擇正確的方法。
串流輸入模式是使用 Claude Agent SDK 的首選方式。它提供對代理功能的完整存取,並支援豐富的互動式體驗。
它允許代理作為長期執行的程序運作,接收使用者輸入、處理中斷、顯示權限請求,以及處理工作階段管理。
直接將影像附加到訊息中以進行視覺分析和理解
傳送多個訊息以順序處理,並能夠中斷
在工作階段期間完整存取所有工具和自訂 MCP 伺服器
使用生命週期 hooks 在各個點自訂行為
查看產生的回應,而不僅僅是最終結果
自然地在多個回合中維持對話內容
單一訊息輸入更簡單但功能更受限。
在以下情況下使用單一訊息輸入:
單一訊息輸入模式不支援:
import { query } from "@anthropic-ai/claude-agent-sdk";
import { readFileSync } from "fs";
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: readFileSync("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);
}
}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);
}
}