💬 对话与流式处理详解

深入理解 Agent 对话的流式架构、AsyncQueue 广播、后台持久化与断线恢复机制

本课程聚焦 src/lib/agents/ 目录下的核心模块,这是 Kuai 前端最复杂也最精妙的部分 — 它让 AI 对话像 ChatGPT 一样实时流式输出,同时支持浏览器关闭后任务继续运行。

📚 前置知识

🏗️ 整体架构:chatStreamHandler

核心模块 对话流处理的全部逻辑集中在 src/lib/agents/chatStreamHandler.js 中,这是一个近 1900 行的文件,是整个项目最核心的模块。

设计目标

核心数据流

┌─────────────────────────────────────────────────────────────────┐ │ chatStreamHandler 架构 │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ 前端 POST 请求 │ │ │ │ │ ▼ │ │ ┌──────────────────┐ │ │ │ Agent 执行引擎 │ agent.streamEvents() — 生产者 │ │ │ (LangGraph) │ │ │ └────────┬─────────┘ │ │ │ event stream │ │ ▼ │ │ ┌──────────────────┐ │ │ │ AsyncQueue │ 广播器 — 一进多出 │ │ │ broadcastAsync │ │ │ └──┬───────────┬───┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌──────┐ ┌──────────────┐ │ │ │ 队列A │ │ 队列B │ 两个独立消费者 │ │ └──┬───┘ └──────┬───────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌──────┐ ┌──────────────┐ │ │ │AI SDK│ │ persistIn- │ │ │ │ 流 │ │ Background() │ 后台 DB 持久化 │ │ └──┬───┘ └──────┬───────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌──────┐ ┌──────────────┐ │ │ │ 前端 │ │ MongoDB │ │ │ │ SSE │ │ 增量写入 │ │ │ └──────┘ └──────────────┘ │ └─────────────────────────────────────────────────────────────────┘

📡 AsyncQueue 广播机制

核心设计 AsyncQueue 是一个自定义的异步队列,用于将生产者(Agent streamEvents)的事件分发给多个消费者(前端展示 + DB 持久化)。

AsyncQueue 实现原理

// src/lib/agents/chatStreamHandler.js

class AsyncQueue {
  constructor() {
    this._queue = [];      // 待消费的事件缓冲区
    this._resolve = null;  // 消费者的 Promise resolve 函数
    this._done = false;    // 是否已结束
    this._error = null;    // 错误信息
  }

  // 生产者:推入事件
  push(value) {
    if (this._done) return;
    if (this._resolve) {
      // 消费者正在等待,直接传递
      this._resolve({ value, done: false });
      this._resolve = null;
    } else {
      // 没有消费者等待,放入缓冲区
      this._queue.push(value);
    }
  }

  // 标记结束
  end() {
    this._done = true;
    if (this._resolve) {
      this._resolve({ value: undefined, done: true });
    }
  }

  // 实现 AsyncIterator 协议,支持 for await...of
  [Symbol.asyncIterator]() {
    return {
      next: () => {
        if (this._queue.length > 0) {
          return Promise.resolve({ value: this._queue.shift(), done: false });
        }
        if (this._done) {
          return Promise.resolve({ value: undefined, done: true });
        }
        // 缓冲区为空,等待新事件
        return new Promise((resolve, reject) => {
          this._resolve = resolve;
        });
      },
    };
  }
}

广播函数

broadcastAsyncIterable 接收一个源事件流,创建多个队列,后台循环将每个事件推入所有队列:

function broadcastAsyncIterable(source, count) {
  const queues = Array.from({ length: count }, () => new AsyncQueue());

  // 后台消费源并分发
  (async () => {
    try {
      for await (const event of source) {
        for (const q of queues) {
          q.push(event);  // 广播给所有消费者
        }
      }
      for (const q of queues) q.end();
    } catch (err) {
      // 忽略前端断开导致的错误
      if (err?.code === 'ERR_INVALID_STATE') {
        for (const q of queues) q.end();
        return;
      }
      for (const q of queues) q.throw(err);
    }
  })();

  return queues;  // 返回两个独立的消费者队列
}

关键设计点

📋 流式事件类型

事件系统 定义在 src/lib/agents/streamEventTypes.js 中,统一管理所有事件类型。

三层事件体系

层级 常量名 事件类型 说明
STREAM_EVENT_TYPE
(应用层)
CONTENT content AI 生成的文本内容
TOOL_CALL tool_call 工具调用请求
TOOL_START / TOOL_END tool_start / tool_end 工具执行开始/结束
AGENT_START / AGENT_END agent_start / agent_end Agent 生命周期
TODO_UPDATE todo_update Todo 列表更新
DONE done 对话完成
ERROR error 执行出错
LANGCHAIN_EVENT_TYPE
(LangChain 原生)
CHAT_MODEL_STREAM on_chat_model_stream LLM 流式输出(一个 token 一次)
TOOL_START / TOOL_END on_tool_start / on_tool_end 工具调用生命周期
TOOL_ERROR on_tool_error 工具执行出错
CHAIN_START / CHAIN_END on_chain_start / on_chain_end Agent 执行链生命周期

事件过滤:只处理关键事件

// 在 persistInBackground 中,只监听这些事件以提升性能
const RELEVANT_EVENTS = new Set([
  'on_chat_model_stream',  // LLM 文本输出
  'on_tool_start',         // 工具开始
  'on_tool_end',           // 工具结束
  'on_tool_error',         // 工具错误
  'on_chain_end',          // 链结束(含 todo 更新)
]);

⚙️ 后台执行与断线恢复

架构核心 这是本项目最核心的设计 — Agent 任务与 HTTP 连接完全解耦。

后台持久化管道

persistInBackground() 函数是 DB 持久化的核心,它:

  1. 消费 LangGraph streamEvents 流中的事件
  2. 实时累积文本内容(state.content)
  3. 跟踪工具调用状态(state.toolCalls)
  4. 维护有序的 parts 数组(交错的 text 和 tool)
  5. 节流写入 MongoDB(每 500ms 最多写一次)
// 核心状态对象
const state = {
  content: '',           // AI 累积生成的文本
  toolCalls: [],         // 工具调用记录数组
  parts: [],             // 有序 parts(text 和 tool 交错)
  todos: [],             // Todo 列表
  lastDbUpdate: 0,       // 上次 DB 更新时间戳
  currentTextSegment: '', // 当前正在累积的文本段
};

// 节流写入 DB
const DB_UPDATE_INTERVAL_MS = 500;  // 每 500ms 最多写一次

async function flushToDb(force = false) {
  const now = Date.now();
  if (!force && now - state.lastDbUpdate < DB_UPDATE_INTERVAL_MS) return;
  state.lastDbUpdate = now;

  await chatHistoryService.updateMessage(sessionId, messageKey, {
    content: state.content,
    toolCalls: state.toolCalls,
    parts: [...state.parts],
    todos: [...state.todos],
    streaming: true,  // 标记为"正在流式传输中"
  });
}

断线恢复流程

用户发送消息 │ ▼ 创建会话 + 消息记录(streaming: true) │ ▼ Agent 开始执行(后台持续运行) │ │ ▼ ▼ 前端 SSE 流 DB 增量写入(streaming: true) │ │ ▼ │ 用户关闭浏览器 │ │ │ ✗ 断开连接 ▼ Agent 继续执行... 最终写入(streaming: false) 用户刷新页面 │ ▼ 从 MongoDB 加载会话 │ ▼ 最后一条消息 streaming=true? → 是:显示为"正在思考..."(任务仍在后台运行) → 否:显示完整结果(已完成)

任务注册表

// 全局任务注册表 — 跟踪所有正在运行的任务
const runningTasks = new Map();

// 终止任务
export function abortTask(taskId) {
  const task = runningTasks.get(taskId);
  if (task) {
    task.abortController.abort();  // 通过 AbortSignal 终止
    runningTasks.delete(taskId);
    return true;
  }
  return false;
}

// 查询运行中的任务
export function getRunningTasks() {
  return Array.from(runningTasks.values());
}

💾 MongoDB 增量持久化

数据层 会话持久化通过 src/lib/agents/conversationStore.js 实现,使用 MongoDB 的 agent_conversations 集合。

ConversationStore 核心操作

// src/lib/agents/conversationStore.js

class ConversationStore {
  constructor() {
    this.collectionName = 'agent_conversations';
  }

  // 创建新会话
  async createConversation(options) {
    const conversation = {
      id: `conv-${new ObjectId().toHexString()}`,
      agentId: options.agentId,
      userId: options.userId,
      messages: [],
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    await collection.insertOne(conversation);
    return conversation;
  }

  // 增量添加消息($push 操作符)
  async addMessage(conversationId, message) {
    return await collection.findOneAndUpdate(
      { id: conversationId },
      {
        $push: { messages: message },
        $set: { updatedAt: new Date() },
      },
      { returnDocument: 'after' },
    );
  }

  // 批量添加消息
  async addMessages(conversationId, messages) {
    return await collection.findOneAndUpdate(
      { id: conversationId },
      {
        $push: { messages: { $each: messages } },
        $set: { updatedAt: new Date() },
      },
      { returnDocument: 'after' },
    );
  }
}

Parts 数组:保留对话交错顺序

对话中的 text 和 tool_call 是交错出现的(AI 先说一段话,调用工具,再说一段话)。parts 数组精确记录了这个顺序:

{
  "parts": [
    { "type": "text", "text": "让我帮你分析一下代码..." },
    { "type": "tool", "toolName": "code_explore", "input": "...", "output": "...", "status": "done" },
    { "type": "text", "text": "分析结果如下:..." },
    { "type": "tool", "toolName": "file_reader", "input": "...", "output": "...", "status": "done" },
    { "type": "text", "text": "以上是完整的分析。" }
  ]
}

Checkpointer:LangGraph 状态持久化

除了对话内容,LangGraph Agent 本身的状态也需要持久化。通过 src/lib/agents/checkpointer.js 使用官方 MongoDBSaver:

// 使用官方 MongoDBSaver(单例模式)
checkpointerInstance = new MongoDBSaver({
  client,                    // MongoClient 实例
  dbName: 'kuai',           // 数据库名
  checkpointCollectionName: 'langgraph_checkpoints',
});

// 构建配置 — thread_id 关联对话线程
const config = buildConfig({ threadId: "thread-123" });

// Agent 自动加载历史状态,只传递新消息
await agent.invoke({ messages: [newMessage] }, { ...config, checkpointer });

🔄 完整执行流程

以 POST /api/agents/[id]/chat 为例,完整流程如下:

  1. 接收请求:解析 agentId、message、sessionId
  2. 会话管理:创建或复用 MongoDB 会话
  3. 历史加载:从 DB 加载历史消息,转换为 LangChain 格式
  4. 消息去重:避免重复发送相同消息
  5. Agent 执行:调用 agent.streamEvents() 启动流式执行
  6. 事件广播:broadcastAsyncIterable() 创建 2 个队列
  7. 前端流:队列 A → toUIMessageStream() → AI SDK 响应
  8. DB 持久化:队列 B → persistInBackground() → MongoDB
  9. HTTP 响应返回:SSE 流开始推送到前端
  10. 后台继续:即使前端断开,DB 管道继续运行直到完成

🧪 知识检验

题目 1:AsyncQueue 广播

在 chatStreamHandler 中,broadcastAsyncIterable() 创建了几个消费者队列?

A. 1 个 — 只给前端展示
B. 2 个 — 一个给前端流,一个给 DB 持久化
C. 3 个 — 前端、DB、日志各一个
D. 不固定,根据连接数动态创建
答案 B。代码中 broadcastAsyncIterable(source, 2) 固定创建 2 个 AsyncQueue:队列 A 通过 toUIMessageStream() 转换为 AI SDK 响应流返回给前端,队列 B 传入 persistInBackground() 进行增量 DB 写入。两个消费者互相独立,前端断开不影响 DB 管道。

题目 2:断线恢复

当用户在 AI 生成过程中关闭浏览器,然后重新打开页面,系统如何判断消息是否还在生成中?

A. 检查 WebSocket 连接状态
B. 检查 runningTasks 注册表
C. 检查 MongoDB 中消息的 streaming 字段
D. 检查 localStorage 中的标记
答案 C。每条消息在写入 MongoDB 时都有一个 streaming 字段:true 表示正在生成中,false 表示已完成。当用户刷新页面加载历史会话时,前端检查最后一条 assistant 消息的 streaming 值 — 如果为 true,说明后台可能还在执行(或异常中断),前端显示"思考中"状态。

题目 3:节流写入

persistInBackground 中 DB 写入的节流间隔是多少?为什么需要节流?

A. 100ms — 为了减少网络延迟
B. 500ms — 减少 MongoDB 写入频率,避免压垮数据库
C. 1000ms — 等待足够的内容积累再写入
D. 不节流,每个事件都立即写入
答案 B。DB_UPDATE_INTERVAL_MS = 500,即每 500ms 最多写一次 MongoDB。LLM 每秒可能产生数十个 token 事件,如果每个事件都写 DB 会产生大量写操作。节流后写入频率降低到每秒 2 次,显著减轻 MongoDB 压力。工具开始/结束事件会强制写入(flushToDb(true)),确保重要状态变更立即持久化。