首页/案例库/AI Agent 工作流编排
高级AI 智能体

AI Agent 工作流编排

LangGraph 状态机驱动的 Agent

当单一 Agent 无法处理复杂任务时,需要工作流编排:将任务拆分为有向图(DAG/循环图),每个节点是独立的 LLM 调用或工具执行,边决定控制流。基于 LangGraph StateGraph 深度理解 Agent 工作流的状态管理、条件路由与 Human-in-the-Loop。

LangGraph工作流StateGraphHuman-in-the-Loop条件路由Checkpointing
STEP_1
Annotation 的 reducer 设计是 LangGraph 的精妙之处:不同字段可以有不同的合并策略。消息列表用追加(实现对话历史),任务状态用覆盖(最新状态覆盖旧状态),收集数据用对象合并(积累所有工具结果)。
STATEGRAPH 类型设计 — PROCESSING
state-definition.log
import { StateGraph, Annotation } from '@langchain/langgraph'

// 定义工作流状态
const AgentState = Annotation.Root({
  // 对话消息列表(追加模式)
  messages: Annotation<Message[]>({
    reducer: (current, update) => [...current, ...update],
    default: () => []
  }),
  // 任务状态(覆盖模式)
  taskStatus: Annotation<'pending' | 'running' | 'done' | 'failed'>({
    reducer: (_, update) => update,
    default: () => 'pending'
  }),
  // 收集到的数据(合并模式)
  collectedData: Annotation<Record<string, unknown>>({
    reducer: (current, update) => ({ ...current, ...update }),
    default: () => ({})
  }),
  // 需要人工审核的内容
  pendingApproval: Annotation<string | null>({
    reducer: (_, update) => update,
    default: () => null
  })
})

type AgentStateType = typeof AgentState.State

状态定义LangGraph 的核心是 StateGraph:定义一个贯穿整个工作流的共享状态类型。每个节点接收状态、执行操作、返回状态更新。Reducer 函数控制状态如何合并(追加 vs 覆盖)。

实时沙盒SANDBOX
NOMINAL
快速场景
手动调节
最大循环次数
防止 Agent 工作流无限循环
10
循环次数适中,能完成大多数任务
并行分支数
同时执行的工具调用数
1
串行执行,结果可预测
启用人工审核
全自动执行,速度最快