当前位置: 首页 > news >正文

LangGraph 多 Agent 架构与 Supervisor 模式

LangGraph 多 Agent 架构与 Supervisor 模式

核心观点:当一个 Agent 的工具太多、上下文太复杂、需要多个专业领域时,就该拆成多 Agent 系统了。Supervisor 模式是多 Agent 架构中最实用的一种——一个"主管"Agent 负责调度,多个"专家"Agent 各司其职。


一、为什么需要多 Agent 系统?


二、多 Agent 架构全景图

LangGraph 定义了四种多 Agent 架构:


三、Supervisor 模式详解

3.1 架构原理

核心流程

  1. 用户请求进入 Supervisor
  2. Supervisor 分析请求,决定调用哪个 Agent
  3. 被调用的 Agent 执行任务,返回结果给 Supervisor
  4. Supervisor 判断是否需要继续调用其他 Agent,或给出最终答案

3.2 手动实现 Supervisor

import{StateGraph,MessagesAnnotation,Command,}from"@langchain/langgraph";import{ChatOpenAI}from"@langchain/openai";constmodel=newChatOpenAI({model:"gpt-4o-mini"});// ─── Supervisor 节点 ───constsupervisor=async(state:typeofMessagesAnnotation.State)=>{// 让 LLM 决定下一个调用哪个 Agentconstresponse=awaitmodel.withStructuredOutput(...).invoke(...);// 路由到指定 Agent,或结束returnnewCommand({goto:response.next_agent,// "agent1" / "agent2" / "__end__"});};// ─── Agent 1 ───constagent1=async(state:typeofMessagesAnnotation.State)=>{constresponse=awaitmodel.invoke(...);returnnewCommand({goto:"supervisor",// 完成后回到 Supervisorupdate:{messages:[response]},});};// ─── Agent 2 ───constagent2=async(state:typeofMessagesAnnotation.State)=>{constresponse=awaitmodel.invoke(...);returnnewCommand({goto:"supervisor",update:{messages:[response]},});};// ─── 组装 Graph ───constgraph=newStateGraph(MessagesAnnotation).addNode("supervisor",supervisor,{ends:["agent1","agent2","__end__"],}).addNode("agent1",agent1,{ends:["supervisor"],}).addNode("agent2",agent2,{ends:["supervisor"],}).addEdge("__start__","supervisor").compile();

关键点

  • Supervisor 是唯一的决策者,所有 Agent 只和 Supervisor 通信
  • Agent 完成后必须goto: "supervisor",回到决策中枢
  • Supervisor 可以goto: "__end__"结束整个流程

3.3 使用 @langchain/langgraph-supervisor 包

LangGraph 官方提供了@langchain/langgraph-supervisor包,一行代码创建 Supervisor 架构:

import{ChatOpenAI}from"@langchain/openai";import{createSupervisor}from"@langchain/langgraph-supervisor";import{createReactAgent}from"@langchain/langgraph/prebuilt";import{tool}from"@langchain/core/tools";import{z}from"zod";constmodel=newChatOpenAI({modelName:"gpt-4o"});// ─── 创建专家 Agent ───constadd=tool(async(args)=>args.a+args.b,{name:"add",description:"Add two numbers.",schema:z.object({a:z.number(),b:z.number()}),});constmultiply=tool(async(args)=>args.a*args.b,{name:"multiply",description:"Multiply two numbers.",schema:z.object({a:z.number(),b:z.number()}),});constwebSearch=tool(async(args)=>{return"Here are the headcounts for each FAANG company in 2024:\n"+"1. Facebook (Meta): 67,317 employees.\n"+"2. Apple: 164,000 employees.\n"+"3. Amazon: 1,551,000 employees.\n"+"4. Netflix: 14,000 employees.\n"+"5. Google (Alphabet): 181,269 employees.";},{name:"web_search",description:"Search the web for information.",schema:z.object({query:z.string()}),});// 数学专家 AgentconstmathAgent=createReactAgent({llm:model,tools:[add,multiply],name:"math_expert",prompt:"You are a math expert. Always use one tool at a time.",});// 研究专家 AgentconstresearchAgent=createReactAgent({llm:model,tools:[webSearch],name:"research_expert",prompt:"You are a world class researcher with access to web search. Do not do any math.",});// ─── 创建 Supervisor ───constworkflow=createSupervisor({agents:[researchAgent,mathAgent],llm:model,prompt:"You are a team supervisor managing a research expert and a math expert. "+"For current events, use research_agent. "+"For math problems, use math_agent.",});// ─── 运行 ───constapp=workflow.compile();constresult=awaitapp.invoke({messages:[{role:"user",content:"what's the combined headcount of the FAANG companies in 2024??",},],});

执行流程


四、Agent 之间的通信方式

4.1 共享消息列表(Shared Message List)

最常用方式:所有 Agent 共享一个消息列表,通过读写这个列表来协作。

// 所有 Agent 共享 MessagesAnnotation 中的 messages 字段constgraph=newStateGraph(MessagesAnnotation).addNode("agent1",agent1).addNode("agent2",agent2)// ...

两种共享策略

策略一:共享完整历史(Share Full History) → 所有 Agent 看到完整的思考过程 → 优点:帮助其他 Agent 做出更好决策 → 缺点:上下文快速增长,需要记忆管理 策略二:只共享最终结果(Share Final Result) → 每个 Agent 有自己的私有"草稿纸" → 只把最终结果放入共享消息列表 → 优点:上下文可控,适合多 Agent 场景 → 缺点:丢失中间推理过程

4.2 不同 State Schema

不同 Agent 可能需要不同的 State 结构。LangGraph 提供两种方式:

方式一:Subgraph 独立 State → 子图有独立的 State Schema → 通过 input/output transformation 与父图通信 方式二:私有输入 State → Agent 节点函数有独立的私有 State → 只接收它需要的信息

五、多层级层级架构

Supervisor 可以嵌套 Supervisor,形成多层级架构:

// 第一层:研究团队constresearchTeam=createSupervisor({agents:[researchAgent,mathAgent],llm:model,}).compile({name:"research_team"});// 第一层:写作团队constwritingTeam=createSupervisor({agents:[writingAgent,publishingAgent],llm:model,}).compile({name:"writing_team"});// 第二层:顶层 SupervisorconsttopLevelSupervisor=createSupervisor({agents:[researchTeam,writingTeam],llm:model,}).compile({name:"top_level_supervisor"});

架构示意


六、实战:构建一个多 Agent 研究助手

6.1 需求

用户: "帮我研究一下 2024 年 AI 领域的最新进展, 并写一份总结报告" 需要: 1. 搜索最新 AI 新闻 2. 整理和分析信息 3. 撰写报告

6.2 实现

import{createSupervisor}from"@langchain/langgraph-supervisor";import{createReactAgent}from"@langchain/langgraph/prebuilt";import{tool}from"@langchain/core/tools";import{z}from"zod";constmodel=newChatOpenAI({modelName:"gpt-4o"});// ─── 搜索 Agent ───constsearchAgent=createReactAgent({llm:model,tools:[webSearchTool],name:"search_expert",prompt:"You are a search expert. Find the latest information on the topic.",});// ─── 分析 Agent ───constanalysisAgent=createReactAgent({llm:model,tools:[],// 不需要工具,只做分析name:"analysis_expert",prompt:"You are an analysis expert. Organize and analyze the information provided.",});// ─── 写作 Agent ───constwritingAgent=createReactAgent({llm:model,tools:[],name:"writing_expert",prompt:"You are a writing expert. Write a clear and well-structured report.",});// ─── Supervisor ───constworkflow=createSupervisor({agents:[searchAgent,analysisAgent,writingAgent],llm:model,prompt:"You are a research supervisor. "+"For finding information, use search_expert. "+"For organizing information, use analysis_expert. "+"For writing reports, use writing_expert. "+"Always follow the order: search → analyze → write.",outputMode:"last_message",// 只共享最终结果});constapp=workflow.compile();// ─── 运行 ───constresult=awaitapp.invoke({messages:[{role:"user",content:"帮我研究一下 2024 年 AI 领域的最新进展,并写一份总结报告",},],});

6.3 执行流程

用户请求 │ ▼ Supervisor: 需要搜索 → 调用 search_expert │ ▼ search_expert: 搜索 "2024 AI latest developments" │ 返回:GPT-5 发布、Claude 4、Gemini 2.0 等 │ ▼ Supervisor: 搜索完成 → 调用 analysis_expert │ ▼ analysis_expert: 整理信息,分类(模型发布、应用落地、行业趋势) │ ▼ Supervisor: 分析完成 → 调用 writing_expert │ ▼ writing_expert: 撰写结构化报告 │ ▼ Supervisor: 写作完成 → 返回最终答案

七、架构选型指南


八、总结

核心认知

关键 API

// 一行代码创建 Supervisorconstworkflow=createSupervisor({agents:[agent1,agent2,agent3],llm:model,prompt:"调度规则...",outputMode:"last_message",// 或 "full_history"});// 编译运行constapp=workflow.compile();constresult=awaitapp.invoke({messages:[...]});

参考

  • LangGraph Multi-Agent Systems
  • @langchain/langgraph-supervisor
  • Agent Supervisor Tutorial
http://www.jsqmd.com/news/794193/

相关文章:

  • ACS运动控制器XSEG功能深度解析:如何用LINE和ARC1/ARC2玩转复杂轨迹规划?
  • 保姆级教程:给Slurm 20.02.3集群添加GTX1080Ti GPU节点(含防火墙和SELinux配置)
  • 基于Laravel与Livewire构建自托管短链接服务:从生成、追踪到部署
  • 免费解锁B站4K大会员视频:Python开源下载工具完全指南
  • 从 API 响应延迟看 Taotoken 路由稳定性对开发体验的影响
  • AI原生编辑器IfAI:从代码补全到智能体协作的编程革命
  • Gemini 创意生成:从关键词到主题大纲再到可用草稿的链路
  • 深度揭秘:WeChatExporter如何实现iOS微信聊天记录的无损导出与可视化?
  • 大模型上下文 Token 极致优化:Context-Mode 项目核心省 Token 方法论全解析
  • FPGA高生产力设计:从RTL到C语言的演进与实践
  • 什么是置信区间,这是我听过最透彻的工程学解释
  • 7、K8S-daemonset控制器
  • 保持画布比例的艺术:使用ResizeObserver实现自适应布局
  • 自动化测试系统部署:挑战与最佳实践
  • 边缘计算中的3D占据映射技术与Gleanmer SoC优化
  • 实战指南:在QGIS Python控制台里直接装scikit-image,为遥感图像分析加装利器
  • 告别JNLP错误:新版Java环境下安全访问IPMI控制台的终极配置指南
  • docx文档的本质
  • 40nm芯片设计实战:搞定SRAM宏模块的电源布线,避开M4层这个“禁区”
  • 为什么92%的AIAgent在高并发下静默失败?SITS2026容错模型的4层防御体系,立即落地
  • 嵌入式实时系统开发的25个致命错误与优化实践
  • 2026年福建艺考生必知的艺考文化课培训选择要点
  • 保姆级教程:手把手教你用STM32CubeMX+MDK5搞定STM32F429第一个工程
  • 指标漂移、用户冷启动、LLM幻觉干扰——大模型A/B测试三大盲区全解析,SITS大会实证数据支撑
  • ARM TRCCCCTLR寄存器详解与性能分析实践
  • 告别网盘限速:3分钟学会用开源工具解锁高速下载新体验
  • 从REST到RAG-native:AI原生API的4层抽象演进(奇点大会架构委员会首次公开技术栈树)
  • 论医院HIS收费诊间支付的优劣
  • PCIe接口与EDSFF存储形态的协同优化实践
  • 盒子模型这么有趣,确定不来看看吗?