指南
流式输入
了解 Claude Agent SDK 的两种输入模式以及何时使用每种模式
概述
概述
Claude Agent SDK 支持两种不同的输入模式来与代理交互:
- 流式输入模式(默认和推荐)- 持久的交互式会话
- 单消息输入 - 使用会话状态和恢复的一次性查询
本指南解释了每种模式的差异、优势和使用场景,帮助您为应用程序选择正确的方法。
流式输入模式(推荐)
流式输入模式(推荐)
流式输入模式是使用 Claude Agent SDK 的首选方式。它提供对代理功能的完全访问,并支持丰富的交互式体验。
它允许代理作为长期运行的进程运行,接收用户输入、处理中断、显示权限请求并处理会话管理。
工作原理
工作原理
%%{init: {"theme": "base", "themeVariables": {"edgeLabelBackground": "#F0F0EB", "lineColor": "#91918D", "primaryColor": "#F0F0EB", "primaryTextColor": "#191919", "primaryBorderColor": "#D9D8D5", "secondaryColor": "#F5E6D8", "tertiaryColor": "#CC785C", "noteBkgColor": "#FAF0E6", "noteBorderColor": "#91918D"}, "sequence": {"actorMargin": 50, "width": 150, "height": 65, "boxMargin": 10, "boxTextMargin": 5, "noteMargin": 10, "messageMargin": 35}}}%%
sequenceDiagram
participant App as Your Application
participant Agent as Claude Agent
participant Tools as Tools/Hooks
participant FS as Environment/<br/>File System
App->>Agent: Initialize with AsyncGenerator
activate Agent
App->>Agent: Yield Message 1
Agent->>Tools: Execute tools
Tools->>FS: Read files
FS-->>Tools: File contents
Tools->>FS: Write/Edit files
FS-->>Tools: Success/Error
Agent-->>App: Stream partial response
Agent-->>App: Stream more content...
Agent->>App: Complete Message 1
App->>Agent: Yield Message 2 + Image
Agent->>Tools: Process image & execute
Tools->>FS: Access filesystem
FS-->>Tools: Operation results
Agent-->>App: Stream response 2
App->>Agent: Queue Message 3
App->>Agent: Interrupt/Cancel
Agent->>App: Handle interruption
Note over App,Agent: Session stays alive
Note over Tools,FS: Persistent file system<br/>state maintained
deactivate Agent优势
优势
图像上传
直接将图像附加到消息中进行视觉分析和理解
排队消息
发送多个按顺序处理的消息,并能够中断
工具集成
在会话期间完全访问所有工具和自定义 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);
}
}