基于 LangChain.js + LangGraph 实现的多智能体协作系统。
本系统模拟一个客服团队,包含三个智能体:
👋 接待员 (Receptionist)
🔧 技术支持 (Tech Support)
💼 销售顾问 (Sales)
用户问题 ↓ [接待员] 分析问题类型 ↓ 决策路由 ↓ ┌─────┴─────┐ ↓ ↓ [技术支持] [销售顾问] ↓ ↓ 技术解答 销售咨询 ↓ ↓ └─────┬─────┘ ↓ 最终回复
# 开发模式
yarn start:dev
# 生产模式
yarn build
NODE_ENV=production yarn start
打开浏览器访问:http://localhost:3000/multi-agent
# 测试聊天接口
curl -X POST http://localhost:3000/api/multi-agent/chat \
-H "Content-Type: application/json" \
-d '{"question": "你们的产品多少钱?"}'
# 健康检查
curl http://localhost:3000/api/multi-agent/health
# 获取工作流信息
curl http://localhost:3000/api/multi-agent/workflow
src/agents/multi-agent/ ├── types.ts # 类型定义 ├── orchestrator.ts # 智能体协调器 (LangGraph) ├── multi-agent.service.ts # NestJS 服务 ├── multi-agent.controller.ts # API 控制器 ├── multi-agent.module.ts # NestJS 模块 └── agents/ # 智能体实现 ├── receptionist.agent.ts # 接待员智能体 ├── tech-support.agent.ts # 技术支持智能体 └── sales.agent.ts # 销售顾问智能体
使用 LangGraph 的 StateGraph 编排智能体协作:
const workflow = new StateGraph<AgentState>({
channels: {
messages: {...},
userQuestion: {...},
currentAgent: {...},
// ...更多状态通道
},
});
// 添加智能体节点
workflow.addNode('receptionist', receptionistHandler);
workflow.addNode('tech_support', techSupportHandler);
workflow.addNode('sales', salesHandler);
// 定义流转规则
workflow.addEdge(START, 'receptionist');
workflow.addConditionalEdges('receptionist', routingDecision, {...});
workflow.addEdge('tech_support', END);
workflow.addEdge('sales', END);
所有智能体共享同一个状态对象 AgentState:
interface AgentState {
messages: Message[]; // 消息历史
userQuestion: string; // 用户问题
currentAgent?: AgentType; // 当前智能体
finalAnswer?: string; // 最终答案
routingReason?: string; // 路由原因
processingSteps: Step[]; // 处理步骤
}
接待员智能体使用 LLM 进行智能路由:
// 接待员分析用户问题
const decision = await receptionistAgent.routeQuestion(userQuestion);
// 返回路由决策
{
targetAgent: 'tech_support' | 'sales',
reason: '路由原因',
confidence: 0.0-1.0
}
处理用户问题(一次性返回完整结果)
请求:
{
"question": "你们的产品多少钱?"
}
响应:
{
"success": true,
"data": {
"answer": "最终答案",
"processingSteps": [...],
"messages": [...],
"routingReason": "路由原因",
"workflowInfo": {...}
},
"timestamp": 1234567890
}
流式处理用户问题(Server-Sent Events)
请求:
{
"question": "我的账号登录不上去了"
}
响应: SSE 流式数据
健康检查
获取工作流信息
agents/ 目录下创建新智能体:export class CustomAgent {
constructor(private llm: ChatOpenAI) {}
async handleQuestion(question: string): Promise<AgentResponse> {
// 实现你的逻辑
}
}
types.ts 中添加智能体类型:export enum AgentType {
// ...existing
CUSTOM = 'custom',
}
orchestrator.ts 中注册节点:workflow.addNode('custom', async (state: AgentState) => {
const response = await customAgent.handleQuestion(state.userQuestion);
return { /* 状态更新 */ };
});
本演示系统展示了以下核心概念:
欢迎提交 Issue 和 Pull Request!
MIT