AutoGen(四) team多智能体团队实战:团队创建、运行、终止与高级用法全解析(附代码)
本文全面解析AutoGen多智能体团队(Team)的核心机制与应用。通过对比单Agent模式,重点介绍了团队协作在代码评审、智能问答等复杂场景的优势。详细讲解了团队创建流程(包括主Agent和评论Agent设置)、基于RoundRobinGroupChat的轮询机制、反思模式提升输出质量的原理。提供多个实战代码示例,涵盖基础团队运作、流式消息观察、内外终止控制等高级用法。特别建议使用GPT-4o模
AutoGen team多智能体团队实战:团队创建、运行、终止与高级用法全解析(附代码)
为什么要用多智能体团队?
在大模型(LLM)应用开发中,单一Agent往往难以胜任复杂任务,比如自动化代码评审、智能问答、复杂决策等。AutoGen的多智能体团队(Team)机制,让多个Agent协作变得高效、灵活且可控。本文将带你一文掌握AutoGen Team的核心机制、典型场景、实战代码与高级用法,助你玩转多智能体协作!
1. AutoGen Team核心概念与机制
- 团队(Team):由多个Agent组成,协作完成复杂任务。
- RoundRobinGroupChat:团队成员按顺序轮流响应,所有成员共享上下文,保证信息一致。
- 反思模式(Reflection Pattern):主Agent负责产出,评论Agent负责反馈和把关,提升输出质量。利用团队的某一成员的反馈,让输出结果更优秀
- 与单Agent区别:团队支持多轮协作、分工、互评,适合复杂场景。
2. 典型应用场景
- 代码生成与自动调试
- 多Agent反思与评审
- 智能问答/知识检索团队
- 动态决策与博弈(如国际象棋AI团队)
3. 快速上手:团队的创建与运行
环境准备
建议使用 gpt-4o 模型进行实验,因其支持标准的工具调用流程(如OpenAI平台)。本地 ollama 模型虽然也可用,但工具调用过程仅以参数形式输出,缺乏真实的"工具调用"事件流,体验不如gpt-4o直观。
代码示例1:最小团队创建与运行
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_ext.models.ollama import OllamaChatCompletionClient
# 推荐:如用gpt-4o请替换为对应的OpenAI模型client
model_client = OllamaChatCompletionClient(
model="qwen2.5-coder:latest",
model_info={
"vision": False,
"function_calling": True,
"json_output": False,
"structured_output": True,
}
)
# 创建主Agent和评论Agent
primary_agent = AssistantAgent(
"primary",
model_client=model_client, # 推荐gpt-4o模型
system_message="你是一个优秀的AI助手"
)
critic_agent = AssistantAgent(
"critic",
model_client=model_client, # 推荐gpt-4o模型
#system_message="你只提供建设性反馈,反馈被采纳后回复"APPROVE"。"
#鉴于模型的不同,对qwen2.5-coder:latest的提示词应该更丰富一些
system_message="你只提供两个能力,1.对内容提供建设性反馈.2.当你的反馈得到处理时,回复"APPROVE",如果对方没有按照你的反馈进行修改就不回复"APPROVE""
)
# 设置终止条件:当评论Agent回复"APPROVE"时终止
termination = TextMentionTermination("APPROVE")
# 创建团队
team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=termination)
# 运行团队
result = await team.run(task="写一首关于秋季的短诗。")
print(result)
source='user' models_usage=None metadata={} content='写一首关于秋季的短诗.' type='TextMessage'
source='primary' models_usage=RequestUsage(prompt_tokens=26, completion_tokens=29) metadata={} content='秋风瑟瑟落黄叶,满地金黄一片片。\n天高云淡景宜人,菊花绽放香气浓。' type='TextMessage'
source='critic' models_usage=RequestUsage(prompt_tokens=100, completion_tokens=78) metadata={} content='这首诗描绘了秋天的美好景象,用词贴切,意境深远。不过,可以稍微调整一下句子的节奏和流畅度,使其更加和谐。\n\n秋风瑟瑟落黄叶,\n满地金黄一片片。\n天高云淡景宜人,\n菊花绽放香气浓。\n\n这样修改后,诗的节奏更流畅,读起来也更有韵味。' type='TextMessage'
source='primary' models_usage=RequestUsage(prompt_tokens=141, completion_tokens=63) metadata={} content='你的建议非常有道理!以下是经过调整后的诗歌:\n\n秋风瑟瑟落黄叶, \n满地金黄一片片。 \n天高云淡景宜人, \n菊花绽放香飘远。\n\n这样修改后,诗的节奏更加和谐流畅,读起来也更有韵味了。' type='TextMessage'
source='critic' models_usage=RequestUsage(prompt_tokens=249, completion_tokens=4) metadata={} content='APPROVE' type='TextMessage'
Stop Reason: Text 'APPROVE' mentioned
4. 团队消息流与观察
AutoGen支持流式输出团队消息,便于实时观察团队协作过程。
代码示例2:流式输出团队对话
# 先创建 model_client
model_client = OllamaChatCompletionClient(
model="qwen2.5-coder:latest",
model_info={
"vision": False,
"function_calling": True,
"json_output": False,
"structured_output": True,
}
)
primary_agent = AssistantAgent(
"primary",
model_client=model_client,
system_message="你是一个优秀的AI助手"
)
critic_agent = AssistantAgent(
"critic",
model_client=model_client,
system_message="你只提供两个能力,1.对内容提供建设性反馈.2.当你的反馈得到处理时,回复"APPROVE",如果对方没有按照你的反馈进行修改就不回复"APPROVE""
)
termination = TextMentionTermination("APPROVE")
team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=termination)
await team.reset() # 重置团队
async for message in team.run_stream(task="写一首关于秋季的短诗。"):
print(message)
你也可以用 Console 进行格式化输出:
from autogen_agentchat.ui import Console
await team.reset()
await Console(team.run_stream(task="写一首关于秋季的短诗。"))
5. 团队控制与高级用法
团队重置与状态恢复
# 先创建 model_client 和 team
# ...(同上)
await team.reset() # 清空历史,准备新任务
外部终止与内部终止
- 内部终止:如TextMentionTermination,自动检测Agent输出内容终止。
- 外部终止:如ExternalTermination,可在任意时刻由外部触发终止。
代码示例3:外部终止团队
from autogen_agentchat.conditions import ExternalTermination
import asyncio
from autogen_agentchat.ui import Console
# 先创建 model_client、primary_agent、critic_agent
model_client = OllamaChatCompletionClient(
model="qwen2.5-coder:latest",
model_info={
"vision": False,
"function_calling": True,
"json_output": False,
"structured_output": True,
}
)
primary_agent = AssistantAgent(
"primary",
model_client=model_client,
system_message="你是一个优秀的AI助手"
)
critic_agent = AssistantAgent(
"critic",
model_client=model_client,
system_message="你只提供两个能力,1.对内容提供建设性反馈.2.当你的反馈得到处理时,回复"APPROVE",如果对方没有按照你的反馈进行修改就不回复"APPROVE""
)
termination = TextMentionTermination("APPROVE")
external_termination = ExternalTermination()
team = RoundRobinGroupChat(
[primary_agent, critic_agent],
termination_condition=external_termination | termination
)
run = asyncio.create_task(Console(team.run_stream(task="写一首关于秋季的短诗。")))
await asyncio.sleep(0.1)
external_termination.set() # 外部终止
await run
立即终止(CancellationToken)
from autogen_core import CancellationToken
import asyncio
# 先创建 model_client、primary_agent、critic_agent、team
# ...(同上)
cancellation_token = CancellationToken()
run = asyncio.create_task(
team.run(
task="Translate the poem to Spanish.",
cancellation_token=cancellation_token,
)
)
cancellation_token.cancel()
try:
result = await run
except asyncio.CancelledError:
print("Task was cancelled.")
6. 单Agent团队的循环任务
AutoGen支持用团队结构运行单个Agent,实现如循环工具调用等高级用法。
注意:
如果你使用的是OpenAI gpt-4o等标准模型,工具调用过程会有明确的ToolCallRequestEvent、ToolCallExecutionEvent等事件,终止条件可以严格依赖于消息类型。但如果你用的是本地ollama模型(如qwen2.5-coder:latest),不会出现标准的工具调用事件,模型输出可能是json格式或多条工具调用结果与终止词(如Done)合并为一条消息。
这时,建议将终止条件由
TextMessageTermination改为TextMentionTermination,只要消息中出现终止词即可终止,兼容性更好。
代码示例4:单Agent循环工具调用(兼容ollama模型)
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_ext.models.ollama import OllamaChatCompletionClient
# 先创建 model_client
model_client = OllamaChatCompletionClient(
model="qwen2.5-coder:latest",
model_info={
"vision": False,
"function_calling": True,
"json_output": False,
"structured_output": True,
}
)
def increment_number(number: int) -> int:
return number + 1
looped_assistant = AssistantAgent(
"looped_assistant",
model_client=model_client, # 推荐gpt-4o模型
tools=[increment_number],
system_message="你是一个AI助手,使用increment_number工具将数字递增到目标值,当得到的反馈结果没有达到目标值时,循环调用该工具。达到目标值后只输出'Done'。"
)
# 兼容ollama模型,使用TextMentionTermination
termination_condition = TextMentionTermination("Done")
team = RoundRobinGroupChat([looped_assistant], termination_condition=termination_condition)
async for message in team.run_stream(task="Increment the number 5 to 10."):
print(type(message).__name__, message)
说明:
- OpenAI gpt-4o等模型会严格分开发送工具调用事件和文本消息,终止条件可用TextMessageTermination。
- 本地ollama模型输出可能为json格式或多条内容合并,建议用TextMentionTermination提升兼容性。
- 你可能会看到一条消息中包含多个工具调用结果和终止词(如’Done’),此时TextMentionTermination能正确终止。
7. 实战案例/进阶技巧
- 多Agent协作写诗、代码评审、自动问答等真实案例
- 性能优化建议:合理设置终止条件,避免死循环
- Agent自定义与团队扩展技巧
- 团队状态管理与多轮任务衔接
8. 常见问题与解决方案(FAQ)
- 团队无法终止/重置的常见原因
- 终止条件设置注意事项
- 团队消息流的调试技巧
- 代理间消息同步与上下文一致性问题
9. 总结与资源推荐
AutoGen Team让多智能体协作变得高效、灵活且可控,适合各类复杂任务。建议优先体验gpt-4o模型,获得最佳工具调用与团队协作体验。
如需更详细的代码、流程图或遇到具体问题,欢迎评论区留言交流!
更多推荐
所有评论(0)