Claude-Agent-SDK:Streaming Input 流式输入

原文:code.claude.com/docs/en/age...

Streaming Input 流式输入

Understanding the two input modes for Claude Agent SDK and when to use each

深入了解 Claude Agent SDK 的两种输入模式及其适用场景。

Overview 概览

The Claude Agent SDK supports two distinct input modes for interacting with agents:

Claude Agent SDK 支持两种不同的输入模式来与代理(Agent)进行交互:

  • Streaming Input Mode (Default & Recommended) - A persistent, interactive session
  • 流式输入模式 (Streaming Input Mode)(默认且推荐)------ 一种持续、交互式的会话。
  • Single Message Input - One-shot queries that use session state and resuming
  • 单消息输入 (Single Message Input) ------ 利用会话状态和恢复(resuming)机制的一次性查询。

This guide explains the differences, benefits, and use cases for each mode to help you choose the right approach for your application.

本指南将解释每种模式的区别、优势及适用场景,帮助你为应用程序选择最合适的方法。

Streaming Input Mode (Recommended) 流式输入模式(推荐)

Streaming input mode is the preferred way to use the Claude Agent SDK. It provides full access to the agent's capabilities and enables rich, interactive experiences.

流式输入模式是使用 Claude Agent SDK 的首选方式。它提供了对代理(Agent)能力的完整访问权,并能实现丰富的交互式体验。

It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.

该模式允许代理作为一个长生命周期的进程运行,能够接收用户输入、处理中断、呈现权限请求并进行会话管理。

How It Works 工作原理

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

Benefits 优势

  • 直接在消息中附带图片,用于视觉分析与理解
  • 发送多条按顺序处理的消息,并具备中断能力
  • 在会话期间拥有对所有工具和自定义 MCP 服务器的完整访问权限
  • 利用生命周期钩子(Hooks)在各个阶段自定义行为
  • 在响应生成时即时查看,而不仅仅是获取最终结果
  • 自然地维持跨多轮对话的上下文内容

Implementation Example 实现示例

typescript 复制代码
import { query } from "@anthropic-ai/claude-agent-sdk";
import { readFile } from "fs/promises";

async function* generateMessages() {
// First message
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "Analyze this codebase for security issues"
    }
  };

  // / 等待用户在终端输入下一条指令  (占位符,让代码看起来更真实一些)
  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: await readFile("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);
  }
}

代码关键点讲解

  1. query() 内部会 for await 消费这个 generator,每次 Claude 返回结果后,继续从 generator 拿下一条消息
  2. 消息是懒执行的 --- generator 不会一次性发送所有消息,而是在 Claude 回复后才 yield 下一条
  3. 可以在 yield 之间插入异步逻辑(等待用户输入、读取文件、网络请求等)
  4. 实现了多轮对话 --- 每个 yield 对应一个 user turn,SDK 负责维护整个对话历史

简单说:prompt 接受一个 async iterable,query() 驱动整个多轮对话流程,你只需要 yield 消息即可。

Single Message Input 单消息输入

Single message input is simpler but more limited.

单消息输入模式更简单,但功能局限性也更多。

When to Use Single Message Input 何时使用单消息输入

Use single message input when:

在以下情况下,请使用单消息输入:

  • You need a one-shot response
  • 你需要一次性响应(One-shot response)
  • You do not need image attachments, hooks, etc.
  • 你不需要图片附件、钩子(Hooks)等功能。
  • You need to operate in a stateless environment, such as a lambda function
  • 你需要在无状态环境中运行,例如 Lambda 函数。

Limitations 限制

Single message input mode does not support: 单消息输入模式不支持:

  • Direct image attachments in messages
  • 在消息中直接附加图片
  • Dynamic message queueing
  • 动态消息队列
  • Real-time interruption
  • 实时中断
  • Hook integration
  • 钩子(Hook)集成
  • Natural multi-turn conversations
  • 自然的多轮对话

Implementation Example

typescript 复制代码
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);
  }
}
相关推荐
码云社区19 分钟前
Spring Boot上门按摩服务系统源码:上门到店服务目录与门店协同方案
java·spring boot·后端·上门服务·上门按摩·上门小程序
AAA修煤气灶刘哥23 分钟前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
Cosolar25 分钟前
LoopForge:把团队的交付经验变成可执行的工程资产
人工智能·后端·agent
tong_li25 分钟前
给娃做个 AI 陪写作业助手:LangChain4j 入门(四):向量库搬进 Qdrant(向量数据库入门)
后端
Rain的Java大神之路36 分钟前
大表 JOIN 不必靠堆内存:Dojao 的跨源 SQL、减量溢写与 Python UDF 实战
java·大数据·后端
AAA修煤气灶刘哥1 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
Cosolar1 小时前
概率性计算的系统工程:从 Super-agent 与 Octop 看多 Agent 架构的收敛
人工智能·后端·架构
bai2731 小时前
npm 在 cmd 里能跑,Node 的 spawn 一调就 EINVAL:Windows 上 .cmd 的六种调法实测
javascript·后端
挖掘狂人2 小时前
如何保证缓存与数据库一致性
数据库·后端·程序员
SimonKing2 小时前
别再自己写同步脚本了!这款开源中间件,一套界面搞定 22 种数据源
java·后端·程序员