首页 教程 常见问题

6.6 流式处理

概述

流式处理允许实时获取 Agent 的响应,无需等待完整输出。对于长文本生成和交互式应用非常重要。

流式输出

TypeScript

const stream = agent.runStream({
  prompt: '写一个完整的快速排序实现,包含详细注释'
});

for await (const event of stream) {
  switch (event.type) {
    case 'content_block_delta':
      // 实时输出文本片段
      process.stdout.write(event.delta.text);
      break;
    case 'message_stop':
      console.log('\n--- 完成 ---');
      break;
  }
}

Python

stream = agent.run_stream(prompt="解释快速排序的原理")

for event in stream:
    if event.type == 'content_block_delta':
        print(event.delta.text, end='', flush=True)
    elif event.type == 'message_stop':
        print("\n--- 完成 ---")

事件类型

事件类型说明
content_block_start内容块开始
content_block_delta内容块增量更新
content_block_stop内容块结束
message_start消息开始
message_delta消息增量
message_stop消息结束
tool_use工具调用开始
tool_result工具结果
error错误发生

工具调用流式

const stream = agent.runStream({
  prompt: '搜索最新的AI新闻'
});

for await (const event of stream) {
  if (event.type === 'tool_use') {
    console.log(`调用工具: ${event.name}`);
    console.log(`参数:`, event.input);
  } else if (event.type === 'tool_result') {
    console.log(`结果:`, event.content);
  }
}

流式与会话结合

const session = agent.createSession();

const stream = session.runStream({
  prompt: '用中文回答:什么是机器学习?'
});

let fullResponse = '';
for await (const event of stream) {
  if (event.type === 'content_block_delta') {
    fullResponse += event.delta.text;
  }
}

console.log('完整响应:', fullResponse);

取消流式请求

const controller = new AbortController();

const stream = agent.runStream({
  prompt: '生成很长的文本...',
  signal: controller.signal
});

// 5秒后取消
setTimeout(() => controller.abort(), 5000);

try {
  for await (const event of stream) {
    // 处理事件
  }
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('请求已取消');
  }
}

实时打字效果示例

function createTypingEffect(stream) {
  return new ReadableStream({
    async start(controller) {
      for await (const event of stream) {
        if (event.type === 'content_block_delta') {
          controller.enqueue(event.delta.text);
        } else if (event.type === 'message_stop') {
          controller.close();
        }
      }
    }
  });
}

// 使用
const responseStream = createTypingEffect(
  agent.runStream({ prompt: '讲一个故事' })
);

使用场景