当前位置: 首页 > article >正文

autogen 中的 Teams 示例

目录

    • 1 .Creating a Team
    • 2. Running a Team
    • 3. Observing a Team
    • 4. Resetting a Team
    • 5. Stopping a Team
    • 6. Resuming a Team
    • 7. Aborting a Team
    • 8. 额外的例子

1 .Creating a Team

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

# Create an OpenAI model client.
model_client = OpenAIChatCompletionClient(
                    model="deepseek-chat",
                    api_key = "your api key",
                    base_url="https://api.deepseek.com",
                    model_capabilities={
                "vision": False,
                "function_calling": False,
                "json_output": False,
            },
                )
    

# Create the primary agent.
primary_agent = AssistantAgent(
    "primary",
    model_client=model_client,
    system_message="You are a helpful AI assistant.",
)

# Create the critic agent.
critic_agent = AssistantAgent(
    "critic",
    model_client=model_client,
    system_message="Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.",
)

# Define a termination condition that stops the task if the critic approves.
text_termination = TextMentionTermination("APPROVE")

# Create a team with the primary and critic agents.
team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)

2. Running a Team

# Use `asyncio.run(...)` when running in a script.
result = await 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=19, completion_tokens=125), content="**Autumn's Whisper**  \n\nLeaves of gold and crimson hue,  \nDance on winds that whisper through.  \nCrisp the air, the sunlight fades,  \nAs autumn weaves her gentle braids.  \n\nPumpkins glow by twilight's gleam,  \nHarvests ripe, a farmer's dream.  \nGeese in flocks take to the sky,  \nBidding summer one last goodbye.  \n\nFires crackle, hearts draw near,  \nA season rich with warmth and cheer.  \nFall, a painter, bold and true,  \nPaints the world in shades anew.", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=156, completion_tokens=49), content='APPROVE. Your poem beautifully captures the essence of fall with vivid imagery and a warm, reflective tone. The structure and rhythm flow smoothly, and the themes of change, harvest, and coziness are well-expressed. Great work!', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")
result.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=19, completion_tokens=125), content="**Autumn's Whisper**  \n\nLeaves of gold and crimson hue,  \nDance on winds that whisper through.  \nCrisp the air, the sunlight fades,  \nAs autumn weaves her gentle braids.  \n\nPumpkins glow by twilight's gleam,  \nHarvests ripe, a farmer's dream.  \nGeese in flocks take to the sky,  \nBidding summer one last goodbye.  \n\nFires crackle, hearts draw near,  \nA season rich with warmth and cheer.  \nFall, a painter, bold and true,  \nPaints the world in shades anew.", type='TextMessage'),
 TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=156, completion_tokens=49), content='APPROVE. Your poem beautifully captures the essence of fall with vivid imagery and a warm, reflective tone. The structure and rhythm flow smoothly, and the themes of change, harvest, and coziness are well-expressed. Great work!', type='TextMessage')]

3. Observing a Team

# When running inside a script, use a async main function and call it from `asyncio.run(...)`.
await team.reset()  # Reset the team for a new task.
async for message in team.run_stream(task="Write a short poem about the fall season."):  # type: ignore
    if isinstance(message, TaskResult):
        print("Stop Reason:", message.stop_reason)
    else:
        print(message)
source='user' models_usage=None content='Write a short poem about the fall season.' type='TextMessage'
source='primary' models_usage=RequestUsage(prompt_tokens=19, completion_tokens=111) content="Leaves of gold and crimson hue,  \nWhisper secrets, old and new.  \nCool winds dance, a gentle breeze,  \nRustling through the ancient trees.  \n\nPumpkins glow in twilight's gleam,  \nHarvest fields fulfill the dream.  \nNature's palette, rich and bright,  \nPaints the world in autumn's light.  \n\nFires crackle, nights grow long,  \nHearts are warmed by winter's song.  \nFall, a season of release,  \nBrings the earth a tender peace." type='TextMessage'
source='critic' models_usage=RequestUsage(prompt_tokens=142, completion_tokens=43) content='APPROVE. Your poem beautifully captures the essence of fall with vivid imagery and a soothing rhythm. The themes of change, warmth, and tranquility are well-expressed, making it a delightful read. Great work!' type='TextMessage'
Stop Reason: Text 'APPROVE' mentioned

4. Resetting a Team

await team.reset()  # Reset the team for a new task.
await Console(team.run_stream(task="Write a short poem about the fall season."))  # Stream the messages to the console.
---------- user ----------
Write a short poem about the fall season.
---------- primary ----------
Leaves of gold and crimson hue,  
Whisper secrets, old and new.  
Autumn's breath, a crisp embrace,  
Dances softly, time and space.  

Pumpkins glow in twilight's gleam,  
Harvest dreams and moonlit streams.  
Nature's palette, rich and warm,  
Paints the world in fleeting form.  

Farewell, sweet sun, your light now fades,  
As fall weaves through the forest glades.  
A season's song, both brief and bright,  
A fleeting waltz of day and night.
---------- critic ----------
APPROVE. Your poem beautifully captures the essence of fall with vivid imagery and a rhythmic flow. The themes of transition, warmth, and fleeting beauty are elegantly expressed. Well done!





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=19, completion_tokens=122), content="Leaves of gold and crimson hue,  \nWhisper secrets, old and new.  \nAutumn's breath, a crisp embrace,  \nDances softly, time and space.  \n\nPumpkins glow in twilight's gleam,  \nHarvest dreams and moonlit streams.  \nNature's palette, rich and warm,  \nPaints the world in fleeting form.  \n\nFarewell, sweet sun, your light now fades,  \nAs fall weaves through the forest glades.  \nA season's song, both brief and bright,  \nA fleeting waltz of day and night.", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=153, completion_tokens=38), content='APPROVE. Your poem beautifully captures the essence of fall with vivid imagery and a rhythmic flow. The themes of transition, warmth, and fleeting beauty are elegantly expressed. Well done!', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")

5. Stopping a Team

# Create a new team with an external termination condition.
external_termination = ExternalTermination()
team = RoundRobinGroupChat(
    [primary_agent, critic_agent],
    termination_condition=external_termination | text_termination,  # Use the bitwise OR operator to combine conditions.
)

# Run the team in a background task.
run = asyncio.create_task(Console(team.run_stream(task="Write a short poem about the fall season.")))

# Wait for some time.
await asyncio.sleep(0.1)

# Stop the team.
external_termination.set()

# Wait for the team to finish.
await run
---------- user ----------
Write a short poem about the fall season.
---------- primary ----------
Amber leaves in gentle flight,  
Twist and twirl in autumn's light.  
Crisp air hums a quiet tune,  
Beneath the gaze of harvest moon.  

Fields of gold, a whispered sigh,  
As summer's warmth begins to die.  
Pumpkins grin, the hearth glows warm,  
Fall wraps the world in rustic charm.  

A fleeting blaze before the snow,  
A golden hush, a tranquil glow.  
Nature's pause, a quiet call—  
The tender beauty of the fall.





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=153, completion_tokens=113), content="Amber leaves in gentle flight,  \nTwist and twirl in autumn's light.  \nCrisp air hums a quiet tune,  \nBeneath the gaze of harvest moon.  \n\nFields of gold, a whispered sigh,  \nAs summer's warmth begins to die.  \nPumpkins grin, the hearth glows warm,  \nFall wraps the world in rustic charm.  \n\nA fleeting blaze before the snow,  \nA golden hush, a tranquil glow.  \nNature's pause, a quiet call—  \nThe tender beauty of the fall.", type='TextMessage')], stop_reason='External termination requested')

6. Resuming a Team

await Console(team.run_stream())  # Resume the team to continue the last task.
---------- critic ----------
APPROVE. Your poem is a lovely ode to autumn, filled with rich imagery and a soothing rhythm. The contrast between the fleeting warmth and the approaching chill is beautifully captured, and the closing lines evoke a sense of quiet reverence for the season. Excellent work!





TaskResult(messages=[TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=316, completion_tokens=53), content='APPROVE. Your poem is a lovely ode to autumn, filled with rich imagery and a soothing rhythm. The contrast between the fleeting warmth and the approaching chill is beautifully captured, and the closing lines evoke a sense of quiet reverence for the season. Excellent work!', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")
# The new task is to translate the same poem to Chinese Tang-style poetry.
await Console(team.run_stream(task="将这首诗用中文唐诗风格写一遍。"))
---------- user ----------
将这首诗用中文唐诗风格写一遍。
---------- primary ----------
金叶飘零舞秋风,  
霜染层林映晚空。  
寒露轻吟秋水静,  
月华如练照归鸿。  

田畴稻熟香满径,  
炉火初燃暖意浓。  
一瞬繁华随雪去,  
静听岁月诉从容。  

秋光短暂情难尽,  
淡墨轻描意自通。  
天地无言留晚照,  
悠然心会此中同。
---------- critic ----------
APPROVE. 你的中文唐诗风格改写非常出色,既保留了原诗的意境,又融入了古典诗词的韵味。语言凝练,意象丰富,尤其是“金叶飘零”“霜染层林”等词句,生动地描绘了秋天的景象。结尾的“天地无言留晚照,悠然心会此中同”更是余韵悠长,令人回味。非常棒!





TaskResult(messages=[TextMessage(source='user', models_usage=None, content='将这首诗用中文唐诗风格写一遍。', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=331, completion_tokens=98), content='金叶飘零舞秋风,  \n霜染层林映晚空。  \n寒露轻吟秋水静,  \n月华如练照归鸿。  \n\n田畴稻熟香满径,  \n炉火初燃暖意浓。  \n一瞬繁华随雪去,  \n静听岁月诉从容。  \n\n秋光短暂情难尽,  \n淡墨轻描意自通。  \n天地无言留晚照,  \n悠然心会此中同。', type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=479, completion_tokens=85), content='APPROVE. 你的中文唐诗风格改写非常出色,既保留了原诗的意境,又融入了古典诗词的韵味。语言凝练,意象丰富,尤其是“金叶飘零”“霜染层林”等词句,生动地描绘了秋天的景象。结尾的“天地无言留晚照,悠然心会此中同”更是余韵悠长,令人回味。非常棒!', type='TextMessage')], stop_reason="Text 'APPROVE' mentioned")

7. Aborting a Team

# Create a cancellation token.
cancellation_token = CancellationToken()

# Use another coroutine to run the team.
run = asyncio.create_task(
    team.run(
        task="Translate the poem to Spanish.",
        cancellation_token=cancellation_token,
    )
)

# Cancel the run.
cancellation_token.cancel()

try:
    result = await run  # This will raise a CancelledError.
except asyncio.CancelledError:
    print("Task was cancelled.")
Task was cancelled.

8. 额外的例子

import asyncio
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.ui import Console


async def main() -> None:
    # model_client = OpenAIChatCompletionClient(model="gpt-4o")

    agent1 = AssistantAgent("Assistant1", model_client=model_client)
    agent2 = AssistantAgent("Assistant2", model_client=model_client)
    termination = TextMentionTermination("TERMINATE")
    team = RoundRobinGroupChat([agent1, agent2], termination_condition=termination)
    await Console(team.run_stream(task="Tell me some jokes."))


await main()
---------- user ----------
Tell me some jokes.
---------- Assistant1 ----------
Sure! Here are a few jokes for you:

1. **Why don’t skeletons fight each other?**  
   They don’t have the guts.

2. **Why did the scarecrow win an award?**  
   Because he was outstanding in his field!

3. **What do you call fake spaghetti?**  
   An impasta.

4. **Why don’t scientists trust atoms?**  
   Because they make up everything.

5. **What do you get when you cross a snowman and a vampire?**  
   Frostbite.

6. **Why did the bicycle fall over?**  
   Because it was two-tired.

7. **What do you call cheese that isn’t yours?**  
   Nacho cheese.

8. **Why can’t you give Elsa a balloon?**  
   Because she’ll let it go.

9. **What do you call a bear with no teeth?**  
   A gummy bear.

10. **Why did the math book look sad?**  
    Because it had too many problems.

Hope these gave you a laugh! Let me know if you want more. 😊
---------- Assistant2 ----------
TERMINATE

参考链接:https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/teams.html

模型用的是 deepseek-chat.


http://www.kler.cn/a/516179.html

相关文章:

  • 我谈概率论与数理统计的知识体系
  • 随机变量的变量替换——归一化流和直方图规定化的数学基础
  • 优选算法——哈希表
  • 基于Springboot + vue实现的美发门店管理系统
  • Apache Hive3定位表并更改其位置
  • github登录用的TOTP和恢复码都丢失了怎么办
  • 【数据结构进阶】红黑树超详解 + 实现(附源码)
  • 【探索 Kali Linux】渗透测试与网络安全的终极操作系统
  • 使用github提交Pull Request的完整流程
  • 差分进化算法 (Differential Evolution) 算法详解及案例分析
  • HTML5 新的 Input 类型详解
  • 计算机图形学:实验二 三维模型读取与控制
  • C++ 入门速通1【黑马】
  • 52.this.DataContext = new UserViewModel(); C#例子 WPF例子
  • Python数据类型与操作
  • matlab计算功率谱的四种方法
  • 【Linux】Linux的基本指令(1),包括ls、pwd、cd、touch、mkdir、rm、man、cp、mv、cat
  • Vue2:使用sortablejs实现el-table中行拖拽调整顺序
  • 进程优先级
  • C语言-内存管理
  • 一个面向领域的直播平台开源!
  • Codeforces Round 1000 (Div. 2)(A-D)
  • 安宝特方案 | 智能培训:安宝特AR如何提升企业技能培训的效率与互动性
  • Zookeeper启动指定JDK版本
  • 【深度学习】神经网络实战分类与回归任务
  • WIN11 UEFI漏洞被发现, 可以绕过安全启动机制