在人工智能的蓬勃发展浪潮中,AutoGen 作为一款强大的工具,正逐渐崭露头角,为复杂任务的处理提供了创新的解决方案。本文将深入探讨 AutoGen 中的智能体团队协作机制,包括团队创建、运行控制、反馈机制以及终止条件等核心方面,并结合实际代码示例与执行结果进行详细分析。
一、智能体团队基础:从创建到运行
(一)创建团队:多样组合实现协作
AutoGen 中的 RoundRobinGroupChat
为创建智能体团队提供了一种简洁而有效的方式。在实际应用中,我们可以根据任务需求灵活组合不同类型的智能体。例如,在一个自然语言处理任务中,我们创建了一个包含 AssistantAgent
和 CriticAgent
的团队,并设置了 TextMentionTermination
终止条件。
ini
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.base import TaskResult
from autogen_agentchat.conditions import ExternalTermination, 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-4o-2024-08-06",
# 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' when your feedbacks are addressed."
)
# 定义终止条件,当评论智能体批准时停止任务
text_termination = TextMentionTermination("APPROVE")
# 创建团队
team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)
这里的主智能体负责生成内容,而评论智能体则对主智能体的输出进行评估和反馈,这种组合体现了多智能体协作中的常见模式,通过不同智能体的专业能力互补,提高任务处理的质量和效率。
(二)运行团队:任务驱动的智能协作
运行团队时,通过调用 run()
或 run_stream()
方法并传入任务描述,智能体团队便开始协同工作。以创作一首关于秋季的短诗为例:
ini
# 使用 asyncio.run(...) 在脚本中运行
result = await team.run(task="Write a short poem about the fall season.")
print(result)
执行结果如下:
python
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=109), content="Leaves of amber, gold, and rust,
Dance upon the gentle gust.
Crisp air whispers tales of old,
As daylight wanes, the night grows bold.
Pumpkin patch and apple treats,
Laughter in the street repeats.
Sweaters warm and fires aglow,
It's time for nature's vibrant show.
The harvest moon ascends the sky,
While geese in formation start to fly.
Autumn speaks in colors bright,
A fleeting grace, a pure delight. ", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=154, completion_tokens=200), content='Your poem beautifully captures the essence of the fall season with vivid imagery and a rhythmic flow. The use of descriptive language like "amber, gold, and rust" effectively paints a visual picture of the changing leaves. Phrases such as "crisp air whispers tales of old" and "daylight wanes, the night grows bold" add a poetic touch by incorporating seasonal characteristics.
However, you might consider exploring other sensory details to deepen the reader's immersion. For example, mentioning the sound of crunching leaves underfoot or the scent of cinnamon and spices in the air could enhance the sensory experience.
Additionally, while the mention of "pumpkin patch and apple treats" is evocative of fall, expanding on these elements or including more personal experiences or emotions associated with the season might make the poem more relatable and engaging.
Overall, you've crafted a lovely poem that celebrates the beauty and traditions of autumn with grace and warmth. A few tweaks to include multisensory details could elevate it even further.', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=347, completion_tokens=178), content="Thank you for the thoughtful feedback. Here's a revised version of the poem with additional sensory details:
Leaves of amber, gold, and rust,
Dance upon the gentle gust.
Crisp air whispers tales of old,
As daylight wanes, the night grows bold.
Crunch beneath the wandering feet,
A melody of autumn's beat.
Cinnamon and spices blend,
In every breeze, nostalgia sends.
Pumpkin patch and apple treats,
Laughter in the street repeats.
Sweaters warm and fires aglow,
It's time for nature's vibrant show.
The harvest moon ascends the sky,
While geese in formation start to fly.
Autumn speaks in colors bright,
A fleeting grace, a pure delight.
I hope this version resonates even more with the spirit of fall. Thank you again for your suggestions!", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=542, completion_tokens=3), content='APPROVE', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")
从结果可以看出,主智能体首先生成一首诗,评论智能体对其进行分析并提出改进建议,如增加感官细节、调整结构等。主智能体根据反馈进行修订,直到评论智能体批准。这种迭代式的协作过程充分展示了多智能体系统在处理复杂创作任务时的优势,能够不断优化输出结果,趋近于更优质的解决方案。
二、团队运行监控与控制:洞察与干预
(一)观察团队:实时追踪运行动态
在团队运行过程中,我们可以使用 run_stream()
方法实时获取智能体产生的消息流。这对于理解智能体的决策过程和协作逻辑至关重要。例如:
python
# 当在脚本内部运行时,使用异步主函数并从 asyncio.run(...) 调用
await team.reset()
async for message in team.run_stream(task="Write a short poem about the fall season."):
if isinstance(message, TaskResult):
print("Stop Reason:", message.stop_reason)
else:
print(message)
执行结果如下:
vbnet
source='user' models_usage=None content='Write a short poem about the fall season.' type='TextMessage'
source='primary' models_usage=RequestUsage(prompt_tokens=28, completion_tokens=105) content="Leaves descend in golden dance,
Whispering secrets as they fall,
Crisp air brings a gentle trance,
Heralding Autumn's call.
Pumpkins glow with orange light,
Fields wear a cloak of amber hue,
Days retreat to longer night,
Skies shift to deeper blue.
Winds carry scents of earth and pine,
Sweaters wrap us, warm and tight,
Nature's canvas, bold design,
In Fall's embrace, we find delight. " type='TextMessage'
source='critic' models_usage=RequestUsage(prompt_tokens=150, completion_tokens=226) content='Your poem beautifully captures the essence of fall with vivid imagery and a soothing rhythm. The imagery of leaves descending, pumpkins glowing, and fields cloaked in amber hues effectively paints a picture of the autumn season. The use of contrasting elements like "Days retreat to longer night" and "Sweaters wrap us, warm and tight" provides a nice balance between the cold and warmth associated with the season. Additionally, the personification of autumn through phrases like "Autumn's call" and "Nature's canvas, bold design" adds depth to the depiction of fall.
To enhance the poem further, you might consider focusing on the soundscape of fall, such as the rustling of leaves or the distant call of migrating birds, to engage readers' auditory senses. Also, varying the line lengths slightly could add a dynamic flow to the reading experience.
Overall, your poem is engaging and effectively encapsulates the beauty and transition of fall. With a few adjustments to explore other sensory details, it could become even more immersive.
If you incorporate some of these suggestions or find another way to expand the sensory experience, please share your update!' type='TextMessage'
source='primary' models_usage=RequestUsage(prompt_tokens=369, completion_tokens=143) content="Thank you for the thoughtful critique and suggestions. Here's a revised version of the poem with added attention to auditory senses and varied line lengths:
Leaves descend in golden dance,
Whisper secrets in their fall,
Breezes hum a gentle trance,
Heralding Autumn's call.
Pumpkins glow with orange light,
Amber fields beneath wide skies,
Days retreat to longer night,
Chill winds and distant cries.
Rustling whispers of the trees,
Sweaters wrap us, snug and tight,
Nature's canvas, bold and free,
In Fall's embrace, pure delight.
I appreciate your feedback and hope this version better captures the sensory richness of the season!" type='TextMessage'
source='critic' models_usage=RequestUsage(prompt_tokens=529, completion_tokens=160) content='Your revised poem is a beautiful enhancement of the original. By incorporating auditory elements such as "Breezes hum" and "Rustling whispers of the trees," you've added an engaging soundscape that draws the reader deeper into the experience of fall. The varied line lengths work well to create a more dynamic rhythm throughout the poem, adding interest and variety to each stanza.
The succinct, yet vivid, lines of "Chill winds and distant cries" wonderfully evoke the atmosphere of the season, adding a touch of mystery and depth. The final stanza wraps up the poem nicely, celebrating the complete sensory embrace of fall with lines like "Nature's canvas, bold and free."
You've successfully infused more sensory richness into the poem, enhancing its overall emotional and atmospheric impact. Great job on the revisions!
APPROVE' type='TextMessage'
Stop Reason: Text 'APPROVE' mentioned
通过这种方式,我们可以详细观察到每个智能体的输入和输出,以及任务的进展情况。在诗歌创作任务中,我们能够看到主智能体如何根据初始提示生成诗歌,评论智能体如何基于诗歌的内容、结构和情感表达给出针对性的反馈,以及主智能体如何进一步改进。这不仅有助于调试和优化智能体的行为,还能为深入研究多智能体协作机制提供丰富的数据和案例。
(二)重置、停止、恢复与中止团队:灵活掌控任务流程
- 重置团队 :在完成一个任务或切换到不相关任务时,调用
reset()
方法可以清除团队的状态,包括所有智能体的内部状态。这确保了每个任务都在一个相对独立和干净的环境中启动,避免了前一个任务的残留信息对后续任务的干扰。 - 停止团队 :除了基于智能体消息内容的终止条件(如
TextMentionTermination
)外,ExternalTermination
允许从外部手动停止团队。这在实际应用中非常有用,例如在用户界面中设置一个停止按钮,当用户点击时可以立即停止团队运行。在示例中,我们创建了一个带有外部终止条件的团队,并在运行一段时间后手动停止:
ini
# 创建一个带有外部终止条件的新团队
external_termination = ExternalTermination()
team = RoundRobinGroupChat(
[primary_agent, critic_agent],
termination_condition=external_termination | text_termination
)
# 在后台任务中运行团队
run = asyncio.create_task(Console(team.run_stream(task="Write a short poem about the fall season.")))
# 等待一段时间
await asyncio.sleep(0.1)
# 停止团队
external_termination.set()
# 等待团队完成
await run
执行结果如下:
python
---------- user ----------
Write a short poem about the fall season.
---------- primary ----------
Leaves of amber, gold, and red,
Gently drifting from trees overhead.
Whispers of wind through the crisp, cool air,
Nature's canvas painted with care.
Harvest moons and evenings that chill,
Fields of plenty on every hill.
Sweaters wrapped tight as twilight nears,
Fall's charming embrace, as warm as it appears.
Pumpkins aglow with autumn's light,
Harvest feasts and stars so bright.
In every leaf and breeze that calls,
We find the magic of glorious fall.
[Prompt tokens: 28, Completion tokens: 114]
---------- Summary ----------
Number of messages: 2
Finish reason: External termination requested
Total prompt tokens: 28
Total completion tokens: 114
Duration: 1.71 seconds
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=114), content="Leaves of amber, gold, and red,
Gently drifting from trees overhead.
Whispers of wind through the crisp, cool air,
Nature's canvas painted with care.
Harvest moons and evenings that chill,
Fields of plenty on every hill.
Sweaters wrapped tight as twilight nears,
Fall's charming embrace, as warm as it appears.
Pumpkins aglow with autumn's light,
Harvest feasts and stars sobright.
In every leaf and breeze that calls,
We find the magic of glorious fall. ", type='TextMessage')], stop_reason='External termination requested')
这种机制使得我们能够在必要时及时干预团队的运行,确保任务执行符合预期的时间和资源限制。
- 恢复团队 :由于团队是有状态的,在不重置的情况下再次调用
run()
或run_stream()
方法可以让团队从上次停止的地方继续执行。这在处理一系列相关任务或需要持续迭代的场景中非常方便。例如,在诗歌创作任务中,我们可以在评论智能体提出反馈后,继续让团队运行以进一步完善诗歌:
scss
await Console(team.run_stream())
执行结果如下:
less
---------- critic ----------
This poem beautifully captures the essence of the fall season with vivid imagery and a soothing rhythm. The descriptions of the changing leaves, cool air, and various autumn traditions make it easy for readers to envision and feel the charm of fall. Here are a few suggestions to enhance its impact:
1. **Structure Variation**: Consider breaking some lines with a hyphen or ellipsis for dramatic effect or emphasis. For instance, "Sweaters wrapped tight as twilight nears--- / Fall's charming embrace, as warm as it appears."
2. **Sensory Details**: While the poem already evokes visual and tactile senses, incorporating other senses such as sound or smell could deepen the immersion. For example, include the scent of wood smoke or the crunch of leaves underfoot.
3. **Metaphorical Language**: Adding metaphors or similes can further enrich the imagery. For example, you might compare the leaves falling to a golden rain or the chill in the air to a gentle whisper.
Overall, it's a lovely depiction of fall. These suggestions are minor tweaks that might elevate the reader's experience even further. Nice work!
Let me know if these feedbacks are addressed.
[Prompt tokens: 159, Completion tokens: 237]
---------- primary ----------
Thank you for the thoughtful feedback! Here's a revised version, incorporating your suggestions:
Leaves of amber, gold---drifting like dreams,
A golden rain from trees' canopies.
Whispers of wind---a gentle breath,
Nature's scented tapestry embracing earth.
Harvest moons rise as evenings chill,
Fields of plenty paint every hill.
Sweaters wrapped tight as twilight nears---
Fall's embrace, warm as whispered years.
Pumpkins aglow with autumn's light,
Crackling leaves underfoot in flight.
In every leaf and breeze that calls,
We find the magic of glorious fall.
I hope these changes enhance the imagery and sensory experience. Thank you again for your feedback!
[Prompt tokens: 389, completion_tokens: 150]
---------- critic ----------
Your revisions have made the poem even more evocative and immersive. The use of sensory details, such as "whispers of wind" and "crackling leaves," beautifully enriches the poem, engaging multiple senses. The metaphorical language, like "a golden rain from trees' canopies" and "Fall's embrace, warm as whispered years," adds depth and enhances the emotional warmth of the poem. The structural variation with the inclusion of dashes effectively adds emphasis and flow.
Overall, these changes bring greater vibrancy and life to the poem, allowing readers to truly experience the wonders of fall. Excellent work on the revisions!
APPROVE
[Prompt tokens: 556, completion_tokens: 132]
---------- Summary ----------
Number of messages: 3
Finish reason: Text 'APPROVE' mentioned
Total prompt tokens: 1104
Total completion_tokens: 519
Duration: 9.79 seconds
TaskResult(messages=[TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=159, completion_to
三、Human-In-Loop:智能体与人类的协同智慧
(一)运行中提供反馈:即时互动优化结果
ini
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
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
# 创建智能体
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
user_proxy = UserProxyAgent("user_proxy", input_func=input)
# 创建终止条件,当用户说 "APPROVE" 时结束对话
termination = TextMentionTermination("APPROVE")
# 创建团队
team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination)
# 运行对话并流式输出到控制台
stream = team.run_stream(task="Write a 4-line poem about the ocean.")
# 使用 asyncio.run(...) 在脚本中运行
await Console(stream)
执行结果:
css
---------- user ----------
Write a 4-line poem about the ocean.
---------- assistant ----------
Waves whisper secrets to the shore's embrace,
A dance of blue under the sun's warm grace.
Endless horizons where dreams take flight,
The ocean's heart glimmers, a canvas of light.
TERMINATE
[Prompt tokens: 46, Completion tokens: 49]
---------- user_proxy ----------
APPROVE
---------- Summary ----------
Number of messages: 3
Finish reason: Text 'APPROVE' mentioned
Total prompt tokens: 46
Total completion tokens: 49
Duration: 6.64 seconds
TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Write a 4-line poem about the ocean.', type='TextMessage'), TextMessage(source='assistant', models_usage=RequestUsage(prompt_tokens=46, completion_tokens=49), content="Waves whisper secrets to the shore's embrace,
A dance of blue under the sun's warm grace.
Endless horizons where dreams take flight,
The ocean's heart glimmers, a canvas of light.
TERMINATE", type='TextMessage'), TextMessage(source='user_proxy', models_usage=None, content='APPROVE', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")
代码解读分析:
- 首先创建了一个
OpenAIChatCompletionClient
作为模型客户端,用于智能体与语言模型的交互。 - 接着定义了
AssistantAgent
作为主要的创作智能体,以及UserProxyAgent
作为用户反馈的代理。UserProxyAgent
的input_func
设置为input
,意味着它会在需要用户输入时从控制台获取用户的反馈。 TextMentionTermination("APPROVE")
作为终止条件,确保当用户输入 "APPROVE" 时,整个对话流程结束。- 在运行
team.run_stream(task="Write a 4-line poem about the ocean.")
时,智能体团队开始工作。AssistantAgent
首先生成了一首关于海洋的 4 行诗,然后由于设置了终止条件,系统等待UserProxyAgent
获取用户反馈。当用户在控制台输入 "APPROVE" 后,团队停止运行,整个过程展示了在智能体运行过程中快速引入人类反馈来决定任务是否继续或完成的机制,这种方式可以在一些需要简单判断或快速决策的场景中,利用人类的主观判断来优化智能体的输出结果。
(二)下次运行提供反馈:持续迭代提升性能
使用最大轮数
python
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
# 创建智能体
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
# 创建团队,设置最大轮数为 1
team = RoundRobinGroupChat([assistant], max_turns=1)
task = "Write a 4-line poem about the ocean."
while True:
# 运行对话并流式输出到控制台
stream = team.run_stream(task=task)
# 使用 asyncio.run(...) 在脚本中运行
await Console(stream)
# 获取用户响应
task = input("Enter your feedback (type 'exit' to leave): ")
if task.lower().strip() == "exit":
break
执行结果:
yaml
---------- user ----------
Write a 4-line poem about the ocean.
---------- assistant ----------
Endless waves in a dance with the shore,
Whispers of secrets in tales from the roar,
Beneath the vast sky, where horizons blend,
The ocean's embrace is a timeless friend.
TERMINATE
[Prompt tokens: 46, Completion tokens: 48]
---------- Summary ----------
Number of messages: 2
Finish reason: Maximum number of turns 1 reached.
Total prompt tokens: 46
Total completion tokens: 48
Duration: 1.63 seconds
---------- user ----------
Can you make it about a person and its relationship with the ocean
---------- assistant ----------
She walks along the tide, where dreams intertwine,
With every crashing wave, her heart feels aligned,
In the ocean's embrace, her worries dissolve,
A symphony of solace, where her spirit evolves.
TERMINATE
[Prompt tokens: 117, Completion tokens: 49]
---------- Summary ----------
Number of messages: 2
Finish reason: Maximum number of turns 1 reached.
Total prompt tokens: 117
Total completion tokens: 49
Duration: 1.21 seconds
代码解读分析:
- 同样先创建了模型客户端和
AssistantAgent
。 - 通过
RoundRobinGroupChat([assistant], max_turns=1)
创建了一个团队,并设置最大轮数为 1。这意味着每次智能体响应一次后,团队就会停止,等待用户反馈。 - 在循环中,首先运行任务 "Write a 4-line poem about the ocean.",智能体生成一首诗后,由于达到最大轮数停止。然后用户在控制台输入新的需求 "Can you make it about a person and its relationship with the ocean",再次运行团队时,智能体根据新的需求生成了新的诗歌。这种方式使得用户可以在智能体每一轮输出后进行干预和引导,逐步调整智能体的创作方向,实现持续迭代优化的效果,适用于需要与用户进行多轮交互来完善任务结果的场景。
使用终止条件
ini
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.base import Handoff
from autogen_agentchat.conditions import HandoffTermination, 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-4o-2024-08-06",
# api_key="sk-...", # 若已设置 OPENAI_API_KEY 环境变量则可选
)
# 创建一个总是将任务交接给用户的智能体
lazy_agent = AssistantAgent(
"lazy_assistant",
model_client=model_client,
handoffs=[Handoff(target="user", message="Transfer to user.")],
system_message="Always transfer to user when you don't know the answer. Respond 'TERMINATE' when task is complete."
)
# 定义终止条件,检查交接消息目标为用户和文本 "TERMINATE"
handoff_termination = HandoffTermination(target="user")
text_termination = TextMentionTermination("TERMINATE")
combined_termination = handoff_termination | text_termination
# 创建单智能体团队
lazy_agent_team = RoundRobinGroupChat([lazy_agent], termination_condition=combined_termination)
# 运行团队并流式输出到控制台
task = "What is the weather in New York?"
await Console(lazy_agent_team.run_stream(task=task))
执行结果:
css
---------- user ----------
What is the weather in New York?
---------- lazy_assistant ----------
[FunctionCall(id='call_nSjgvWCUYo5ccacBz7yzrPLN', arguments='{}', name='transfer_to_user')]
[Prompt tokens: 68, Completion tokens: 12]
---------- lazy_assistant ----------
[FunctionExecutionResult(content='Transfer to user.', call_id='call_nSjgvWCUYo5ccacBz7yzrPLN')]
---------- lazy_assistant ----------
Transfer to user.
---------- Summary ----------
Number of messages: 4
Finish reason: Handoff to user from lazy_assistant detected.
Total prompt tokens: 68
Total completion tokens: 12
Duration: 0.75 seconds
TaskResult(messages=[TextMessage(source='user', models_usage=None, content='What is the weather in New York?', type='TextMessage'), ToolCallRequestEvent(source='lazy_assistant', models_usage=RequestUsage(prompt_tokens=68, completion_tokens=12), content=[FunctionCall(id='call_nSjgvWCUYo5ccacBz7yzrPLN', arguments='{}', name='transfer_to_user')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='lazy_assistant', models_usage=None, content=[FunctionExecutionResult(content='Transfer to user.', call_id='call_nSjgvWCUYo5ccacBz7yzrPLN')], type='ToolCallExecutionEvent'), HandoffMessage(source='lazy_assistant', models_usage=None, target='user', content='Transfer to user.', type='HandoffMessage')], stop_reason='Handoff to user from lazy_assistant detected.')
继续运行:
ini
await Console(lazy_agent_team.run_stream(task="The weather in New York is sunny."))
执行结果:
css
---------- user ----------
The weather in New York is sunny.
---------- lazy_assistant ----------
Great to hear that it's sunny in New York! Is there anything else you'd like to know or discuss?
[Prompt tokens: 109, Completion tokens: 23]
---------- lazy_assistant ----------
TERMINATE
[Prompt tokens: 138, Completion tokens: 5]
---------- Summary ----------
Number of messages: 3
Finish reason: Text 'TERMINATE' mentioned
Total prompt tokens: 247
Total completion tokens: 28
Duration: 1.44 seconds
TaskResult(messages=[TextMessage(source='user', models_usage=None, content='The weather in New York is sunny.', type='TextMessage'), TextMessage(source='lazy_assistant', models_usage=RequestUsage(prompt_tokens=109, completion_tokens=23), content="Great to hear that it's sunny in New York! Is there anything else you'd like to know or discuss?", type='TextMessage'), TextMessage(source='lazy_assistant', models_usage=RequestUsage(prompt_tokens=138, completion_tokens=5), content='TERMINATE', type='TextMessage')], stop_reason="Text 'TERMINATE' mentioned")
代码解读分析:
- 首先创建模型客户端和一个特殊的
AssistantAgent
名为lazy_agent
,它的特点是当不知道答案时会通过handoffs
机制将任务交接给用户。 - 定义了
HandoffTermination
和TextMentionTermination
组合的终止条件,确保当智能体发出交接消息给用户或者提到 "TERMINATE" 时团队停止。 - 当运行查询纽约天气的任务时,由于智能体无法直接回答,它触发了交接机制,向用户发送了交接消息,团队停止。此时用户输入 "The weather in New York is sunny." 后再次运行团队,智能体根据用户提供的信息继续进行对话,展示了在智能体遇到知识瓶颈时,通过终止条件触发用户输入,然后继续任务的流程,这种机制增强了智能体系统的灵活性和对未知情况的处理能力。
四、终止条件:智能体运行的精准把控
ini
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
model_client = OpenAIChatCompletionClient(
model="gpt-4o",
temperature=1,
# 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 for every message. Respond with 'APPROVE' when your feedbacks are addressed."
)
max_msg_termination = MaxMessageTermination(max_messages=3)
round_robin_team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=max_msg_termination)
# 使用 asyncio.run(...) 如果作为独立脚本运行
await Console(round_robin_team.run_stream(task="Write a unique, Haiku about the weather in Paris"))
执行结果:
vbnet
---------- user ----------
Write a unique, Haiku about the weather in Paris
---------- primary ----------
Gentle rain whispers,
Cobblestones glisten softly---
Paris dreams in gray.
[Prompt tokens: 30, Completion tokens: 19]
---------- critic ----------
The Haiku captures the essence of a rainy day in Paris beautifully, and the imagery is vivid. However, it's important to ensure the use of the traditional 5-7-5 syllable structure for Haikus. Your current Haiku lines are composed of 4-7-5 syllables, which slightly deviates from the form. Consider revising the first line to fit the structure.
For example:
Soft rain whispers down,
Cobblestones glisten softly ---
Paris dreams in gray.
This revision maintains the essence of your original lines while adhering to the traditional Haiku structure.
[Prompt tokens: 70, Completion tokens: 120]
---------- Summary ----------
Number of messages: 3
Finish reason: Maximum number of messages 3 reached, current message count: 3
Total prompt tokens: 100
Total completion tokens: 139
Duration: 3.34 seconds
TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Write a unique, Haiku about the weather in Paris'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=30, completion_tokens=19), content='Gentle rain whispers,
Cobblestones glisten softly---
Paris dreams in gray.'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=70, completion_tokens=120), content="The Haiku captures the essence of a rainy day in Paris beautifully, and the imagery is vivid. However, it's important to ensure the use of the traditional 5-7-5 syllable structure for Haikus. Your current Haiku lines are composed of 4-7-5 syllables, which slightly deviates from the form. Consider revising the first line to fit the structure.
For example:
Soft rain whispers down,
Cobblestones glisten softly ---
Paris dreams in gray.
This revision maintains the essence of your original lines while adhering to the traditional Haiku structure.")], stop_reason='Maximum number of messages 3 reached, current message count: 3')
继续运行:
scss
# 使用 asyncio.run(...) 如果作为独立脚本运行
await Console(round_robin_team.run_stream())
执行结果:
yaml
---------- primary ----------
Thank you for your feedback. Here is the revised Haiku:
Soft rain whispers down,
Cobblestones glisten softly ---
Paris dreams in gray.
[Prompt tokens: 181, Completion tokens: 32]
---------- critic ----------
The revised Haiku now follows the traditional 5-7-5 syllable pattern, and it still beautifully captures the atmospheric mood of Paris in the rain. The imagery and flow are both clear and evocative. Well done on making the adjustment!
APPROVE
[Prompt tokens: 234, Completion tokens: 54]
---------- primary ----------
Thank you for your kind words and approval. I'm glad the revision meets your expectations and captures the essence of Paris. If you have any more requests or need further assistance, feel free to ask!
[Prompt tokens: 279, Completion tokens: 39]
---------- Summary ----------
Number of messages: 3
Finish reason: Maximum number of messages 3 reached, current message count: 3
Total prompt tokens: 694
Total completion_tokens: 125
Duration: 6.43 seconds
TaskResult(messages=[TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=181, completion_tokens=32), content='Thank you for your feedback. Here is the revised Haiku:
Soft rain whispers down,
Cobblestones glisten softly ---
五、总结
AutoGen 的智能体团队协作机制在人工智能领域展现出了独特的技术魅力与巨大的应用潜力,其背后蕴含着多方面的深度技术洞察。
从技术架构角度看,RoundRobinGroupChat
等团队组织形式构建了一个高效的信息交互网络。在这个网络中,智能体之间通过共享上下文和轮流响应机制,实现了信息的快速传播与协同处理。这种架构设计降低了智能体之间的通信复杂度,使得每个智能体能够在统一的任务框架下发挥各自的专长,避免了信息孤岛的出现,从而提高了整个团队解决复杂问题的能力。例如在诗歌创作和内容评估的任务中,不同智能体能够紧密协作,逐步优化输出结果,体现了这种架构在促进多智能体协同工作方面的有效性。
终止条件的设计则为智能体团队运行提供了精确的控制逻辑。多种内置终止条件如 MaxMessageTermination
、TextMentionTermination
等,不仅可以单独使用来满足简单的任务停止需求,更重要的是通过逻辑运算符组合后,能够应对复杂多变的任务场景。这类似于构建一个精细的任务调度器,根据任务的进展、资源消耗、内容特征等多维度因素动态地决定任务的持续或终止,确保系统在高效运行的同时保持良好的稳定性和可控性。
在人类参与循环方面,UserProxyAgent
以及相关的反馈机制巧妙地融合了人类智慧与智能体的能力。在运行中提供反馈的方式,虽然存在阻塞团队执行的风险,但在某些需要即时人类判断的场景下,如简单的创意审核或快速决策任务,能够迅速引入人类的主观认知和经验,纠正智能体可能出现的偏差或进一步优化结果。而在下次运行提供反馈的模式中,通过设置最大轮数或特定终止条件,实现了智能体与人类之间的迭代式交互,使得任务处理过程能够不断吸收人类的反馈信息,逐步趋近于最优解,这在处理复杂的、需要深度人类理解的任务时尤为关键。