微软AutoGen高级功能——Swarm
介绍
大家好,博主又来给大家分享知识了,这次给大家分享的内容是微软AutoGen框架的高级功能Swarm。Swarm直译为“群体”,但是在AutoGen框架中我们会称它为“集群智能体” 或 “智能体群”。那么它是用来做什么的或它又是什么功能呢,我们直接进入正题。
Swarm
Swarm实现了一种团队模式,在这种模式下,智能体可以根据自身的能力将任务移交给其他智能体。这是一种由OpenAI在“集群智能体(Swarm)” 概念中首次提出的多智能体设计模式。其关键理念是让智能体通过调用一种特殊的工具,将任务委托给其他智能体,同时所有智能体共享相同的消息上下文。这使得智能体能够就任务规划做出局部决策,而无需像在 “选择器群聊(SelectorGroupChat)” 中那样依赖一个中央协调器。
它如何运作
从核心层面来讲,“集群智能体(Swarm)”是一种群聊模式,在其中各个智能体轮流生成回复内容。与“选择器群聊(SelectorGroupChat)”和“循环轮询群聊(RoundRobinGroupChat)” 类似,参与的智能体将各自的回复进行广播,这样所有智能体就共享相同的消息上下文。
与另外两种群聊团队模式不同的是,在每一轮中,发言的智能体是根据上下文中最新的“任务移交消息(HandoffMessage)”来选定的。这自然就要求团队中的每个智能体都能够生成“任务移交消息”,以表明它将任务移交给了其他哪些智能体。
对于“助理智能体(AssistantAgent)”,我们可以设置“handoffs”参数来指定它能够将任务移交给哪些智能体。你可以使用“任务移交(Handoff)”来定制消息内容和任务移交行为。
整个过程可以总结如下:
- 每个智能体都具备生成 “任务移交消息(HandoffMessage)”的能力,以此来表明它可以将任务移交给其他哪些智能体。对于“助理智能体(AssistantAgent)”而言,这意味着要设置 “handoffs”参数。
- 当团队开始处理一项任务时,第一个发言的智能体对该任务进行处理,并就是否移交任务以及移交给谁做出局部决策。
- 当一个智能体生成一条 “任务移交消息” 时,接收任务的智能体将在相同的消息上下文下接手该任务。
- 这个过程会一直持续,直到满足终止条件为止。
博主笔记:"助理智能体(AssistantAgent)”利用模型的工具调用能力来生成任务移交信息。这意味着模型必须支持工具调用。如果模型进行并行工具调用,可能会同时生成多个任务移交信息,这可能会导致意外行为情况。为避免这种情况,我们可以通过配置模型客户端来禁用并行工具调用。对于 “OpenAIChatCompletionClient”和“AzureOpenAIChatCompletionClient”,我们可以在配置中设置parallel_tool_calls=False。
为了加以说明,我将向大家展示两个关于如何使用“集群智能体(Swarm)”的示例:
- 一个有人参与其中进行任务移交的客户支持团队。
- 一个用于内容生成的自主团队。
客户支持示例
该系统通过两个智能体实现了一个航班退票场景:
- 旅行社智能体:处理一般性的旅行事务以及退票协调工作。
- 航班退票智能体:擅长使用"refund_flight(办理航班退票)"工具来处理航班退票事宜。
此外,当智能体将任务移交给"用户"时,我们让用户与这些智能体进行交互。
工作流程
1. 旅行社智能体开启对话并评估用户的请求。
2. 根据该请求:
· 对于与退票相关的任务,旅行社智能体将任务移交给航班退票智能体。
· 对于需要从客户那里获取的信息,任意一个智能体都可以将任务移交给 “用户”。
3.航班退票智能体在适当时会使用 “办理航班退票(refund_flight)” 工具来处理退票事宜。
4.如果某个智能体将任务移交给“用户”,团队的执行将暂停,并等待用户输入回复。
5.当用户提供输入内容时,该内容会作为一条任务移交消息(HandoffMessage)发送回团队。这条消息会被发送给最初请求用户输入的智能体。
6.这个过程会持续进行,直到旅行社智能体判定任务已完成并终止工作流程。
首先,我们先引用“客户支持示例”需要用到的模块。
演示代码
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import HandoffTermination, TextMentionTermination
from autogen_agentchat.messages import HandoffMessage
from autogen_agentchat.teams import Swarm
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
其次,我们实现一个“航班退票”功能。
代码演示
def refund_flight(flight_id: str) -> str:
"""办理航班退票"""
return f"Flight {flight_id} refunded"
再次,我们声明并实例化两个智能体,一个是旅行社智能体,另一个是航班退票智能体。
代码演示
model_client = OpenAIChatCompletionClient(
model="gpt-4o",
# api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,此步骤可选。
)
travel_agent = AssistantAgent(
"travel_agent",
model_client=model_client,
handoffs=["flights_refunder", "user"],
system_message="""You are a travel agent.
The flights_refunder is in charge of refunding flights.
If you need information from the user, you must first send your message, then you can handoff to the user.
Use TERMINATE when the travel planning is complete.""",
)
flights_refunder = AssistantAgent(
"flights_refunder",
model_client=model_client,
handoffs=["travel_agent", "user"],
tools=[refund_flight],
system_message="""You are an agent specialized in refunding flights.
You only need flight reference numbers to refund a flight.
You have the ability to refund a flight using the refund_flight tool.
If you need information from the user, you must first send your message, then you can handoff to the user.
When the transaction is complete, handoff to the travel agent to finalize.""",
)
再次,我定义并实例化一个“终止条件”对象,和本次重点讲解的集群智能体(Swarm)对象。
代码演示
termination = HandoffTermination(target="user") | TextMentionTermination("TERMINATE")
team = Swarm([travel_agent, flights_refunder], termination_condition=termination)
而后,我们实现一个async(异步)方法def run_team_stream(),模拟一个智能体团队与用户之间的交互过程。
代码演示
task = "I need to refund my flight."
async def run_team_stream() -> None:
task_result = await Console(team.run_stream(task=task))
last_message = task_result.messages[-1]
while isinstance(last_message, HandoffMessage) and last_message.target == "user":
user_message = input("User: ")
task_result = await Console(
team.run_stream(task=HandoffMessage(source="user", target=last_message.source, content=user_message))
)
last_message = task_result.messages[-1]
asyncio.run(run_team_stream())
最后,我们展示完整代码并运行看结果。
完整代码
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import HandoffTermination, TextMentionTermination
from autogen_agentchat.messages import HandoffMessage
from autogen_agentchat.teams import Swarm
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
def refund_flight(flight_id: str) -> str:
"""办理航班退票"""
return f"Flight {flight_id} refunded"
model_client = OpenAIChatCompletionClient(
model="gpt-4o",
# api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,此步骤可选。
)
travel_agent = AssistantAgent(
"travel_agent",
model_client=model_client,
handoffs=["flights_refunder", "user"],
system_message="""You are a travel agent.
The flights_refunder is in charge of refunding flights.
If you need information from the user, you must first send your message, then you can handoff to the user.
Use TERMINATE when the travel planning is complete.""",
)
flights_refunder = AssistantAgent(
"flights_refunder",
model_client=model_client,
handoffs=["travel_agent", "user"],
tools=[refund_flight],
system_message="""You are an agent specialized in refunding flights.
You only need flight reference numbers to refund a flight.
You have the ability to refund a flight using the refund_flight tool.
If you need information from the user, you must first send your message, then you can handoff to the user.
When the transaction is complete, handoff to the travel agent to finalize.""",
)
termination = HandoffTermination(target="user") | TextMentionTermination("TERMINATE")
team = Swarm([travel_agent, flights_refunder], termination_condition=termination)
task = "I need to refund my flight."
async def run_team_stream() -> None:
task_result = await Console(team.run_stream(task=task))
last_message = task_result.messages[-1]
while isinstance(last_message, HandoffMessage) and last_message.target == "user":
user_message = input("User: ")
task_result = await Console(
team.run_stream(task=HandoffMessage(source="user", target=last_message.source, content=user_message))
)
last_message = task_result.messages[-1]
asyncio.run(run_team_stream())
运行结果
---------- user ----------
I need to refund my flight.
---------- travel_agent ----------
[FunctionCall(id='call_xq1zDhBa23PE3UH2m97MU13s', arguments='{}', name='transfer_to_flights_refunder')]
---------- travel_agent ----------
[FunctionExecutionResult(content='Transferred to flights_refunder, adopting the role of flights_refunder immediately.', call_id='call_xq1zDhBa23PE3UH2m97MU13s')]
---------- travel_agent ----------
Transferred to flights_refunder, adopting the role of flights_refunder immediately.
---------- flights_refunder ----------
To process your flight refund, I need the flight reference number. Could you please provide that information?
---------- flights_refunder ----------
[FunctionCall(id='call_KIiIbg8aSR62lwehWbokTxYV', arguments='{}', name='transfer_to_user')]
---------- flights_refunder ----------
[FunctionExecutionResult(content='Transferred to user, adopting the role of user immediately.', call_id='call_KIiIbg8aSR62lwehWbokTxYV')]
---------- flights_refunder ----------
Transferred to user, adopting the role of user immediately.
User: Could you please provide me with the flight reference number so I can process the refund for you?
---------- user ----------
Could you please provide me with the flight reference number so I can process the refund for you?
---------- flights_refunder ----------
[FunctionCall(id='call_xq1zDhBa23PE3UH2m97MU13s', arguments='{}', name='transfer_to_user')]
---------- flights_refunder ----------
[FunctionExecutionResult(content='Transferred to user, adopting the role of user immediately.', call_id='call_xq1zDhBa23PE3UH2m97MU13s')]
---------- flights_refunder ----------
Transferred to user, adopting the role of user immediately.
User: Sure, it's 608722
---------- user ----------
Sure, it's 608722
---------- flights_refunder ----------
[FunctionCall(id='call_AerZYe3ZWx7lJjMUDFHrEktq', arguments='{"flight_id":"608722"}', name='refund_flight')]
---------- flights_refunder ----------
[FunctionExecutionResult(content='Flight 608722 refunded', call_id='call_AerZYe3ZWx7lJjMUDFHrEktq')]
---------- flights_refunder ----------
Flight 608722 refunded
---------- flights_refunder ----------
[FunctionCall(id='call_OmxesWvrJSoGsHWwQWTIoBDU', arguments='{}', name='transfer_to_travel_agent')]
---------- flights_refunder ----------
[FunctionExecutionResult(content='Transferred to travel_agent, adopting the role of travel_agent immediately.', call_id='call_OmxesWvrJSoGsHWwQWTIoBDU')]
---------- flights_refunder ----------
Transferred to travel_agent, adopting the role of travel_agent immediately.
---------- travel_agent ----------
Your flight refund has been successfully processed. If you need further assistance with travel plans, feel free to ask. TERMINATE
进程已结束,退出代码为 0
股票研究示例
该系统旨在通过利用四个智能体来执行股票研究任务:
规划者:作为核心协调者,它根据各专业智能体的专长,将特定任务委派给它们。规划者确保每个智能体都能得到高效利用,并监督整个工作流程。
金融分析师:这是一个专业智能体,负责运用诸如获取股票数据(get_stock_data)这类工具来分析财务指标和股票数据。
新闻分析师:该智能体专注于利用获取新闻(get_news)等工具,收集并总结与该股票相关的近期新闻文章。
撰写者:此智能体的任务是将来自股票分析和新闻分析的结果整理成一份连贯的最终报告。
工作流程
- 规划者通过逐步将任务委派给合适的智能体来启动研究流程。
- 每个智能体独立执行其任务,并将自己的工作内容添加到共享的消息线程/历史记录中。所有智能体并非直接将结果返回给规划者,而是都向这个共享消息历史记录中添加内容并从中读取信息。当智能体使用大语言模型(LLM)开展工作时,它们可以访问这个共享消息历史记录,这为其提供了上下文信息,并有助于追踪任务的整体进展情况。
- 一旦某个智能体完成了它的任务,就会将控制权交还给规划者。
- 这个过程会持续进行,直到规划者判定所有必要的任务都已完成,并决定终止工作流程为止。
首先,我们先引用“股票研究示例”需要用到的模块。
代码演示
import asyncio
from typing import Any, Dict, List
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import Swarm
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
其次,我们模拟并实现两个功能,一个是“获取给定股票代码的股市数据”。另一个是"获取关于一家公司的近期新闻报道"。
代码演示
async def get_stock_data(symbol: str) -> Dict[str, Any]:
"""获取给定股票代码的股市数据"""
return {"price": 180.25, "volume": 1000000, "pe_ratio": 65.4, "market_cap": "700B"}
async def get_news(query: str) -> List[Dict[str, str]]:
"""获取关于一家公司的近期新闻报道"""
return [
{
"title": "Tesla Expands Cybertruck Production",
"date": "2024-03-20",
"summary": "Tesla ramps up Cybertruck manufacturing capacity at Gigafactory Texas, aiming to meet strong demand.",
},
{
"title": "Tesla FSD Beta Shows Promise",
"date": "2024-03-19",
"summary": "Latest Full Self-Driving beta demonstrates significant improvements in urban navigation and safety features.",
},
{
"title": "Model Y Dominates Global EV Sales",
"date": "2024-03-18",
"summary": "Tesla's Model Y becomes best-selling electric vehicle worldwide, capturing significant market share.",
},
]
再次,我们声明并实例化四个智能体,一个是规划者智能体,一个是金融分析智能体,还有一个是新闻分析智能体,最后一个是撰写者智能体。
代码演示
model_client = OpenAIChatCompletionClient(
model="gpt-3.5-turbo",
# api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,此步骤可选。
)
planner = AssistantAgent(
"planner",
model_client=model_client,
handoffs=["financial_analyst", "news_analyst", "writer"],
system_message="""You are a research planning coordinator.
Coordinate market research by delegating to specialized agents:
- Financial Analyst: For stock data analysis
- News Analyst: For news gathering and analysis
- Writer: For compiling final report
Always send your plan first, then handoff to appropriate agent.
Always handoff to a single agent at a time.
Use TERMINATE when research is complete.""",
)
financial_analyst = AssistantAgent(
"financial_analyst",
model_client=model_client,
handoffs=["planner"],
tools=[get_stock_data],
system_message="""You are a financial analyst.
Analyze stock market data using the get_stock_data tool.
Provide insights on financial metrics.
Always handoff back to planner when analysis is complete.""",
)
news_analyst = AssistantAgent(
"news_analyst",
model_client=model_client,
handoffs=["planner"],
tools=[get_news],
system_message="""You are a news analyst.
Gather and analyze relevant news using the get_news tool.
Summarize key market insights from news.
Always handoff back to planner when analysis is complete.""",
)
writer = AssistantAgent(
"writer",
model_client=model_client,
handoffs=["planner"],
system_message="""You are a financial report writer.
Compile research findings into clear, concise reports.
Always handoff back to planner when writing is complete.""",
)
再次,我定义并实例化一个“终止条件”对象,和本次重点讲解的集群智能体(Swarm)对象。
代码演示
# 定义终止条件
text_termination = TextMentionTermination("TERMINATE")
termination = text_termination
research_team = Swarm(
participants=[planner, financial_analyst, news_analyst, writer], termination_condition=termination
)
而后,我们实现一个async(异步)方法run_stream(),运行整个会话。
代码演示
async def run_stream() -> None:
task = "Conduct market research for TSLA stock"
await Console(research_team.run_stream(task=task))
asyncio.run(run_stream())
最后,我们展示完整代码并运行看结果。
完整代码
import asyncio
from typing import Any, Dict, List
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import Swarm
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
async def get_stock_data(symbol: str) -> Dict[str, Any]:
"""获取给定股票代码的股市数据"""
return {"price": 180.25, "volume": 1000000, "pe_ratio": 65.4, "market_cap": "700B"}
async def get_news(query: str) -> List[Dict[str, str]]:
"""获取关于一家公司的近期新闻报道"""
return [
{
"title": "Tesla Expands Cybertruck Production",
"date": "2024-03-20",
"summary": "Tesla ramps up Cybertruck manufacturing capacity at Gigafactory Texas, aiming to meet strong demand.",
},
{
"title": "Tesla FSD Beta Shows Promise",
"date": "2024-03-19",
"summary": "Latest Full Self-Driving beta demonstrates significant improvements in urban navigation and safety features.",
},
{
"title": "Model Y Dominates Global EV Sales",
"date": "2024-03-18",
"summary": "Tesla's Model Y becomes best-selling electric vehicle worldwide, capturing significant market share.",
},
]
model_client = OpenAIChatCompletionClient(
model="gpt-3.5-turbo",
# api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,此步骤可选。
)
planner = AssistantAgent(
"planner",
model_client=model_client,
handoffs=["financial_analyst", "news_analyst", "writer"],
system_message="""You are a research planning coordinator.
Coordinate market research by delegating to specialized agents:
- Financial Analyst: For stock data analysis
- News Analyst: For news gathering and analysis
- Writer: For compiling final report
Always send your plan first, then handoff to appropriate agent.
Always handoff to a single agent at a time.
Use TERMINATE when research is complete.""",
)
financial_analyst = AssistantAgent(
"financial_analyst",
model_client=model_client,
handoffs=["planner"],
tools=[get_stock_data],
system_message="""You are a financial analyst.
Analyze stock market data using the get_stock_data tool.
Provide insights on financial metrics.
Always handoff back to planner when analysis is complete.""",
)
news_analyst = AssistantAgent(
"news_analyst",
model_client=model_client,
handoffs=["planner"],
tools=[get_news],
system_message="""You are a news analyst.
Gather and analyze relevant news using the get_news tool.
Summarize key market insights from news.
Always handoff back to planner when analysis is complete.""",
)
writer = AssistantAgent(
"writer",
model_client=model_client,
handoffs=["planner"],
system_message="""You are a financial report writer.
Compile research findings into clear, concise reports.
Always handoff back to planner when writing is complete.""",
)
# 定义终止条件
text_termination = TextMentionTermination("TERMINATE")
termination = text_termination
research_team = Swarm(
participants=[planner, financial_analyst, news_analyst, writer], termination_condition=termination
)
async def run_stream() -> None:
task = "Conduct market research for TSLA stock"
await Console(research_team.run_stream(task=task))
asyncio.run(run_stream())
运行结果
---------- user ----------
Conduct market research for TSLA stock
---------- planner ----------
[FunctionCall(id='call_BX5QaRuhmB8CxTsBlqCUIXPb', arguments='{}', name='transfer_to_financial_analyst')]
---------- planner ----------
[FunctionExecutionResult(content='Transferred to financial_analyst, adopting the role of financial_analyst immediately.', call_id='call_BX5QaRuhmB8CxTsBlqCUIXPb')]
---------- planner ----------
Transferred to financial_analyst, adopting the role of financial_analyst immediately.
---------- financial_analyst ----------
[FunctionCall(id='call_SAXy1ebtA9mnaZo4ztpD2xHA', arguments='{"symbol":"TSLA"}', name='get_stock_data')]
---------- financial_analyst ----------
[FunctionExecutionResult(content="{'price': 180.25, 'volume': 1000000, 'pe_ratio': 65.4, 'market_cap': '700B'}", call_id='call_SAXy1ebtA9mnaZo4ztpD2xHA')]
---------- financial_analyst ----------
Tool calls:
get_stock_data({"symbol":"TSLA"}) = {'price': 180.25, 'volume': 1000000, 'pe_ratio': 65.4, 'market_cap': '700B'}
---------- financial_analyst ----------
[FunctionCall(id='call_IsdcFUfBVmtcVzfSuwQpeAwl', arguments='{}', name='transfer_to_planner')]
---------- financial_analyst ----------
[FunctionExecutionResult(content='Transferred to planner, adopting the role of planner immediately.', call_id='call_IsdcFUfBVmtcVzfSuwQpeAwl')]
---------- financial_analyst ----------
Transferred to planner, adopting the role of planner immediately.
---------- planner ----------
[FunctionCall(id='call_tN5goNFahrdcSfKnQqT0RONN', arguments='{}', name='transfer_to_news_analyst')]
---------- planner ----------
[FunctionExecutionResult(content='Transferred to news_analyst, adopting the role of news_analyst immediately.', call_id='call_tN5goNFahrdcSfKnQqT0RONN')]
---------- planner ----------
Transferred to news_analyst, adopting the role of news_analyst immediately.
---------- news_analyst ----------
[FunctionCall(id='call_Owjw6ZbiPdJgNWMHWxhCKgsp', arguments='{"query":"Tesla market news"}', name='get_news')]
---------- news_analyst ----------
[FunctionExecutionResult(content='[{\'title\': \'Tesla Expands Cybertruck Production\', \'date\': \'2024-03-20\', \'summary\': \'Tesla ramps up Cybertruck manufacturing capacity at Gigafactory Texas, aiming to meet strong demand.\'}, {\'title\': \'Tesla FSD Beta Shows Promise\', \'date\': \'2024-03-19\', \'summary\': \'Latest Full Self-Driving beta demonstrates significant improvements in urban navigation and safety features.\'}, {\'title\': \'Model Y Dominates Global EV Sales\', \'date\': \'2024-03-18\', \'summary\': "Tesla\'s Model Y becomes best-selling electric vehicle worldwide, capturing significant market share."}]', call_id='call_Owjw6ZbiPdJgNWMHWxhCKgsp')]
---------- news_analyst ----------
Tool calls:
get_news({"query":"Tesla market news"}) = [{'title': 'Tesla Expands Cybertruck Production', 'date': '2024-03-20', 'summary': 'Tesla ramps up Cybertruck manufacturing capacity at Gigafactory Texas, aiming to meet strong demand.'}, {'title': 'Tesla FSD Beta Shows Promise', 'date': '2024-03-19', 'summary': 'Latest Full Self-Driving beta demonstrates significant improvements in urban navigation and safety features.'}, {'title': 'Model Y Dominates Global EV Sales', 'date': '2024-03-18', 'summary': "Tesla's Model Y becomes best-selling electric vehicle worldwide, capturing significant market share."}]
---------- news_analyst ----------
Here are some of the key market insights regarding Tesla (TSLA):
1. **Expansion in Cybertruck Production**: Tesla has increased its Cybertruck production capacity at the Gigafactory in Texas to meet the high demand. This move might positively impact Tesla's revenues if the demand for the Cybertruck continues to grow.
2. **Advancements in Full Self-Driving (FSD) Technology**: The recent beta release of Tesla's Full Self-Driving software shows significant advancements, particularly in urban navigation and safety. Progress in this area could enhance Tesla's competitive edge in the autonomous driving sector.
3. **Dominance of Model Y in EV Sales**: Tesla's Model Y has become the best-selling electric vehicle globally, capturing a substantial market share. Such strong sales performance reinforces Tesla's leadership in the electric vehicle market.
These developments reflect Tesla's ongoing innovation and ability to capture market demand, which could positively influence its stock performance and market position.
I will now hand off back to the planner.
---------- news_analyst ----------
[FunctionCall(id='call_pn7y6PKsBspWA17uOh3AKNMT', arguments='{}', name='transfer_to_planner')]
---------- news_analyst ----------
[FunctionExecutionResult(content='Transferred to planner, adopting the role of planner immediately.', call_id='call_pn7y6PKsBspWA17uOh3AKNMT')]
---------- news_analyst ----------
Transferred to planner, adopting the role of planner immediately.
---------- planner ----------
[FunctionCall(id='call_MmXyWuD2uJT64ZdVI5NfhYdX', arguments='{}', name='transfer_to_writer')]
---------- planner ----------
[FunctionExecutionResult(content='Transferred to writer, adopting the role of writer immediately.', call_id='call_MmXyWuD2uJT64ZdVI5NfhYdX')]
---------- planner ----------
Transferred to writer, adopting the role of writer immediately.
---------- writer ----------
[FunctionCall(id='call_Pdgu39O6GMYplBiB8jp3uyN3', arguments='{}', name='transfer_to_planner')]
---------- writer ----------
[FunctionExecutionResult(content='Transferred to planner, adopting the role of planner immediately.', call_id='call_Pdgu39O6GMYplBiB8jp3uyN3')]
---------- writer ----------
Transferred to planner, adopting the role of planner immediately.
---------- planner ----------
TERMINATE
进程已结束,退出代码为 0
说明
如果大家在运行上述代码的时候有AutoGen相关的提示或报错(例如:该参数不存在,没有此类方法等),请尝试更新一下AutoGen,博主在分享这篇博文的时候,AutoGen的版本是0.4.6稳定版。
安装或更新命令
pip install -U "autogen-agentchat" "autogen-ext[openai,azure]"
另外大家要根据业务需求,设置使用的LLM,不一定要按照我给大家分享代码中的设置来,如果只是为了测试并看运行结果可直接复制粘贴代码(完整代码)。
结束
好了,以上就是本次分享的全部内容,不知道大家有没有Get到Swarm的原理及使用方式。为了不让大家再往上翻,博主帮助大家再次整理下今天分享的内容。
Swarm是微软AutoGen框架中一种多智能体设计模式。具体来说,它有以下内容:
定义与原理:Swarm实现了一个智能体团队,其中的智能体可以根据自身能力将任务交给其他智能体。其核心是一个群聊模式,智能体轮流生成响应,类似于选择器群聊和轮询群聊,参与的智能体广播他们的响应,以便所有智能体共享相同的消息上下文。不同的是,在 Swarm 中,每个轮次的发言智能体是根据上下文中最近的交接消息来选择的,这就要求团队中的每个智能体都能够生成交接消息,以表明它要将任务交给哪个其他智能体。
使用方式
- 智能体设置:对于 AssistantAgent,可以设置 handoffs 参数来指定它可以交接给哪些智能体,还可以使用 handoff 来定制消息内容和交接行为。
- 运行流程:当团队开始一项任务时,第一个发言智能体对任务进行操作,并就是否交接以及交给谁做出局部决策。当一个智能体生成一个交接消息时,接收智能体将在相同的消息上下文中接管任务,这个过程会持续进行,直到满足终止条件。
应用示例
- 客户支持场景:例如在航班退款场景中,有负责一般旅行和退款协调的旅行代理,以及专门处理航班退款的航班退款代理,还允许用户与智能体交互。旅行代理发起对话并评估用户请求,与退款相关的任务交给航班退款代理,需要客户提供信息时,任一智能体都可以将任务交给 “用户”。
- 内容生成场景:可以组建一个自主团队,让不同智能体发挥各自专长,在内容生成的不同环节进行协作,通过任务交接共同完成内容生成任务。
我相信大家看到这里还是会有些疑惑,那么Swarm与RoundRobinGroupChat和SelectorGroupChat的区别是什么,Swarm应用在什么场景下?如果大家能想到这些,说明大家已经认真看过并思考过本次分享的内容了,为了帮助大家学到实际应用上的的东西,博主再次帮大家整理。内容如下:
发言智能体选择机制
- Swarm:每个轮次的发言智能体是根据上下文中最近的交接消息来选择,要求团队中的每个智能体都能够生成交接消息,以表明它要将任务交给哪个其他智能体。
- RoundRobinGroupChat:按照预先确定的顺序,以循环的方式依次选择智能体发言,如智能体 A、B、C,会按照 A→B→C→A→B→C 这样的顺序轮流发言。
- SelectorGroupChat:通过生成式模型(如 LLM)基于共享的上下文来选择下一个发言的智能体,可根据对话历史、参与者的名称和描述等属性,分析确定最适合处理当前任务的智能体。
任务交接方式
- Swarm:智能体完成任务后,通过生成交接消息明确指定将任务交接给下一个智能体,接收智能体在相同消息上下文中接管任务。
- RoundRobinGroupChat:不存在特定的任务交接消息,只是按照固定顺序轮到哪个智能体,哪个智能体就开始执行任务和发言。
- SelectorGroupChat:没有明确的任务交接概念,只是由模型根据上下文选择下一个发言智能体,智能体根据当前对话状态和自身职责进行回应。
对智能体(Agent)的要求
- Swarm:要求每个智能体都具备生成交接消息的能力,以便实现任务在智能体之间的传递。
- RoundRobinGroupChat:智能体只需按照顺序进行发言和执行任务,不需要特别的任务交接或选择机制相关的能力。
- SelectorGroupChat:智能体需要有能够被模型根据上下文进行选择的相关属性和能力,比如有明确的名称、描述等,以便模型判断其是否适合处理当前任务。
应用场景
- Swarm:适用于任务需要在不同智能体之间进行灵活、明确交接的场景,如多阶段、多角色协作的复杂任务,像大型项目的不同模块开发,不同智能体负责不同模块,完成一个模块后交接给下一个模块的智能体。
- RoundRobinGroupChat:适用于对智能体发言顺序有固定要求,且任务相对简单、不需要根据复杂上下文动态选择智能体的场景,如简单的信息收集或轮询式的问答场景。
- SelectorGroupChat:适用于任务复杂,需要根据对话历史和上下文动态确定由哪个智能体来处理任务的场景,如智能客服系统中,根据用户咨询的问题内容,动态选择合适的专业客服智能体来回答。
好了,看到这里我相信大家对本次分享的内容有很深刻的理解了。博主还是那句话,请大家多去大胆的尝试和使用。成功总是在不断的错误中试验出来的,敢于尝试就已经成功了一半,哈哈。这次分享就到这,如果大家对博主分享的内容感兴趣或有帮助,请点赞和关注,大家的点赞和关注是博主持续分享的动力🤭,博主也希望让更多的人学习到新的知识。