Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Agent SDK 支持两种不同的输入模式来与代理交互:
本指南解释了每种模式的差异、优势和用例,以帮助您为应用程序选择正确的方法。
流式输入模式是使用 Claude Agent SDK 的首选方式。它提供对代理功能的完全访问,并支持丰富的交互式体验。
它允许代理作为一个长期运行的进程运行,接收用户输入、处理中断、显示权限请求并处理会话管理。
直接将图像附加到消息中以进行视觉分析和理解
发送多条按顺序处理的消息,具有中断能力
在会话期间完全访问所有工具和自定义 MCP 服务器
使用生命周期钩子在各个点自定义行为
查看生成的响应,而不仅仅是最终结果
自然地在多个回合中保持对话上下文
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);
}
}