介绍
大家好,今天给大家分享的内容是微软AutoGen框架的核心功能Teams。我们直接进入主题。
Teams
在微软AutoGen框架里,“Teams” 代表着智能体团队的概念,它让多个智能体相互协作,共同完成复杂任务。
AutoGen中的智能体是能够自主执行特定任务、与其他智能体交互的实体。Teams 就是将多个这样的智能体组合在一起,每个智能体有不同专长和职责,它们通过彼此沟通和协作,完成单个智能体难以完成的复杂任务。
在本次的分享内容中,我们将学习如何使用AutoGen创建多代理Team(或简称为团队)。团队是一群共同努力并实现共同目标的代理。
我首先会向大家分享如何创建和运行团队。然后,我会解释如何观察团队(Teams)的行为(因为这对于调试和了解团队的性能至关重要),以及控制团队行为的常见操作。
创建团队
RoundRobinGroupChat是由AutoGen提供的类,它是一种简单但有效的团队配置类。在此配置下,所有智能体共享相同的上下文,并以循环赛的方式轮流做出回应。轮到每个智能体时,它会将自己的回应广播给其他所有智能体,以确保整个团队保持一致的上下文。
我们将从创建一个由两个助理智能体(AssistantAgent)组成的团队开始,并设置一个文本提及终止条件(TextMentionTermination),当在智能体的回应中检测到特定词汇时,该团队就会停止运行。
这个双智能体团队实现了反思模式,这是一种多智能体设计模式,其中一个评判智能体评估一个主要智能体的回应。
代码演示
- import asyncio
- from autogen_agentchat.agents import AssistantAgent
- from autogen_agentchat.conditions import TextMentionTermination
- from autogen_agentchat.teams import RoundRobinGroupChat
- from autogen_ext.models.openai import OpenAIChatCompletionClient
-
- # 创建一个OpenAI模型客户端。
- model_client = OpenAIChatCompletionClient(
- model="gpt-3.5-turbo",
- # api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,则此步骤可选。
- )
-
- # 创建主智能体。
- primary_agent = AssistantAgent(
- "primary",
- model_client=model_client,
- system_message="You are a helpful AI assistant.",
- )
-
- # 创建评判智能体。
- critic_agent = AssistantAgent(
- "critic",
- model_client=model_client,
- system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
- )
-
- # 定义一个终止条件,若评判者批准,则停止任务。
- text_termination = TextMentionTermination("APPROVE")
-
- # 创建一个包含主智能体和评判智能体的团队。
- team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)
运行团队
让我们调用 run()方法,通过一项任务运行该团队。
代码演示
- result = asyncio.run(team.run(task="Write a short poem about the fall season."))
- print(result)
完整代码
- import asyncio
- from autogen_agentchat.agents import AssistantAgent
- from autogen_agentchat.conditions import TextMentionTermination
- from autogen_agentchat.teams import RoundRobinGroupChat
- from autogen_ext.models.openai import OpenAIChatCompletionClient
-
- # 创建一个OpenAI模型客户端。
- model_client = OpenAIChatCompletionClient(
- model="gpt-3.5-turbo",
- # api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,则此步骤可选。
- )
-
- # 创建主智能体。
- primary_agent = AssistantAgent(
- "primary",
- model_client=model_client,
- system_message="You are a helpful AI assistant.",
- )
-
- # 创建评判智能体。
- critic_agent = AssistantAgent(
- "critic",
- model_client=model_client,
- system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
- )
-
- # 定义一个终止条件,若评判者批准,则停止任务。
- text_termination = TextMentionTermination("APPROVE")
-
- # 创建一个包含主智能体和评判智能体的团队。
- team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)
-
- result = asyncio.run(team.run(task="Write a short poem about the fall season."))
- print(result)
运行结果
- TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Write a short poem about the fall season.', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=28, completion_tokens=94), content="In hues of gold and crimson blaze,\nAutumn's touch on trees displays,\nA gentle chill in the air's embrace,\nAs leaves gently fall with grace.\n\nNature's canvas painted with flair,\nWhispers of change linger in the air,\nHarvest bounty on display,\nIn the fall season's gentle sway.\n\nCool winds rustle through the land,\nA symphony by autumn's hand,\nCrunch of leaves beneath our feet,\nA fleeting beauty, oh so sweet.", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=140, completion_tokens=57), content='I like the vivid imagery and the beautiful flow of your poem about the fall season. The use of descriptive language and sensory details really brings the essence of autumn to life. Maybe consider adding a concluding stanza to wrap up the poem or bring it to a satisfying close. Well done overall!', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=192, completion_tokens=52), content="Thank you for your feedback! I'm glad you enjoyed the imagery and flow of the poem. I will consider adding a concluding stanza to provide a sense of closure and bring the poem to a satisfying end. Your feedback is valuable, and I appreciate your insights.", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=262, completion_tokens=51), content='Great to hear that you found the feedback helpful! Adding a concluding stanza can help give your poem a sense of completion and leave a lasting impression on the reader. I look forward to reading the revised version with the new stanza. Keep up the great work!', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=308, completion_tokens=46), content="Thank you for the encouragement! I'll work on adding a concluding stanza to the poem to enhance its completeness and leave a lasting impact on the reader. Your feedback is truly appreciated, and I'm grateful for your support and guidance.", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=372, completion_tokens=3), content='APPROVE', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")
-
- 进程已结束,退出代码为 0
该团队会运行各个智能体,直至满足终止条件。在这种情况下,团队会按照循环顺序运行智能体,直到在智能体的回复中检测到 “TERMINATE” 这个词,满足终止条件。团队停止运行时,会返回一个TaskResult对象,其中包含团队中各个智能体生成的所有消息。
观察团队
与智能体的on_messages_stream()方法类似,我们可以通过调用run_stream()方法,在团队运行时实时接收其消息流。此方法返回一个生成器,在团队中的智能体生成消息时,该生成器会逐个产出这些消息,最后一个产出项是TaskResult对象。
完整代码
- import asyncio
- from autogen_agentchat.agents import AssistantAgent
- from autogen_agentchat.base import TaskResult
- from autogen_agentchat.conditions import TextMentionTermination
- from autogen_agentchat.teams import RoundRobinGroupChat
- from autogen_ext.models.openai import OpenAIChatCompletionClient
-
- # 创建一个OpenAI模型客户端。
- model_client = OpenAIChatCompletionClient(
- model="gpt-3.5-turbo",
- # api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,则此步骤可选。
- )
-
- # 创建主智能体。
- primary_agent = AssistantAgent(
- "primary",
- model_client=model_client,
- system_message="You are a helpful AI assistant.",
- )
-
- # 创建评判智能体。
- critic_agent = AssistantAgent(
- "critic",
- model_client=model_client,
- system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
- )
-
- # 定义一个终止条件,若评判者批准,则停止任务。
- text_termination = TextMentionTermination("APPROVE")
-
- # 创建一个包含主智能体和评判智能体的团队。
- team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)
-
-
- async def main() -> None:
- # 运行团队
- result = await team.run(task="Write a short poem about the fall season.")
- # print(result)
-
- await team.reset() # 为新任务重置团队。
- async for message in team.run_stream(task="Write a short poem about the summer season."): # type: ignore
- if isinstance(message, TaskResult):
- print("Stop Reason:", message.stop_reason)
- else:
- print(message)
-
- asyncio.run(main())
运行结果
- source='user' models_usage=None content='Write a short poem about the summer season.' type='TextMessage'
- source='primary' models_usage=RequestUsage(prompt_tokens=28, completion_tokens=53) content="In summer's embrace, the sun's warm kiss,\nGolden days filled with endless bliss.\nBreezes whisper through the trees with ease,\nNature hums a melody that brings peace.\nFields adorned with flowers bloom,\nAs summer's magic dispels all gloom." type='TextMessage'
- source='critic' models_usage=RequestUsage(prompt_tokens=99, completion_tokens=74) content='I like how you captured the essence of summer with vivid imagery and evocative language. The flow of the poem is smooth and the rhymes are well-crafted, painting a serene picture of the season. Consider playing with different rhyme schemes or adding a touch of personal experience to make the poem even more engaging for the reader. Great work overall! \n\nAPPROVE' type='TextMessage'
- Stop Reason: Text 'APPROVE' mentioned
-
- 进程已结束,退出代码为 0
如上述示例所示,我们可以通过检查stop_reason属性来确定团队停止运行的原因。
Console()方法提供了一种便捷方式,能够以合适的格式将消息打印到控制台。
完整代码
- import asyncio
- from autogen_agentchat.agents import AssistantAgent
- from autogen_agentchat.conditions import TextMentionTermination
- from autogen_agentchat.teams import RoundRobinGroupChat
- from autogen_agentchat.ui import Console
- from autogen_ext.models.openai import OpenAIChatCompletionClient
-
- # 创建一个OpenAI模型客户端。
- model_client = OpenAIChatCompletionClient(
- model="gpt-3.5-turbo",
- # api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,则此步骤可选。
- )
-
- # 创建主智能体。
- primary_agent = AssistantAgent(
- "primary",
- model_client=model_client,
- system_message="You are a helpful AI assistant.",
- )
-
- # 创建评判智能体。
- critic_agent = AssistantAgent(
- "critic",
- model_client=model_client,
- system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
- )
-
- # 定义一个终止条件,若评判者批准,则停止任务。
- text_termination = TextMentionTermination("APPROVE")
-
- # 创建一个包含主智能体和评判智能体的团队。
- team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)
-
-
- async def main() -> None:
- # 运行团队
- result = await team.run(task="Write a short poem about the fall season.")
- # print(result)
-
- await team.reset() # 为新任务重置团队。
- await Console(
- team.run_stream(task="Write a short poem about the summer season.")) # 将流式消息输出到控制台。
-
- asyncio.run(main())
运行结果
- ---------- user ----------
- Write a short poem about the summer season.
- ---------- primary ----------
- In summer's warmth, the sun shines bright,
- Days so long and endless night.
- Fields of green and flowers bloom,
- Nature's beauty in full costume.
- Beach days, picnics, laughter shared,
- Summer memories, beyond compare.
- Oh, sweet summer, how we adore,
- Your essence leaves us craving more.
- ---------- critic ----------
- I like your poem about the summer season! It captures the essence of summer with vivid descriptions and a sense of nostalgia. One suggestion could be to add more sensory details to make the imagery even more immersive. For example, you could describe the sounds of waves crashing on the beach or the scent of freshly cut grass. This would help bring your poem to life even more. Great job overall!
- ---------- primary ----------
- Thank you for your feedback and suggestion! I appreciate your kind words and will definitely consider adding more sensory details to enhance the imagery in future poems. I'm glad you enjoyed the poem about the summer season. If you have any other requests or feedback, feel free to let me know.
- ---------- critic ----------
- I'm glad you found the feedback helpful! Adding more sensory details can indeed make a poem more captivating. Keep up the great work with your poetry, and feel free to reach out if you ever need more feedback or ideas. APPROVE
-
- 进程已结束,退出代码为 0
重置团队
我们可以通过调用reset()方法来重置团队。此方法会清除团队的状态,包括所有智能体的状态。它会调用每个智能体的on_reset()方法,以清除智能体的状态。
代码演示
- async def main() -> None:
- # 运行团队
- result = await team.run(task="Write a short poem about the summer season.")
- # print(result)
- await team.reset() # 为下一次运行重置团队。
如果下一个任务与上一个任务无关,重置团队通常是个好主意。然而,如果下一个任务与上一个任务相关,就无需重置,而是可以让团队继续运行。
停止团队
除了像TextMentionTermination这类基于团队内部状态使团队停止运行的自动终止条件之外,你还可以通过使用ExternalTermination从外部使团队停止运行。
对ExternalTermination调用set()方法,会在当前智能体轮次结束时停止团队运行。因此,团队可能不会立即停止。这使得当前智能体能够在团队停止前完成其轮次,并向团队广播最终消息,从而保持团队状态的一致性。
完整代码
- import asyncio
- from autogen_agentchat.agents import AssistantAgent
- from autogen_agentchat.conditions import ExternalTermination, TextMentionTermination
- from autogen_agentchat.teams import RoundRobinGroupChat
- from autogen_agentchat.ui import Console
- from autogen_ext.models.openai import OpenAIChatCompletionClient
-
- # 创建一个OpenAI模型客户端。
- model_client = OpenAIChatCompletionClient(
- model="gpt-3.5-turbo",
- # api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,则此步骤可选。
- )
-
- # 创建主智能体。
- primary_agent = AssistantAgent(
- "primary",
- model_client=model_client,
- system_message="You are a helpful AI assistant.",
- )
-
- # 创建评判智能体。
- critic_agent = AssistantAgent(
- "critic",
- model_client=model_client,
- system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
- )
-
- # 定义一个终止条件,若评判者批准,则停止任务。
- text_termination = TextMentionTermination("APPROVE")
-
- # 创建一个带有外部终止条件的新团队。
- external_termination = ExternalTermination()
- team = RoundRobinGroupChat(
- [primary_agent, critic_agent],
- termination_condition=external_termination | text_termination,
- # 使用按位或运算符来组合条件。
- )
-
-
- async def main() -> None:
- # 在后台任务中运行该团队。
- run = asyncio.create_task(Console(team.run_stream(task="Write a short poem about the summer season.")))
-
- # 等待一段时间。
- await asyncio.sleep(0.1)
-
- # 停止这个团队(的运行)。
- external_termination.set()
-
- # 等待团队完成任务。
- await run
-
- asyncio.run(main())
运行结果
- ---------- user ----------
- Write a short poem about the summer season.
- ---------- primary ----------
- Under the warm sun's gaze we play,
- With skies of blue, a perfect day.
- Golden fields and flowers bloom,
- Summer's beauty, nature's perfume.
- Ocean waves that gently kiss the shore,
- As we seek adventure, forevermore.
- Joyful laughter fills the air,
- In summer's embrace, we have no care.
-
- 进程已结束,退出代码为 0
从上述运行结果中,我们可以看到团队停止是因为满足了外部终止条件,但发言的智能体在团队停止前得以完成其轮次。
恢复团队
团队是有状态的,每次运行后都会保留对话历史和上下文,除非我们重置团队。
我们可以通过再次调用run()或run_stream()方法,在不设置新任务的情况下恢复团队,使其从上一次中断的地方继续。RoundRobinGroupChat将按照循环顺序从下一个智能体继续进行。
完整代码
- import asyncio
- from autogen_agentchat.agents import AssistantAgent
- from autogen_agentchat.conditions import ExternalTermination, TextMentionTermination
- from autogen_agentchat.teams import RoundRobinGroupChat
- from autogen_agentchat.ui import Console
- from autogen_ext.models.openai import OpenAIChatCompletionClient
-
- # 创建一个OpenAI模型客户端。
- model_client = OpenAIChatCompletionClient(
- model="gpt-3.5-turbo",
- # api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,则此步骤可选。
- )
-
- # 创建主智能体。
- primary_agent = AssistantAgent(
- "primary",
- model_client=model_client,
- system_message="You are a helpful AI assistant.",
- )
-
- # 创建评判智能体。
- critic_agent = AssistantAgent(
- "critic",
- model_client=model_client,
- system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
- )
-
- # 定义一个终止条件,若评判者批准,则停止任务。
- text_termination = TextMentionTermination("APPROVE")
-
- # 创建一个带有外部终止条件的新团队。
- external_termination = ExternalTermination()
- team = RoundRobinGroupChat(
- [primary_agent, critic_agent],
- termination_condition=external_termination | text_termination,
- # 使用按位或运算符来组合条件。
- )
-
-
- async def main() -> None:
- # 在后台任务中运行该团队。
- run = asyncio.create_task(Console(team.run_stream(task="Write a short poem about the summer season.")))
-
- # 等待一段时间。
- await asyncio.sleep(0.1)
-
- # 停止这个团队(的运行)。
- external_termination.set()
-
- # 等待团队完成任务。
- await run
-
- # 恢复团队以继续完成上一个任务。
- await Console(team.run_stream())
-
- asyncio.run(main())
运行结果
- ---------- user ----------
- Write a short poem about the summer season.
- ---------- primary ----------
- In summer's light, the world ablaze,
- Golden sun on warm skin plays.
- Fields of green and skies so blue,
- Nature's beauty shining through.
-
- Breezes dance, a whispered song,
- Days grow long, nights not so long.
- Laughter echoing down the shore,
- Memories made forevermore.
-
- Fruits ripe, sweet and juicy,
- Bees hum in meadows so floozy.
- Children's laughs fill the air,
- Summer magic everywhere.
- A season of joy and delight,
- Summer's warmth, a pure delight.
- ---------- critic ----------
- I really enjoyed reading your poem about the summer season. The vivid imagery and descriptive language help to capture the essence of summer and evoke a sense of warmth and joy. One suggestion would be to explore different rhyme schemes or structures to add variety and depth to the poem. Additionally, considering incorporating sensory details to further engage the reader's imagination and create a more immersive experience. Keep up the great work!
- ---------- primary ----------
- Thank you for your feedback! I appreciate your positive comments and suggestions. I will definitely explore different rhyme schemes, structures, and incorporate more sensory details in future poems. Your feedback will help me improve and create more engaging and immersive pieces. If you have any other suggestions or requests, feel free to let me know.
- ---------- critic ----------
- Great to hear that you found the feedback helpful! Exploring different techniques and continuing to enhance your writing will definitely add more depth to your poems. Keep practicing and experimenting with various styles to further develop your unique voice as a poet. I encourage you to keep writing and sharing your work. Don't hesitate to ask for more feedback or guidance whenever you need it. Keep up the fantastic work! APPROVE
-
- 进程已结束,退出代码为 0
从上述输出中我们可以看到,团队从上一次中断的地方继续运行,并且第一条消息来自团队停止前最后发言的智能体之后的下一个智能体。
现在,我们在保留上一个任务相关上下文的同时,给团队安排新任务并再次恢复运行。
完整代码
- ---------- user ----------
- Write a short poem about the summer season.
- ---------- primary ----------
- In summer's warm embrace we find delight,
- The sun's bright rays, the day so long and bright.
- Trees dance in the gentle breeze that blows,
- As flowers bloom in colors that transpose.
-
- The chirping birds sing sweetly in the air,
- And children's laughter fills the atmosphere.
- Picnics and adventures, joy abound,
- In summer's magic, simple pleasures found.
-
- The days stretch out in golden hues so grand,
- A season cherished in this wondrous land.
- So let us savor what the summer brings,
- And revel in the beauty that it sings.
-
- Summer, oh summer, radiant and true,
- Bringing warmth and light in all we do.
- ---------- user ----------
- 将这首诗用中文唐诗风格写一遍。
- ---------- critic ----------
- 夏日阳光暖如炎,天高云淡水东流。
- 绿树成荫乘风舞,百花斑斓色斩流。
- 鸟啼声动山迢峻,儿童欢笑乐无休。
- 野餐冒险皆为乐,夏日正当好时留。
-
- 金色阳光着人眼,夏日气候何其闲。
- 细细咀嚼夏之美,尽情沉醉其中间。
- 夏天呀夏天光辉现,温暖与光辉见不断。
- ---------- primary ----------
- 这首唐诗风格中文诗歌如下:
-
- 夏日暖阳照人间,
- 高天淡云水悠悠。
- 翠树摇风舞来去,
- 百花绚烂色斑斓。
- 鸟语悠扬山谷鸣,
- 儿童欢笑乐无穷。
- 野餐冒险快乐趣,
- 夏日光阴好时光。
-
- 金色暖阳照眼前,
- 夏日气候多闲适。
- 品味夏天独美景,
- 陶醉其中真乐事。
- 夏日之光闪耀现,
- 温暖光辉不停摆。
- ---------- critic ----------
- This Tang-style Chinese poem captures the essence of summer beautifully! The imagery and flow are well-crafted, evoking the warmth and beauty of the season. Great job! If you would like assistance with any other poems or have any other requests, feel free to ask.
-
- APPROVE
-
- 进程已结束,退出代码为 0
中止团队
我们可以在执行过程中,通过设置传递给cancellationToken参数的CancellationToken,来中止对run()或run_stream()的调用。
与停止团队不同,中止团队会立即停止团队,并抛出CancelledError异常。
完整代码
- import asyncio
- from autogen_agentchat.agents import AssistantAgent
- from autogen_agentchat.conditions import TextMentionTermination
- from autogen_agentchat.teams import RoundRobinGroupChat
- from autogen_agentchat.ui import Console
- from autogen_core import CancellationToken
- from autogen_ext.models.openai import OpenAIChatCompletionClient
-
- # 创建一个OpenAI模型客户端。
- model_client = OpenAIChatCompletionClient(
- model="gpt-3.5-turbo",
- # api_key="sk-...", # 如果已设置OPENAI_API_KEY环境变量,则此步骤可选。
- )
-
- # 创建主智能体。
- primary_agent = AssistantAgent(
- "primary",
- model_client=model_client,
- system_message="You are a helpful AI assistant.",
- )
-
- # 创建评判智能体。
- critic_agent = AssistantAgent(
- "critic",
- model_client=model_client,
- system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
- )
-
- # 定义一个终止条件,若评判者批准,则停止任务。
- text_termination = TextMentionTermination("APPROVE")
-
- team = RoundRobinGroupChat(
- [primary_agent, critic_agent],
- termination_condition=text_termination
- # 使用按位或运算符来组合条件。
- )
-
- # 创建一个取消令牌。
- cancellation_token = CancellationToken()
-
-
- async def main() -> None:
- # 利用另一个协程来运行这个团队。
- run = asyncio.create_task(
- Console(
- team.run_stream(
- task="Write a short poem about the summer season.",
- cancellation_token=cancellation_token
- )
- )
- )
-
- # 取消运行。
- cancellation_token.cancel()
-
- try:
- result = await run # 这将引发一个 “取消错误” 。
- except asyncio.CancelledError:
- print("Task was cancelled.")
-
- asyncio.run(main())
运行效果
- Task was cancelled.
-
- 进程已结束,退出代码为 0
说明
如果大家在运行上述代码的时候有AutoGen相关的提示或报错(例如:该参数不存在,没有此类方法等),请尝试更新一下AutoGen,博主在分享这篇博文的时候AutoGen的版本是0.4.5稳定版。
安装或更新命令
pip install -U "autogen-agentchat" "autogen-ext[openai,azure]"
结束
好了,以上就是本次分享的全部内容。总体上看,RoundRobinGroupChat是一种用于实现多智能体(Agent)之间进行循环式对话交互的机制,属于群组聊天(Group Chat)功能的一部分。上述分享帮助大家掌握如何创建、运行、观察、重置、停止、恢复及中止该“聊天组”,并希望大家会灵活的运用,博主也希望本次分享能对大家有所帮助。如果大家对博主分享的内容感兴趣或有帮助,请点赞和关注,博主会持续更新关于微软AutoGen更多和更有趣的内容。
评论记录:
回复评论: