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

【由浅入深探究langchain】第二十二集-多智能体Supervisor Agent(下)

前情提要

在上一集中,我们亲手打造了日历专家Calendar Agent和邮件专家Email Agent。但现实场景往往更复杂,比如:“帮我定个周一的会,然后发邮件通知大家。”

面对这种跨领域的复合任务,我们需要一个“大脑”来统筹全局。这就是我们今天要聊的 Supervisor Agent(主管智能体)。

一、 核心逻辑:Agent 嵌套

下集最硬核的知识点在于:把 Agent 包装

在 LangChain 1.0 中,supervisor_agent并不直接与底层的数据库或 API 交互,它的“工具箱”里装的是其他的 Agent。

  • 上集:Agent 1 $\rightarrow$ 调用Python Function

  • 下集:Supervisor $\rightarrow$ 调用Agent Tool$\rightarrow$ 执行Agent 1

成 Tool。

这种层级结构(Layered Architecture)极大地降低了单个 Agent 的 Prompt 复杂度,提高了稳定性。

二、完整代码

supervisor_agent.py

from langchain_openai import ChatOpenAI kimi_model = ChatOpenAI( model="kimi-k2.5", api_key="sk-uQp***", base_url="https://api.moonshot.cn/v1", # 重点:这里严格对应 Kimi 的 API 结构 extra_body={ "thinking": {"type": "disabled"} } ) from langchain_core.tools import tool from langchain.agents import create_agent SUPERVISOR_PROMPT=( "You are a helpful personal assistant." "You can schedule calendar events and send emails." "Break down user requests into appropriate tool calls and coordinate the results." "When a request involves multiple actions, use multiple tools in sequence." ) from calendar_agent import calander_agent from email_agent import email_agent @tool def schedule_event(request: str) -> str: """Schedule calendar events using natural language. Use this when the user wants to create, modify, or check calendar appointments. Handles date/time parsing, availability checking, and event creation. Input: Natural language scheduling request (e.g., 'meeting with design team next Tuesadt at 2pm') """ result = calander_agent.invoke({ "messages":[{"role":"user","content":request}] }) return result["messages"][-1].text @tool def manage_email(request: str) -> str: """Send emails using natural language. Use this when the user wants to send notifications, reminders, or any emailcommunication. Handles recipient extraction, subject generation, and email composition. Input: Natural language email request (e.g., 'send them a reminder about the meeting') """ result = email_agent.invoke({ "messages":[{"role":"user","content":request}] }) return result["messages"][-1].text supervisor_agent = create_agent( model=kimi_model, system_prompt=SUPERVISOR_PROMPT, tools=[schedule_event,manage_email] ) def test_supervisor_agent(): query = "hello" for event in supervisor_agent.stream( {"messages":{"role":"user","content":query}}, stream_mode="values" ): event["messages"][-1].pretty_print() query = "Schedule a team meeting ['aaa@abc.com'] on 2026-03-30 at 2pm, 1hour,then send email to notify the team." for event in supervisor_agent.stream( {"messages":{"role":"user","content":query}}, stream_mode="values" ): event["messages"][-1].pretty_print() test_supervisor_agent()
三、 代码详解:构建调度中心
1. 导入“组件化”的Agent

我们直接导入上集写好的calander_agentemail_agent。在大型项目中,这种模块化导入让代码非常整洁。

from calendar_agent import calander_agent from email_agent import email_agent
2. 将 Agent 封装为工具

我们定义了两个新工具:schedule_eventmanage_email

目的:

  • 黑盒化:Supervisor 不需要知道怎么解析日期,它只需要把用户的原始需求(request)丢给schedule_event工具。

  • 状态隔离:子 Agent 的中间思考过程(Thinking)会被封装在工具内部,Supervisor 只能看到最终执行结果,防止上下文干扰。

@tool def schedule_event(request: str) -> str: """Schedule calendar events using natural language. Use this when the user wants to create, modify, or check calendar appointments. Handles date/time parsing, availability checking, and event creation. Input: Natural language scheduling request (e.g., 'meeting with design team next Tuesadt at 2pm') """ result = calander_agent.invoke({ "messages":[{"role":"user","content":request}] }) return result["messages"][-1].text @tool def manage_email(request: str) -> str: """Send emails using natural language. Use this when the user wants to send notifications, reminders, or any emailcommunication. Handles recipient extraction, subject generation, and email composition. Input: Natural language email request (e.g., 'send them a reminder about the meeting') """ result = email_agent.invoke({ "messages":[{"role":"user","content":request}] }) return result["messages"][-1].text
3.定义主管:Supervisor 的职责(prompt)
SUPERVISOR_PROMPT = ( "You are a helpful personal assistant." "Break down user requests into appropriate tool calls..." )
4.构建agent
supervisor_agent = create_agent( model=kimi_model, system_prompt=SUPERVISOR_PROMPT, tools=[schedule_event,manage_email] )
5.测试

我们让它"Schedule a team meeting ... then send email to notify the team."

理论上Supervisor 的执行流转如下:

识别任务 A:发现需要“订会议”,调用schedule_event工具。

触发子 Agent:calander_agent介入,调用它自己的工具完成任务,并返回“Event created...”。

识别任务 B:Supervisor 收到 A 完成的消息后,发现还需要“发邮件”,于是调用manage_email

触发子 Agent:email_agent介入,完成发送任务。

总结:Supervisor 汇总两次工具调用的结果,给用户最终反馈。

def test_supervisor_agent(): query = "hello" for event in supervisor_agent.stream( {"messages":{"role":"user","content":query}}, stream_mode="values" ): event["messages"][-1].pretty_print() query = "Schedule a team meeting ['aaa@abc.com'] on 2026-03-30 at 2pm, 1hour,then send email to notify the team." for event in supervisor_agent.stream( {"messages":{"role":"user","content":query}}, stream_mode="values" ): event["messages"][-1].pretty_print() test_supervisor_agent()
四、结果详解

当输入:“订个会,然后发邮件通知”时,我们可以看到 Supervisor 并没有直接输出文字,而是立刻生成了两个 Tool Calls:

schedule_event (Args: Schedule a team meeting...)

manage_email (Args: Send email to aaa@abc.com...)

打印中可以看到:

  • Calendar工具被调用。

  • send_email工具随后被调用。

这两个print语句是在两个work agents中的。模型通过一次响应(Response)输出了两个工具调用指令。这种“全能主管”的表现,极大提升了执行效率。

最终AI将结果重新格式化成了人类友好的报告,这种将“底层执行结果”转化为“高层业务总结”的能力,正是 LangChain 1.0 架构下多智能体的核心价值所在。

总结

通过这两集的学习,我们从 0 到 1 搭建了一个可以感知、思考、并驱动多个专家协作的 Personal Assistant。

  • 上集:我们学会了如何给“手脚”(Worker Agents)安装工具。

  • 下集:我们学会了如何给系统安装“大脑”(Supervisor)。

核心感悟: 在 AI 开发的新范式下,编写代码不再是编写逻辑,而是编写“契约”。你定义好 Agent 之间的边界和接口文档(Docstrings),剩下的协作逻辑,交给 LLM 去推理。

http://www.jsqmd.com/news/565704/

相关文章:

  • 突破语音转文字依赖瓶颈:AnythingLLM如何实现全本地化音频处理
  • 2026年度核工业工程咨询公司加盟推荐,北京中京天元口碑出众 - mypinpai
  • 伊利诺伊大学首次让AI学会把3D物体像积木一样拆分重组
  • 图像处理和深度学习笔记[特殊字符](一)
  • 南京高端腕表维修推荐:2026年六城17家认证中心维修大数据与品牌故障全解析 - 时光修表匠
  • Windows文件系统开发的革命性突破:WinFsp技术原理与实战指南
  • YimMenu安全增强指南:GTA5免费辅助工具的高效配置与实战应用
  • BYD蓝牙IOT网关——GATT服务发现流程优化
  • 5分钟掌握同星LIN主从节点仿真实战技巧(附TSMaster操作指南)
  • 2026年华北地区热门工程咨询公司排名,推荐煤炭工程咨询分公司 - 工业设备
  • Reachy Mini开源桌面机器人:从零开始构建智能交互伙伴的完整指南
  • VideoDownloadHelper:智能解析驱动的高效视频资源管理解决方案
  • 三维建模助力刑侦:2026 刑侦现场精准还原软件品牌哪家好? - 品牌2026
  • Zotero元数据格式化插件:架构解析与实战方案
  • 模型服务化实战:将DAMOYOLO-S封装为ChatGPT式的智能Agent
  • 企业级人脸识别系统设计:Retinaface+CurricularFace高可用架构
  • 2026年国标钢丸厂家推荐:合金铸钢丸/合金钢丸/钢丸钢砂专业供应 - 品牌推荐官
  • 别再手动查了!用Python+Requests 5分钟搞定12306时刻表数据抓取
  • Oni-Duplicity:3分钟掌握《缺氧》存档编辑,告别资源焦虑
  • 直击制造业六大核心痛点,MES解决方案全解析
  • Argos Translate:如何为你的应用构建企业级离线翻译能力?
  • 【实战指南】Docker中PostgreSQL数据库的备份与恢复全流程解析
  • Qwen3-Coder-30B-A3B-Instruct:面向企业级代码工程的混合专家架构实践
  • 2026年恒压变频供水设备选购指南:A品牌与B品牌深度对比与决策分析 - 速递信息
  • 2026永州找GEO推广服务怕被坑?湖南企拓官方电话与避坑指南 - 精选优质企业推荐榜
  • 如何快速掌握Markdown预览:终极浏览器插件使用教程
  • X11桌面自动化实战指南:用xdotool提升Linux工作效率的终极解决方案
  • Windows 10/11下用StyleGAN2-ADA-PyTorch训练自己的数据集(避坑Visual Studio编译错误)
  • 告别混乱!「秒云Tokens管家」一个API Key搞定所有大模型!
  • 全球燃料电池堆:高增27.8%,2032年剑指401.5亿