AutoGen 多智能体实战:订单 + 物流查询案例
本文介绍了一个基于AutoGen框架的多智能体协作系统,用于实现订单和物流查询业务场景。系统包含四个核心组件:UserProxyAgent作为用户代理执行工具调用,三个AssistantAgent分别负责订单查询、物流查询和结果汇总,GroupChatManager协调智能体间的协作流程。通过注册工具函数和配置群组聊天规则,系统实现了"用户发起→订单查询→物流查询→结果汇总"的
·
1. 案例组件使用情况总结
| 组件名称 | 对应代码位置 | 备注 |
|---|---|---|
| UserProxyAgent | self.user_proxy | 用户代理 / 用户替身。它是系统的 “手脚”,负责发起任务、真实执行工具调用,并接收工具返回结果。 |
| AssistantAgent | self.order_agent 、logistics_agent、summary_agent | 业务智能体 / 大脑。定义了 3 个核心角色:1. 订单专员:调用订单查询工具;2. 物流专员:调用物流查询工具;3. 客服主管(汇总智能体):汇总结果生成最终回复 |
| GroupChat | self.groupchat | 智能体容器 / 会议室。存储所有参与的智能体列表,同时维护对话历史上下文,保证多智能体能在同一语境下协作。 |
| GroupChatManager | self.manager | 流程调度器 / 会议主持人。负责发言顺序、驱动流程运转,会依据对话上下文智能决定下一位发言人。控制对话轮次,防止流程卡死。 |
| initiate_chat() | self.user_proxy.initiate_chat | 对话启动入口。由 UserProxyAgent 调用,作为整个多智能体流程的启动按钮,下达任务指令。 |
整体流程:
启动脚本
↓
UserProxyAgent(用户代理,发起任务)
↓
GroupChatManager(会议主持人,调度群组对话)
↓
GroupChat(会议室)
↓
AssistantAgent(智能体分工思考 → 决定调用工具)
↓
UserProxyAgent(真正执行调用工具)
↓
结果返回 → 汇总 → 输出最终回复
2. AutoGen完整案例
"""
AutoGen 多智能体案例:订单 + 物流查询
核心流程:用户发起查询 → 订单智能体 → 物流智能体 → 主管汇总 → 输出结果
"""
import autogen
from autogen.agentchat import register_function
# ====================== LLM 模型配置 ======================
LLM_CONFIG = {
"config_list": [
{
"model": "your-model-name", # 大模型名称
"api_key": "your-api-key", # API密钥
"base_url": "your-base-url", # 接口地址
}
],
"temperature": 0.1,
}
# ====================== 业务工具类(模拟接口) ======================
class OrderTools:
"""订单查询工具"""
_order_db = {"ORD001": {"status": "待发货", "amount": 199}}
def get_order_info(self, order_id):
info = self._order_db.get(order_id)
if info is None:
return f"订单{order_id}不存在"
return f"订单{order_id}:状态={info['status']},金额={info['amount']}元"
class LogisticsTools:
"""物流查询工具"""
_logistics_db = {"ORD001": {"status": "揽收完成", "carrier": "顺丰"}}
def get_logistics_info(self, order_id):
info = self._logistics_db.get(order_id)
if info is None:
return f"物流信息{order_id}不存在"
return f"物流{order_id}:状态={info['status']},承运商={info['carrier']}"
# ====================== AutoGen 多智能体核心类 ======================
class AutoGenOrderAgent:
def __init__(self):
# ------------------------------------------------------
""" 【用户代理】user_proxy 组件:人类替身,负责发起任务、执行工具、终止对话 """
# ------------------------------------------------------
self.user_proxy = autogen.UserProxyAgent(
name="用户代理", # 智能体名称
human_input_mode="NEVER", # 全自动执行,无需人工输入
max_consecutive_auto_reply=5, # 最大连续自动回复次数
is_termination_msg=lambda x: any( # 明确的终止标志,只要含 "问题已解决"..字样。
kw in x.get("content", "")
for kw in ["问题已解决", "结束", "完成"]
),
code_execution_config={"use_docker": False}, # 关闭Docker,避免报错
)
# ------------------------------------------------------
""" 【助手智能体】AssistantAgent 组件:分工处理订单/物流/汇总任务 """
# ------------------------------------------------------
# 订单查询智能体
self.order_agent = autogen.AssistantAgent(
name="订单专员",
system_message="你负责调用订单查询工具,返回订单信息",
llm_config=LLM_CONFIG,
)
# 物流查询智能体
self.logistics_agent = autogen.AssistantAgent(
name="物流专员",
system_message="你负责调用物流查询工具,返回物流信息",
llm_config=LLM_CONFIG,
)
# 汇总智能体
self.summary_agent = autogen.AssistantAgent(
name="客服主管",
system_message="汇总订单和物流信息,生成友好的最终回复。回复末尾必须包含问题已解决、结束、完成", # 必须告知“终止字符”,否则多智能体会无限对话,直到触达 max_turns/max_round 硬性截断,浪费 token 且答案可能不完整
llm_config=LLM_CONFIG,
)
# ------------------------------------------------------
""" 【工具注册】:绑定智能体与业务工具函数 """
# ------------------------------------------------------
# 在 __init__ 中一次性创建工具实例,避免重复创建
self.order_tools = OrderTools()
self.logistics_tools = LogisticsTools()
# 包装工具函数
def get_order_info(order_id: str) -> str:
return self.order_tools.get_order_info(order_id)
def get_logistics_info(order_id: str) -> str:
return self.logistics_tools.get_logistics_info(order_id)
# 使用 register_function 将工具函数同时注册到调用者和执行者
register_function(
get_order_info, # 工具函数
caller=self.order_agent, # 调用者:订单智能体
executor=self.user_proxy, # 执行者:用户代理
description="根据订单ID查询订单信息", # 工具描述
)
register_function(
get_logistics_info, # 工具函数
caller=self.logistics_agent, # 调用者:物流智能体
executor=self.user_proxy, # 执行者:用户代理
description="根据订单ID查询物流信息", # 工具描述
)
# ------------------------------------------------------
""" 【群组聊天】GroupChat 组件:定义参与智能体 + 协作规则 """
# ------------------------------------------------------
self.groupchat = autogen.GroupChat(
agents=[
self.order_agent, # 订单查询智能体
self.logistics_agent, # 物流查询智能体
self.summary_agent, # 汇总智能体
self.user_proxy, # 用户代理(执行工具)
],
messages=[], # 对话历史(初始为空)
max_round=10, # 最大对话轮次
speaker_selection_method="auto", # 自动选择下一个发言人
allow_repeat_speaker=True, # 允许同一智能体连续发言(避免流程卡死)
)
# ------------------------------------------------------
""" 【聊天管理器】GroupChatManager 组件:控制多智能体发言顺序 """
# ------------------------------------------------------
self.manager = autogen.GroupChatManager(
groupchat=self.groupchat, # 绑定群组
llm_config=LLM_CONFIG, # 绑定大模型配置
)
# 执行查询任务
def run(self, order_id="ORD001"):
# ------------------------------------------------------
""" 【启动多智能体对话】 user_proxy.initiate_chat """
# ------------------------------------------------------
# 任务指令
task_msg = f"请查询订单{order_id},先查订单、再查物流,最后客服主管汇总回复"
chat_result = self.user_proxy.initiate_chat(
recipient=self.manager, # 接收方:群组管理器
message=task_msg, # 任务指令
max_turns=10, # 最大对话轮次
summary_method="last_msg", # 指定 summary 取最后一条消息(一般最后一条消息就是汇总的最终结果,也可以按照官方推荐的获取最终结果写法)
)
# 返回最终汇总结果
return chat_result
# ====================== 启动运行 ======================
if __name__ == "__main__":
result = AutoGenOrderAgent().run(order_id="ORD001")
# 打印最终结果
print("\n" + "="*50)
print("📌 会话ID,方便以后做日志追踪、查历史:")
print(result.chat_id)
print("📌 智能体汇总回复:")
print(result.summary)
print("="*50)
更多推荐

所有评论(0)