news 2026/5/11 6:47:03

LangGraph 多 Agent 架构与 Supervisor 模式

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/11 6:46:28

【人工智能】-AI行业新风口:FDE成为AI落地企业的关键枢纽

当前AI行业正经历一场深刻的方向性转变,一个显著的趋势已经清晰浮现:AI的商业价值核心,已从模型本身的能力,转向其能否真正融入企业的实际工作流程(workflow)。一个原本仅在Palantir内部广泛应用的经典岗位…

作者头像 李华
网站建设 2026/5/11 6:45:23

保持画布比例的艺术:使用ResizeObserver实现自适应布局

引言 在现代网页设计中,响应式布局是确保用户体验一致性的关键。特别是在游戏开发或数据可视化应用中,保持画布的比例对于用户体验至关重要。本文将探讨如何使用ResizeObserver API 来动态调整画布尺寸,以保持其1:1的纵横比,并解决…

作者头像 李华
网站建设 2026/5/11 6:41:41

告别插件依赖:HEC-RAS 5.0+内置GIS工具实战入门,比HEC-GeoRAS更香?

HEC-RAS 5.0内置GIS工具全解析:彻底告别插件依赖的技术革命 在水利工程与水文建模领域,HEC-RAS长期作为行业标准软件存在,但其传统工作流程中最大的痛点莫过于对ArcGIS和HEC-GeoRAS插件的重度依赖。这种依赖不仅带来高昂的软件许可成本&#…

作者头像 李华
网站建设 2026/5/11 6:34:52

arduino-跑马灯

#define LEDNUM 8 const int LedPin[LEDNUM]{1,2,3,4,5,6,7,8};void setup() {// put your setup code here, to run once:for(int i0;i<LEDNUM;i) {pinMode(LedPin[i], OUTPUT);//设置数字接口为输出模式 } }void loop() {// put your main code here, to run repeatedly: …

作者头像 李华