深入理解 AgentFlow:AI Agent 工作流编排的艺术
从核心概念到实战案例,全面解析 AgentFlow 工作流编排框架,帮你构建可靠的多 Agent 协作系统
深入理解 AgentFlow:AI Agent 工作流编排的艺术
前言
随着大语言模型(LLM)的快速发展,AI Agent 已经从"单一对话"演进到"多步协作"的新阶段。然而,当我们需要让多个 Agent 协同完成复杂任务时,如何编排它们的工作流就成了核心挑战。
AgentFlow 正是为解决这一问题而生的工作流编排框架。它提供了直观、灵活且可扩展的方式来定义、执行和监控 AI Agent 的工作流程。
本文将从基础概念到高级实践,带你全面掌握 AgentFlow。
一、为什么需要 AgentFlow?
1.1 单一 Agent 的局限
一个 LLM Agent 通常只能处理单一类型的任务。但在真实业务场景中,一个完整的流程往往需要多个能力:
- 意图识别 → 知识检索 → 内容生成 → 质量审核
- 数据分析 → 报告生成 → 格式转换 → 邮件发送
这些步骤需要不同的 Agent 各司其职,按特定顺序协作完成。
1.2 手动编排的痛点
如果不使用编排框架,你可能需要:
- 手写大量胶水代码串联各个 Agent
- 自行处理状态传递和错误恢复
- 缺乏可视化,难以调试和优化
- 无法复用已有的工作流模板
AgentFlow 正是为了解决这些痛点。
二、AgentFlow 核心概念
2.1 四大核心组件
┌─────────────────────────────────────────────┐
│ AgentFlow │
│ │
│ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │ Node │───▶│ Node │───▶│ Node │ │
│ └──────┘ └──────┘ └──────┘ │
│ │ │ │
│ │ ┌──────▼──────┐ │
│ │ │ Conditional │ │
│ │ │ Edge │ │
│ │ └──────┬──────┘ │
│ │ │ │
│ ┌────▼────────────▼────┐ │
│ │ State │ │
│ │ (共享上下文数据) │ │
│ └──────────────────────┘ │
└─────────────────────────────────────────────┘| 概念 | 说明 | 类比 | |:---|:---|:---| | Node(节点) | 工作流中的一个执行单元,通常是一个 Agent 或函数 | 流水线上的工位 | | Edge(边) | 节点之间的连接,定义执行顺序 | 传送带 | | Conditional Edge | 根据运行时状态动态决定下一步走向 | 分拣器 | | State(状态) | 贯穿整个工作流的共享数据 | 工件/半成品 |
2.2 一个简单的例子
import { AgentFlow, Agent, State } from '@agentflow/core';
// 定义状态类型
interface WorkflowState extends State {
userQuery: string;
intent: string;
response: string;
}
// 创建 Agent
const intentAgent = new Agent({
name: 'intent-recognizer',
model: 'gpt-4',
prompt: '分析用户意图,输出: question / complaint / request',
});
const responseAgent = new Agent({
name: 'response-generator',
model: 'gpt-4',
prompt: '根据用户意图和查询内容,生成专业回复',
});
// 构建工作流
const flow = new AgentFlow<WorkflowState>({
nodes: {
recognize: intentAgent.asNode(),
respond: responseAgent.asNode(),
},
edges: [
{ from: 'START', to: 'recognize' },
{ from: 'recognize', to: 'respond' },
{ from: 'respond', to: 'END' },
],
});
// 执行
const result = await flow.run({
userQuery: '我的订单怎么还没发货?',
});三、实战:构建智能客服工作流
下面我们用 AgentFlow 构建一个完整的智能客服系统:
import { AgentFlow, Agent, ConditionalEdge } from '@agentflow/core';
interface CustomerServiceState extends State {
userQuery: string;
intent: 'question' | 'complaint' | 'refund' | 'unknown';
context: string;
response: string;
needHuman: boolean;
}
// 1. 意图识别 Agent
const intentAgent = new Agent({
name: 'intent-agent',
model: 'gpt-4',
systemPrompt: `你是一个意图分类器,将用户输入分类为:
- question: 产品咨询
- complaint: 投诉
- refund: 退款请求
- unknown: 无法识别
只输出分类结果,不要其他内容。`,
});
// 2. 知识检索 Agent
const knowledgeAgent = new Agent({
name: 'knowledge-agent',
model: 'gpt-4',
tools: [vectorSearchTool], // 接入向量数据库
systemPrompt: '根据用户问题检索相关知识库,返回相关信息',
});
// 3. 回复生成 Agent
const responseAgent = new Agent({
name: 'response-agent',
model: 'gpt-4',
systemPrompt: '基于检索到的知识,生成友好、专业的客服回复',
});
// 4. 人工升级 Agent
const escalateAgent = new Agent({
name: 'escalate-agent',
model: 'gpt-4',
systemPrompt: '生成转人工话术,并创建工单',
});
// 条件路由:根据意图决定下一步
const routeByIntent = (state: CustomerServiceState): string => {
if (state.intent === 'unknown') return 'escalate';
if (state.intent === 'complaint') return 'escalate';
return 'knowledge'; // question 和 refund 走知识检索
};
// 构建工作流
const customerServiceFlow = new AgentFlow<CustomerServiceState>({
nodes: {
intent: intentAgent.asNode(),
knowledge: knowledgeAgent.asNode(),
response: responseAgent.asNode(),
escalate: escalateAgent.asNode(),
},
edges: [
{ from: 'START', to: 'intent' },
// 条件边:根据意图动态路由
ConditionalEdge.from('intent', routeByIntent, {
knowledge: 'knowledge',
escalate: 'escalate',
}),
{ from: 'knowledge', to: 'response' },
{ from: 'response', to: 'END' },
{ from: 'escalate', to: 'END' },
],
});
// 执行工作流
const result = await customerServiceFlow.run({
userQuery: '我买的手机屏幕碎了,要退款',
});执行流程图
用户输入: "我买的手机屏幕碎了,要退款"
│
▼
┌─────────┐
│ 意图识别 │ → refund
└────┬────┘
│
▼
┌─────────┐
│ 知识检索 │ → 检索退款政策
└────┬────┘
│
▼
┌─────────┐
│ 回复生成 │ → 生成退款指引
└────┬────┘
│
▼
输出结果
四、高级模式
4.1 并行执行
当多个步骤之间没有依赖关系时,可以并行执行以提升效率:
const flow = new AgentFlow({
nodes: {
analyze: analyzeAgent.asNode(),
summarize: summarizeAgent.asNode(),
translate: translateAgent.asNode(),
merge: mergeAgent.asNode(),
},
edges: [
{ from: 'START', to: 'analyze' },
// 并行分支
{ from: 'analyze', to: 'summarize' },
{ from: 'analyze', to: 'translate' },
// 等待两个分支都完成后再合并
{ from: 'summarize', to: 'merge' },
{ from: 'translate', to: 'merge' },
{ from: 'merge', to: 'END' },
],
});4.2 子流程复用
将常用的工作流片段封装为子流程,提高复用性:
// 定义子流程:内容审核
const contentReviewSubflow = new SubFlow({
nodes: {
check: checkAgent.asNode(),
filter: filterAgent.asNode(),
},
edges: [
{ from: 'START', to: 'check' },
{ from: 'check', to: 'filter' },
{ from: 'filter', to: 'END' },
],
});
// 在主流程中使用
const mainFlow = new AgentFlow({
nodes: {
generate: generateAgent.asNode(),
review: contentReviewSubflow.asNode(), // 子流程作为节点
publish: publishAgent.asNode(),
},
edges: [
{ from: 'START', to: 'generate' },
{ from: 'generate', to: 'review' },
{ from: 'review', to: 'publish' },
{ from: 'publish', to: 'END' },
],
});4.3 错误处理与重试
const flow = new AgentFlow({
nodes: {
fetch: fetchAgent.asNode({
retry: {
maxAttempts: 3,
delay: 1000,
backoff: 'exponential',
},
onError: async (error, state) => {
// 降级处理:使用缓存数据
state.response = await cache.get(state.userQuery);
return 'END'; // 跳过后续步骤
},
}),
},
});4.4 可观测性
AgentFlow 内置了丰富的可观测性支持:
flow.on('node:start', (event) => {
console.log(`[${event.timestamp}] 节点 ${event.nodeId} 开始执行`);
});
flow.on('node:complete', (event) => {
console.log(`[${event.timestamp}] 节点 ${event.nodeId} 完成,耗时 ${event.duration}ms`);
});
flow.on('edge:traverse', (event) => {
console.log(`边 ${event.from} → ${event.to} 被触发`);
});
flow.on('error', (event) => {
console.error(`节点 ${event.nodeId} 出错: ${event.error.message}`);
});五、最佳实践
✅ 推荐做法
- 状态设计要精简 — State 只包含必要的字段,避免传递大量无关数据
- 节点职责单一 — 每个 Node 只做一件事,保持高内聚
- 善用条件边 — 用 Conditional Edge 实现动态路由,而非硬编码
- 添加超时控制 — 为每个节点设置合理的超时时间
- 记录执行日志 — 开启可观测性,方便排查问题
❌ 避坑指南
- 避免循环依赖 — 工作流中不要出现 A → B → A 的死循环
- 不要过度拆分 — 节点太细会增加编排复杂度,找到合适的粒度
- 注意状态竞争 — 并行节点不要同时修改同一个 State 字段
- 做好降级方案 — LLM 调用可能失败,要有兜底策略
六、方案对比
| 特性 | AgentFlow | LangGraph | Dify | AutoGen | |:---|:---:|:---:|:---:|:---:| | 可视化编排 | ✅ | ✅ | ✅ | ❌ | | 条件路由 | ✅ | ✅ | ✅ | ✅ | | 并行执行 | ✅ | ✅ | ❌ | ✅ | | 子流程复用 | ✅ | ❌ | ✅ | ❌ | | 错误重试 | ✅ | ❌ | ✅ | ❌ | | TypeScript 原生 | ✅ | ❌ | ❌ | ❌ | | 学习曲线 | 低 | 中 | 低 | 高 | | 适合场景 | 全场景 | 研究/原型 | 低代码 | 多Agent对话 |
总结
AgentFlow 是一个面向生产环境的 AI Agent 工作流编排框架,它的核心优势在于:
- 直观 — 基于图的工作流定义,所见即所得
- 灵活 — 支持条件路由、并行执行、子流程等高级模式
- 可靠 — 内置错误处理、重试机制和可观测性
- 易用 — TypeScript 原生支持,类型安全,API 简洁
如果你的项目需要编排多个 AI Agent 协同工作,AgentFlow 值得一试。
📎 参考资源