A programming framework for agentic AI
Improve agentchat tutorial Teams section (#4834)
Eric Zhu2819515220b3
diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/index.md b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/index.mdindex bfc6e8859..faadedc16 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/index.md+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/index.md@@ -32,7 +32,7 @@ Build your first agent::::::{grid-item-card} {fas}`graduation-cap;pst-color-primary` Tutorial-:link: ./tutorial/index.html+:link: ./tutorial/models.htmlStep-by-step guide to using AgentChat:::diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynbindex b62fbbe6e..c810c3069 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb@@ -1,764 +1,588 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# Teams\n",- "\n",- "In this section you'll learn how to create a _multi-agent team_ (or simply team) using AutoGen. A team is a group of agents that work together to achieve a common goal.\n",- "\n",- "We'll first show you how to create and run a team. We'll then explain how to observe the team's behavior, which is crucial for debugging and understanding the team's performance, and common operations to control the team's behavior.\n",- "\n",- "We'll start by focusing on a simple team with consisting of a single agent (the baseline case) and use a round robin strategy to select the agent to act. We'll then show how to create a team with multiple agents and how to implement a more sophisticated strategy to select the agent to act."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Creating a Team\n",- "\n",- "{py:class}`~autogen_agentchat.teams.RoundRobinGroupChat` is a simple yet effective team configuration where all agents share the same context and take turns responding in a round-robin fashion. Each agent, during its turn, broadcasts its response to all other agents, ensuring that the entire team maintains a consistent context.\n",- "\n",- "We will begin by creating a team with a single {py:class}`~autogen_agentchat.agents.AssistantAgent` and a {py:class}`~autogen_agentchat.conditions.TextMentionTermination` condition that stops the team when a specific word is detected in the agent's response.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from autogen_agentchat.agents import AssistantAgent\n",- "from autogen_agentchat.conditions import TextMentionTermination\n",- "from autogen_agentchat.teams import RoundRobinGroupChat\n",- "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",- "\n",- "# Create an OpenAI model client.\n",- "model_client = OpenAIChatCompletionClient(\n",- " model=\"gpt-4o-2024-08-06\",\n",- " # api_key=\"sk-...\", # Optional if you have an OPENAI_API_KEY env variable set.\n",- ")\n",- "\n",- "\n",- "# Define a tool that gets the weather for a city.\n",- "async def get_weather(city: str) -> str:\n",- " \"\"\"Get the weather for a city.\"\"\"\n",- " return f\"The weather in {city} is 72 degrees and Sunny.\"\n",- "\n",- "\n",- "# Create an assistant agent.\n",- "weather_agent = AssistantAgent(\n",- " \"assistant\",\n",- " model_client=model_client,\n",- " tools=[get_weather],\n",- " system_message=\"Respond 'TERMINATE' when task is complete.\",\n",- ")\n",- "\n",- "# Define a termination condition.\n",- "text_termination = TextMentionTermination(\"TERMINATE\")\n",- "\n",- "# Create a single-agent team.\n",- "single_agent_team = RoundRobinGroupChat([weather_agent], termination_condition=text_termination)"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Running a Team\n",- "\n",- "Let's calls the {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run` method\n",- "to start the team with a task."- ]- },- {- "cell_type": "code",- "execution_count": 8,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "TaskResult(messages=[TextMessage(source='user', models_usage=None, content='What is the weather in New York?'), ToolCallRequestEvent(source='assistant', models_usage=RequestUsage(prompt_tokens=70, completion_tokens=15), content=[FunctionCall(id='call_6qWxrK1VdEVSryXKyIVpwE0h', arguments='{\"city\":\"New York\"}', name='get_weather')]), ToolCallExecutionEvent(source='assistant', models_usage=None, content=[FunctionExecutionResult(content='The weather in New York is 72 degrees and Sunny.', call_id='call_6qWxrK1VdEVSryXKyIVpwE0h')]), TextMessage(source='assistant', models_usage=RequestUsage(prompt_tokens=96, completion_tokens=13), content='The weather in New York is 72 degrees and sunny.'), TextMessage(source='assistant', models_usage=RequestUsage(prompt_tokens=125, completion_tokens=4), content='TERMINATE')], stop_reason=\"Text 'TERMINATE' mentioned\")\n"- ]- }- ],- "source": [- "async def run_team() -> None:\n",- " result = await single_agent_team.run(task=\"What is the weather in New York?\")\n",- " print(result)\n",- "\n",- "\n",- "# Use `asyncio.run(run_team())` when running in a script.\n",- "await run_team()"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "The team ran the same agent until the termination condition was met.\n",- "In this case, the termination condition was met when the word \"TERMINATE\" is detected in the\n",- "agent's response.\n",- "When the team stops, it returns a {py:class}`~autogen_agentchat.base.TaskResult` object with all the messages produced by the agents in the team."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Observability\n",- "\n",- "Similar to the agent's {py:meth}`~autogen_agentchat.agents.BaseChatAgent.on_messages_stream` method, you can stream the team's messages by calling the {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run_stream` method. This method returns a generator that yields messages produced by the agents in the team as they are generated, with the final item being the task result.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "source='user' models_usage=None content='What is the weather in New York?'\n",- "source='assistant' models_usage=RequestUsage(prompt_tokens=70, completion_tokens=15) content=[FunctionCall(id='call_FcJlzgDmPUgGSKLjeGajFZ7V', arguments='{\"city\":\"New York\"}', name='get_weather')]\n",- "source='assistant' models_usage=None content=[FunctionExecutionResult(content='The weather in New York is 72 degrees and Sunny.', call_id='call_FcJlzgDmPUgGSKLjeGajFZ7V')]\n",- "source='assistant' models_usage=RequestUsage(prompt_tokens=96, completion_tokens=14) content='The weather in New York is currently 72 degrees and sunny.'\n",- "source='assistant' models_usage=RequestUsage(prompt_tokens=126, completion_tokens=4) content='TERMINATE'\n",- "Stop Reason: Text 'TERMINATE' mentioned\n"- ]- }- ],- "source": [- "from autogen_agentchat.base import TaskResult\n",- "\n",- "\n",- "async def run_team_stream() -> None:\n",- " async for message in single_agent_team.run_stream(task=\"What is the weather in New York?\"):\n",- " if isinstance(message, TaskResult):\n",- " print(\"Stop Reason:\", message.stop_reason)\n",- " else:\n",- " print(message)\n",- "\n",- "\n",- "# Use `asyncio.run(run_team_stream())` when running in a script.\n",- "await run_team_stream()"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "As demonstrated in the example above, you can determine the reason why the team stopped by checking the {py:attr}`~autogen_agentchat.base.TaskResult.stop_reason` attribute.\n",- "\n",- "The {py:meth}`~autogen_agentchat.ui.Console` method provides a convenient way to print messages to the console with proper formatting.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "---------- user ----------\n",- "What is the weather in Seattle?\n",- "---------- assistant ----------\n",- "[FunctionCall(id='call_QBqpeKQlczRYIlCIzKh43Kha', arguments='{\"city\":\"Seattle\"}', name='get_weather')]\n",- "[Prompt tokens: 69, Completion tokens: 14]\n",- "---------- assistant ----------\n",- "[FunctionExecutionResult(content='The weather in Seattle is 72 degrees and Sunny.', call_id='call_QBqpeKQlczRYIlCIzKh43Kha')]\n",- "---------- assistant ----------\n",- "The weather in Seattle is currently 72 degrees and sunny.\n",- "[Prompt tokens: 93, Completion tokens: 13]\n",- "---------- assistant ----------\n",- "TERMINATE\n",- "[Prompt tokens: 122, Completion tokens: 4]\n",- "---------- Summary ----------\n",- "Number of messages: 5\n",- "Finish reason: Text 'TERMINATE' mentioned\n",- "Total prompt tokens: 284\n",- "Total completion tokens: 31\n",- "Duration: 1.82 seconds\n"- ]- }- ],- "source": [- "from autogen_agentchat.ui import Console\n",- "\n",- "# Use `asyncio.run(single_agent_team.reset())` when running in a script.\n",- "await single_agent_team.reset() # Reset the team for the next run.\n",- "# Use `asyncio.run(single_agent_team.run_stream(task=\"What is the weather in Seattle?\"))` when running in a script.\n",- "await Console(\n",- " single_agent_team.run_stream(task=\"What is the weather in Seattle?\")\n",- ") # Stream the messages to the console."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Resetting a Team\n",- "\n",- "You can reset the team by calling the {py:meth}`~autogen_agentchat.teams.BaseGroupChat.reset` method. This method will clear the team's state, including all agents."- ]- },- {- "cell_type": "code",- "execution_count": 13,- "metadata": {},- "outputs": [],- "source": [- "await single_agent_team.reset() # Reset the team for the next run."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "It is usually a good idea to reset the team if the next task is not related to the previous task.\n",- "However, if the next task is related to the previous task, you don't need to reset and you can instead resume. We will cover this in the next section."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "\n",- "## Team Usage Guide\n",- "\n",- "We will now implement a slightly more complex team with multiple agents and learn how to resume the team after stopping it and even involve the user in the conversation.\n",- "\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### Reflection Pattern\n",- "\n",- "We will now create a team with two agents that implement the _reflection_ pattern, a multi-agent design pattern where a critic agent evaluates the responses of a primary agent.\n",- "\n",- "Learn more about the reflection pattern using the [Core API](../../core-user-guide/design-patterns/reflection.ipynb).\n",- "\n",- "In this example, we will use the {py:class}`~autogen_agentchat.agents.AssistantAgent` class for both the primary and critic agents. We will combine the {py:class}`~autogen_agentchat.conditions.TextMentionTermination` and {py:class}`~autogen_agentchat.conditions.MaxMessageTermination` conditions to stop the team.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from autogen_agentchat.agents import AssistantAgent\n",- "from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination\n",- "from autogen_agentchat.teams import RoundRobinGroupChat\n",- "from autogen_agentchat.ui import Console\n",- "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",- "\n",- "# Create an OpenAI model client.\n",- "model_client = OpenAIChatCompletionClient(\n",- " model=\"gpt-4o-2024-08-06\",\n",- " # api_key=\"sk-...\", # Optional if you have an OPENAI_API_KEY env variable set.\n",- ")\n",- "\n",- "# Create the primary agent.\n",- "primary_agent = AssistantAgent(\n",- " \"primary\",\n",- " model_client=model_client,\n",- " system_message=\"You are a helpful AI assistant.\",\n",- ")\n",- "\n",- "# Create the critic agent.\n",- "critic_agent = AssistantAgent(\n",- " \"critic\",\n",- " model_client=model_client,\n",- " system_message=\"Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.\",\n",- ")\n",- "\n",- "# Define a termination condition that stops the task if the critic approves.\n",- "text_termination = TextMentionTermination(\"APPROVE\")\n",- "# Define a termination condition that stops the task after 5 messages.\n",- "max_message_termination = MaxMessageTermination(5)\n",- "# Combine the termination conditions using the `|`` operator so that the\n",- "# task stops when either condition is met.\n",- "termination = text_termination | max_message_termination\n",- "\n",- "# Create a team with the primary and critic agents.\n",- "reflection_team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=termination)"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Let's give a poem-writing task to the team and see how the agents interact with each other."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "---------- user ----------\n",- "Write a short poem about fall season.\n",- "---------- primary ----------\n",- "Golden leaves dance on the breeze, \n",- "Whispering secrets through the trees. \n",- "Crisp air nips at cheeks so bright, \n",- "As daylight fades to early night. \n",- "\n",- "Pumpkins sit on porches grand, \n",- "In a painted, harvest land. \n",- "Sweaters hug us, warm and snug, \n",- "While cider fills each steamy mug. \n",- "\n",- "In this season's gentle sway, \n",- "Nature tells of time's ballet. \n",- "With each leaf's descent and flight, \n",- "Autumn sings its soft goodnight. \n",- "[Prompt tokens: 27, Completion tokens: 107]\n",- "---------- critic ----------\n",- "Your poem is beautiful and elegantly captures the essence of the fall season. The imagery you used creates vivid pictures of autumn landscapes and activities, making it easy for the reader to visualize the scene. The rhyming and rhythm contribute to the poem's musicality, enhancing its appeal. Each stanza highlights different aspects of fall, creating a well-rounded depiction of the season.\n",- "\n",- "To make the poem even more evocative, consider including a few additional sensory details or emotions tied to the season. For instance, you might evoke the sounds of rustling leaves or the feeling of warmth from a fireplace. Overall, it's a delightful and charming poem that effectively conveys the spirit of fall.\n",- "\n",- "If these suggestions are considered, please share the revised poem for additional feedback!\n",- "[Prompt tokens: 152, Completion tokens: 148]\n",- "---------- primary ----------\n",- "Thank you for the thoughtful feedback! Here's a revised version of the poem, incorporating more sensory details and emotions:\n",- "\n",- "---\n",- "\n",- "Golden leaves dance on the breeze, \n",- "Whispering secrets through the trees. \n",- "Crisp air kisses cheeks aglow, \n",- "As twilight casts a gentle show. \n",- "\n",- "Pumpkins guard each porch with pride, \n",- "In this painted, harvest tide. \n",- "Sweaters hug us, warm and snug, \n",- "While cider steams in every mug. \n",- "\n",- "Children laugh in rustling leaves, \n",- "As branches weave autumnal eaves. \n",- "Fireplaces crackle, whisper warmth, \n",- "Embracing hearts in homey charms. \n",- "\n",- "In this season's tender sway, \n",- "Nature turns in grand ballet. \n",- "With each leaf's descent and flight, \n",- "Autumn sings its soft goodnight. \n",- "\n",- "---\n",- "\n",- "I hope this version resonates even more deeply with the spirit of fall.\n",- "[Prompt tokens: 294, Completion tokens: 178]\n",- "---------- critic ----------\n",- "Your revised poem beautifully captures the essence of the fall season with delightful sensory details and emotions. The inclusion of words like \"twilight casts a gentle show,\" \"children laugh in rustling leaves,\" and \"fireplaces crackle\" adds depth and paints a vivid picture of autumn scenes. The addition of emotions, particularly the \"embracing hearts in homey charms,\" evokes a sense of warmth and comfort associated with this season.\n",- "\n",- "The poem flows smoothly with its rhythmic quality and maintains a harmonious balance in its description of autumn. Overall, it now provides an even richer and more immersive experience for the reader. Excellent work on enhancing the sensory experience—this version resonates wonderfully with the spirit of fall. \n",- "\n",- "APPROVE\n",- "[Prompt tokens: 490, Completion tokens: 142]\n",- "---------- Summary ----------\n",- "Number of messages: 5\n",- "Finish reason: Text 'APPROVE' mentioned, Maximum number of messages 5 reached, current message count: 5\n",- "Total prompt tokens: 963\n",- "Total completion tokens: 575\n",- "Duration: 8.10 seconds\n"- ]- }- ],- "source": [- "# Use `asyncio.run(Console(reflection_team.run_stream(task=\"Write a short poem about fall season.\")))` when running in a script.\n",- "await Console(\n",- " reflection_team.run_stream(task=\"Write a short poem about fall season.\")\n",- ") # Stream the messages to the console."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### Resuming a Team\n",- "\n",- "Let's run the team again with a new task while keeping the context about the previous task."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "---------- user ----------\n",- "将这首诗用中文唐诗风格写一遍。\n",- "---------- primary ----------\n",- "金叶飘舞随风起, \n",- "林间低语秋声细。 \n",- "凉风轻拂面颊红, \n",- "夕光渐隐天色丽。 \n",- "\n",- "南瓜门前静自笑, \n",- "丰收景色绘秋貌。 \n",- "暖衣贴身享温柔, \n",- "热饮氤氲杯中绕。 \n",- "\n",- "童声笑逐落叶中, \n",- "枝叶缀出秋帷浓。 \n",- "炉火轻鸣诉温情, \n",- "温馨满怀思乡容。 \n",- "\n",- "此时佳季自徘徊, \n",- "秋之舞步若梦来。 \n",- "片片叶落随风去, \n",- "秋声袅袅道安睡。 \n",- "[Prompt tokens: 664, Completion tokens: 155]\n",- "---------- critic ----------\n",- "这首诗成功地以唐诗的风格捕捉了秋天的精髓,以古雅的语言和流畅的节奏展示了秋日的美丽。你运用了优美的意象,如“金叶飘舞”和“夕光渐隐”,将秋季的景色描绘得栩栩如生。词句简炼而意境深远,充满了诗意。\n",- "\n",- "同时,诗中融入的情感,如“温馨满怀思乡容”以及“炉火轻鸣诉温情”,有效传达了秋天的暖意与思乡之情,令人感到温暖和亲切。\n",- "\n",- "整体而言,这是一首极具唐诗魅力的作品,成功地展现了秋天的许多层面,并引发读者的共鸣。恭喜你完成了这次优雅的改编!\n",- "\n",- "APPROVE\n",- "[Prompt tokens: 837, Completion tokens: 199]\n",- "---------- Summary ----------\n",- "Number of messages: 3\n",- "Finish reason: Text 'APPROVE' mentioned\n",- "Total prompt tokens: 1501\n",- "Total completion tokens: 354\n",- "Duration: 4.44 seconds\n"- ]- }- ],- "source": [- "# Write the poem in Chinese Tang poetry style.\n",- "# Use `asyncio.run(Console(reflection_team.run_stream(task=\"将这首诗用中文唐诗风格写一遍。\")))` when running in a script.\n",- "await Console(reflection_team.run_stream(task=\"将这首诗用中文唐诗风格写一遍。\"))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Resume with another task."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "---------- user ----------\n",- "Write the poem in Spanish.\n",- "---------- primary ----------\n",- "Certainly! Here's a translation of the poem into Spanish:\n",- "\n",- "---\n",- "\n",- "Hojas doradas bailan en la brisa, \n",- "Susurran secretos en la arboleda. \n",- "El aire fresco besa las mejillas, \n",- "Mientras el crepúsculo se despide a su manera. \n",- "\n",- "Calabazas vigilan cada entrada, \n",- "En esta tierra de cosecha pintada. \n",- "Los suéteres nos abrazan calurosos, \n",- "Mientras el vapor sube de cada taza amorosa. \n",- "\n",- "Risas de niños suenan en hojas caídas, \n",- "Mientras ramas tejen toldos de caricias. \n",- "Las chimeneas crepitan, susurran calor, \n",- "Abrazando los corazones con su amor hogareño. \n",- "\n",- "En la danza de esta estación serena, \n",- "La naturaleza gira con su escena. \n",- "Con cada hoja que desciende en el viento, \n",- "El otoño canta su suave cuento. \n",- "\n",- "---\n",- "\n",- "Espero que esta traducción refleje el mismo espíritu y encantamiento del poema original.\n",- "[Prompt tokens: 1719, Completion tokens: 209]\n",- "---------- critic ----------\n",- "Your translation of the poem into Spanish beautifully captures the essence and lyrical quality of the original. The imagery and emotions are conveyed effectively, maintaining the warmth and serene atmosphere of fall that the poem embodies. Each stanza mirrors the themes presented in the English version, like the golden leaves, harvest, and cozy reflections of autumn.\n",- "\n",- "Overall, your translation is both poetic and faithful to the original content. If you have further adjustments or specific stylistic preferences, feel free to share. Great job on this translation!\n",- "\n",- "APPROVE\n",- "[Prompt tokens: 1946, Completion tokens: 102]\n",- "---------- Summary ----------\n",- "Number of messages: 3\n",- "Finish reason: Text 'APPROVE' mentioned\n",- "Total prompt tokens: 3665\n",- "Total completion tokens: 311\n",- "Duration: 4.22 seconds\n"- ]- }- ],- "source": [- "# Write the poem in Spanish.\n",- "# Use `asyncio.run(Console(reflection_team.run_stream(task=\"Write the poem in Spanish.\")))` when running in a script.\n",- "await Console(reflection_team.run_stream(task=\"Write the poem in Spanish.\"))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### Resuming a Previous Task\n",- "\n",- "We can call {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run` or {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run_stream` methods\n",- "without setting the `task` again to resume the previous task. The team will continue from where it left off."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "---------- primary ----------\n",- "Thank you for your kind words! I'm glad the translation captures the essence and lyrical quality of the original poem. If you have any more requests or need further assistance, please feel free to let me know. I'm here to help!\n",- "[Prompt tokens: 2042, Completion tokens: 46]\n",- "---------- critic ----------\n",- "You're very welcome! I'm glad to hear that you're satisfied with the translation. If you have any more requests, whether it's poetry, translation, or any other kind of assistance, don't hesitate to reach out. I'm here to help with whatever you need. Enjoy the rest of your creative journey!\n",- "[Prompt tokens: 2106, Completion tokens: 58]\n",- "---------- primary ----------\n",- "Thank you for your encouraging words! I'm here to assist you with any other requests you might have, whether related to creativity, translation, or any other topic. Feel free to reach out whenever you need help or inspiration. Enjoy your journey in creativity!\n",- "[Prompt tokens: 2158, Completion tokens: 50]\n",- "---------- critic ----------\n",- "You're welcome! It's always a pleasure to assist you. If you ever have more questions or need inspiration, don't hesitate to reach out. Happy creating, and enjoy every moment of your creative journey!\n",- "[Prompt tokens: 2226, Completion tokens: 39]\n",- "---------- primary ----------\n",- "Thank you so much! Your encouragement is greatly appreciated. Feel free to reach out at any time for assistance or inspiration. I wish you the best on your creative journey and hope you enjoy every step of the way!\n",- "[Prompt tokens: 2259, Completion tokens: 43]\n",- "---------- Summary ----------\n",- "Number of messages: 5\n",- "Finish reason: Maximum number of messages 5 reached, current message count: 5\n",- "Total prompt tokens: 10791\n",- "Total completion tokens: 236\n",- "Duration: 5.00 seconds\n"- ]- }- ],- "source": [- "# Use the `asyncio.run(Console(reflection_team.run_stream()))` when running in a script.\n",- "await Console(reflection_team.run_stream())"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### Pausing for User Input\n",- "\n",- "Sometimes, teams may require additional input from the application (e.g., the user) to continue making meaningful progress on a task. Here are two ways to achieve this:\n",- "\n",- "- Set the maximum number of turns so that the team stops after the specified number of turns.\n",- "- Use the {py:class}`~autogen_agentchat.conditions.HandoffTermination` termination condition.\n",- "\n",- "You can also create custom termination conditions. For more details, see [Termination Conditions](./termination.ipynb).\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "#### Via Max Turns\n",- "\n",- "This method allows you to pause the team for user input by setting a maximum number of turns. For instance, you can configure the team to stop after the first agent responds by setting `max_turns` to 1. This is particularly useful in scenarios where continuous user engagement is required, such as in a chatbot.\n",- "\n",- "To implement this, set the `max_turns` parameter in the {py:meth}`~autogen_agentchat.teams.RoundRobinGroupChat` constructor.\n",- "\n",- "```python\n",- "team = RoundRobinGroupChat([...], max_turns=1)\n",- "```\n",- "\n",- "Once the team stops, the turn count will be reset. When you resume the team,\n",- "it will start from 0 again.\n",- "\n",- "Note that `max_turn` is specific to the team class and is currently only supported by\n",- "{py:class}`~autogen_agentchat.teams.RoundRobinGroupChat`, {py:class}`~autogen_agentchat.teams.SelectorGroupChat`, and {py:class}`~autogen_agentchat.teams.Swarm`.\n",- "When used with termination conditions, the team will stop when either condition is met."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "#### Via Handoff\n",- "\n",- "You can use the {py:class}`~autogen_agentchat.conditions.HandoffTermination` termination condition\n",- "to stop the team when an agent sends a {py:class}`~autogen_agentchat.messages.HandoffMessage` message.\n",- "\n",- "Let's create a team with a single {py:class}`~autogen_agentchat.agents.AssistantAgent` agent\n",- "with a handoff setting.\n",- "\n",- "```{note}\n",- "The model used with {py:class}`~autogen_agentchat.agents.AssistantAgent` must support tool call\n",- "to use the handoff feature.\n",- "```"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from autogen_agentchat.agents import AssistantAgent\n",- "from autogen_agentchat.base import Handoff\n",- "from autogen_agentchat.conditions import HandoffTermination, TextMentionTermination\n",- "from autogen_agentchat.teams import RoundRobinGroupChat\n",- "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",- "\n",- "# Create an OpenAI model client.\n",- "model_client = OpenAIChatCompletionClient(\n",- " model=\"gpt-4o-2024-08-06\",\n",- " # api_key=\"sk-...\", # Optional if you have an OPENAI_API_KEY env variable set.\n",- ")\n",- "\n",- "# Create a lazy assistant agent that always hands off to the user.\n",- "lazy_agent = AssistantAgent(\n",- " \"lazy_assistant\",\n",- " model_client=model_client,\n",- " handoffs=[Handoff(target=\"user\", message=\"Transfer to user.\")],\n",- " system_message=\"Always transfer to user when you don't know the answer. Respond 'TERMINATE' when task is complete.\",\n",- ")\n",- "\n",- "# Define a termination condition that checks for handoff message targetting helper and text \"TERMINATE\".\n",- "handoff_termination = HandoffTermination(target=\"user\")\n",- "text_termination = TextMentionTermination(\"TERMINATE\")\n",- "termination = handoff_termination | text_termination\n",- "\n",- "# Create a single-agent team.\n",- "lazy_agent_team = RoundRobinGroupChat([lazy_agent], termination_condition=termination)"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Let's run the team with a task that requires additional input from the user\n",- "because the agent doesn't have relevant tools to continue processing the task."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "---------- user ----------\n",- "What is the weather in New York?\n",- "---------- lazy_assistant ----------\n",- "[FunctionCall(id='call_YHm4KPjFIWZE95YrJWlJwcv4', arguments='{}', name='transfer_to_user')]\n",- "[Prompt tokens: 68, Completion tokens: 11]\n",- "---------- lazy_assistant ----------\n",- "[FunctionExecutionResult(content='Transfer to user.', call_id='call_YHm4KPjFIWZE95YrJWlJwcv4')]\n",- "---------- lazy_assistant ----------\n",- "Transfer to user.\n",- "---------- Summary ----------\n",- "Number of messages: 4\n",- "Finish reason: Handoff to user from lazy_assistant detected.\n",- "Total prompt tokens: 68\n",- "Total completion tokens: 11\n",- "Duration: 0.73 seconds\n"- ]- }- ],- "source": [- "from autogen_agentchat.ui import Console\n",- "\n",- "# Use `asyncio.run(Console(lazy_agent_team.run_stream(task=\"What is the weather in New York?\")))` when running in a script.\n",- "await Console(lazy_agent_team.run_stream(task=\"What is the weather in New York?\"))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "You can see the team stopped due to the handoff message was detected.\n",- "Let's continue the team by providing the information the agent needs."- ]- },- {- "cell_type": "code",- "execution_count": 17,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "---------- user ----------\n",- "It is raining in New York.\n",- "---------- lazy_assistant ----------\n",- "I hope you stay dry! Is there anything else you would like to know or do?\n",- "[Prompt tokens: 108, Completion tokens: 19]\n",- "---------- lazy_assistant ----------\n",- "TERMINATE\n",- "[Prompt tokens: 134, Completion tokens: 4]\n",- "---------- Summary ----------\n",- "Number of messages: 3\n",- "Finish reason: Text 'TERMINATE' mentioned\n",- "Total prompt tokens: 242\n",- "Total completion tokens: 23\n",- "Duration: 6.77 seconds\n"- ]- }- ],- "source": [- "# Use `asyncio.run(Console(lazy_agent_team.run_stream(task=\"It is raining in New York.\")))` when running in a script.\n",- "await Console(lazy_agent_team.run_stream(task=\"It is raining in New York.\"))"- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": ".venv",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.11.5"- }+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Teams\n",+ "\n",+ "In this section you'll learn how to create a _multi-agent team_ (or simply team) using AutoGen. A team is a group of agents that work together to achieve a common goal.\n",+ "\n",+ "We'll first show you how to create and run a team. We'll then explain how to observe the team's behavior, which is crucial for debugging and understanding the team's performance, and common operations to control the team's behavior."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Creating a Team\n",+ "\n",+ "{py:class}`~autogen_agentchat.teams.RoundRobinGroupChat` is a simple yet effective team configuration where all agents share the same context and take turns responding in a round-robin fashion. Each agent, during its turn, broadcasts its response to all other agents, ensuring that the entire team maintains a consistent context.\n",+ "\n",+ "We will begin by creating a team with two {py:class}`~autogen_agentchat.agents.AssistantAgent` and a {py:class}`~autogen_agentchat.conditions.TextMentionTermination` condition that stops the team when a specific word is detected in the agent's response.\n",+ "\n",+ "The two-agent team implements the _reflection_ pattern, a multi-agent design pattern where a critic agent evaluates the responses of a primary agent. Learn more about the reflection pattern using the [Core API](../../core-user-guide/design-patterns/reflection.ipynb)."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 14,+ "metadata": {},+ "outputs": [],+ "source": [+ "import asyncio\n",+ "\n",+ "from autogen_agentchat.agents import AssistantAgent\n",+ "from autogen_agentchat.base import TaskResult\n",+ "from autogen_agentchat.conditions import ExternalTermination, TextMentionTermination\n",+ "from autogen_agentchat.teams import RoundRobinGroupChat\n",+ "from autogen_agentchat.ui import Console\n",+ "from autogen_core import CancellationToken\n",+ "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",+ "\n",+ "# Create an OpenAI model client.\n",+ "model_client = OpenAIChatCompletionClient(\n",+ " model=\"gpt-4o-2024-08-06\",\n",+ " # api_key=\"sk-...\", # Optional if you have an OPENAI_API_KEY env variable set.\n",+ ")\n",+ "\n",+ "# Create the primary agent.\n",+ "primary_agent = AssistantAgent(\n",+ " \"primary\",\n",+ " model_client=model_client,\n",+ " system_message=\"You are a helpful AI assistant.\",\n",+ ")\n",+ "\n",+ "# Create the critic agent.\n",+ "critic_agent = AssistantAgent(\n",+ " \"critic\",\n",+ " model_client=model_client,\n",+ " system_message=\"Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.\",\n",+ ")\n",+ "\n",+ "# Define a termination condition that stops the task if the critic approves.\n",+ "text_termination = TextMentionTermination(\"APPROVE\")\n",+ "\n",+ "# Create a team with the primary and critic agents.\n",+ "team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Running a Team\n",+ "\n",+ "Let's calls the {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run` method\n",+ "to start the team with a task."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "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, \\nDance upon the gentle gust. \\nCrisp air whispers tales of old, \\nAs daylight wanes, the night grows bold. \\n\\nPumpkin patch and apple treats, \\nLaughter in the street repeats. \\nSweaters warm and fires aglow, \\nIt's time for nature's vibrant show. \\n\\nThe harvest moon ascends the sky, \\nWhile geese in formation start to fly. \\nAutumn speaks in colors bright, \\nA 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.\\n\\nHowever, 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.\\n\\nAdditionally, 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.\\n\\nOverall, 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:\\n\\nLeaves of amber, gold, and rust, \\nDance upon the gentle gust. \\nCrisp air whispers tales of old, \\nAs daylight wanes, the night grows bold. \\n\\nCrunch beneath the wandering feet, \\nA melody of autumn's beat. \\nCinnamon and spices blend, \\nIn every breeze, nostalgia sends. \\n\\nPumpkin patch and apple treats, \\nLaughter in the street repeats. \\nSweaters warm and fires aglow, \\nIt's time for nature's vibrant show. \\n\\nThe harvest moon ascends the sky, \\nWhile geese in formation start to fly. \\nAutumn speaks in colors bright, \\nA fleeting grace, a pure delight. \\n\\nI 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\")\n"+ ]+ }+ ],+ "source": [+ "# Use `asyncio.run(...)` when running in a script.\n",+ "result = await team.run(task=\"Write a short poem about the fall season.\")\n",+ "print(result)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "The team ran the same agent until the termination condition was met.\n",+ "In this case, the termination condition was met when the word \"TERMINATE\" is detected in the\n",+ "agent's response.\n",+ "When the team stops, it returns a {py:class}`~autogen_agentchat.base.TaskResult` object with all the messages produced by the agents in the team."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Observing a Team\n",+ "\n",+ "Similar to the agent's {py:meth}`~autogen_agentchat.agents.BaseChatAgent.on_messages_stream` method, you can stream the team's messages while it is running by calling the {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run_stream` method. This method returns a generator that yields messages produced by the agents in the team as they are generated, with the final item being the {py:class}`~autogen_agentchat.base.TaskResult` object."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "source='user' models_usage=None content='Write a short poem about the fall season.' type='TextMessage'\n",+ "source='primary' models_usage=RequestUsage(prompt_tokens=28, completion_tokens=105) content=\"Leaves descend in golden dance, \\nWhispering secrets as they fall, \\nCrisp air brings a gentle trance, \\nHeralding Autumn's call. \\n\\nPumpkins glow with orange light, \\nFields wear a cloak of amber hue, \\nDays retreat to longer night, \\nSkies shift to deeper blue. \\n\\nWinds carry scents of earth and pine, \\nSweaters wrap us, warm and tight, \\nNature's canvas, bold design, \\nIn Fall's embrace, we find delight. \" type='TextMessage'\n",+ "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.\\n\\nTo 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.\\n\\nOverall, 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. \\n\\nIf you incorporate some of these suggestions or find another way to expand the sensory experience, please share your update!' type='TextMessage'\n",+ "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:\\n\\nLeaves descend in golden dance, \\nWhisper secrets in their fall, \\nBreezes hum a gentle trance, \\nHeralding Autumn's call. \\n\\nPumpkins glow with orange light, \\nAmber fields beneath wide skies, \\nDays retreat to longer night, \\nChill winds and distant cries. \\n\\nRustling whispers of the trees, \\nSweaters wrap us, snug and tight, \\nNature's canvas, bold and free, \\nIn Fall's embrace, pure delight. \\n\\nI appreciate your feedback and hope this version better captures the sensory richness of the season!\" type='TextMessage'\n",+ "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.\\n\\nThe 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.\"\\n\\nYou\\'ve successfully infused more sensory richness into the poem, enhancing its overall emotional and atmospheric impact. Great job on the revisions!\\n\\nAPPROVE' type='TextMessage'\n",+ "Stop Reason: Text 'APPROVE' mentioned\n"+ ]+ }+ ],+ "source": [+ "# When running inside a script, use a async main function and call it from `asyncio.run(...)`.\n",+ "await team.reset() # Reset the team for a new task.\n",+ "async for message in team.run_stream(task=\"Write a short poem about the fall season.\"): # type: ignore\n",+ " if isinstance(message, TaskResult):\n",+ " print(\"Stop Reason:\", message.stop_reason)\n",+ " else:\n",+ " print(message)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "As demonstrated in the example above, you can determine the reason why the team stopped by checking the {py:attr}`~autogen_agentchat.base.TaskResult.stop_reason` attribute.\n",+ "\n",+ "The {py:meth}`~autogen_agentchat.ui.Console` method provides a convenient way to print messages to the console with proper formatting.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "---------- user ----------\n",+ "Write a short poem about the fall season.\n",+ "---------- primary ----------\n",+ "Golden leaves in crisp air dance, \n",+ "Whispering tales as they prance. \n",+ "Amber hues paint the ground, \n",+ "Nature's symphony all around. \n",+ "\n",+ "Sweaters hug with tender grace, \n",+ "While pumpkins smile, a warm embrace. \n",+ "Chill winds hum through towering trees, \n",+ "A vibrant tapestry in the breeze. \n",+ "\n",+ "Harvest moons in twilight glow, \n",+ "Casting magic on fields below. \n",+ "Fall's embrace, a gentle call, \n",+ "To savor beauty before snowfalls. \n",+ "[Prompt tokens: 28, Completion tokens: 99]\n",+ "---------- critic ----------\n",+ "Your poem beautifully captures the essence of the fall season, creating a vivid and cozy atmosphere. The imagery of golden leaves and amber hues paints a picturesque scene that many can easily relate to. I particularly appreciate the personification of pumpkins and the gentle embrace of sweaters, which adds warmth to your verses. \n",+ "\n",+ "To enhance the poem further, you might consider adding more sensory details to make the reader feel even more immersed in the experience. For example, including specific sounds, scents, or textures could deepen the connection to autumn's ambiance. Additionally, you could explore the emotional transitions as the season prepares for winter to provide a reflective element to the piece.\n",+ "\n",+ "Overall, it's a lovely and evocative depiction of fall, evoking feelings of comfort and appreciation for nature's changing beauty. Great work!\n",+ "[Prompt tokens: 144, Completion tokens: 157]\n",+ "---------- primary ----------\n",+ "Thank you for your thoughtful feedback! I'm glad you enjoyed the imagery and warmth in the poem. To enhance the sensory experience and emotional depth, here's a revised version incorporating your suggestions:\n",+ "\n",+ "---\n",+ "\n",+ "Golden leaves in crisp air dance, \n",+ "Whispering tales as they prance. \n",+ "Amber hues paint the crunchy ground, \n",+ "Nature's symphony all around. \n",+ "\n",+ "Sweaters hug with tender grace, \n",+ "While pumpkins grin, a warm embrace. \n",+ "Chill winds hum through towering trees, \n",+ "Crackling fires warm the breeze. \n",+ "\n",+ "Apples in the orchard's glow, \n",+ "Sweet cider scents that overflow. \n",+ "Crunch of paths beneath our feet, \n",+ "Cinnamon spice and toasty heat. \n",+ "\n",+ "Harvest moons in twilight's glow, \n",+ "Casting magic on fields below. \n",+ "Fall's embrace, a gentle call, \n",+ "Reflects on life's inevitable thaw. \n",+ "\n",+ "--- \n",+ "\n",+ "I hope this version enhances the sensory and emotional elements of the season. Thank you again for your insights!\n",+ "[Prompt tokens: 294, Completion tokens: 195]\n",+ "---------- critic ----------\n",+ "APPROVE\n",+ "[Prompt tokens: 506, Completion tokens: 4]\n",+ "---------- Summary ----------\n",+ "Number of messages: 5\n",+ "Finish reason: Text 'APPROVE' mentioned\n",+ "Total prompt tokens: 972\n",+ "Total completion tokens: 455\n",+ "Duration: 11.78 seconds\n"+ ]},- "nbformat": 4,- "nbformat_minor": 2+ {+ "data": {+ "text/plain": [+ "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=99), content=\"Golden leaves in crisp air dance, \\nWhispering tales as they prance. \\nAmber hues paint the ground, \\nNature's symphony all around. \\n\\nSweaters hug with tender grace, \\nWhile pumpkins smile, a warm embrace. \\nChill winds hum through towering trees, \\nA vibrant tapestry in the breeze. \\n\\nHarvest moons in twilight glow, \\nCasting magic on fields below. \\nFall's embrace, a gentle call, \\nTo savor beauty before snowfalls. \", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=144, completion_tokens=157), content=\"Your poem beautifully captures the essence of the fall season, creating a vivid and cozy atmosphere. The imagery of golden leaves and amber hues paints a picturesque scene that many can easily relate to. I particularly appreciate the personification of pumpkins and the gentle embrace of sweaters, which adds warmth to your verses. \\n\\nTo enhance the poem further, you might consider adding more sensory details to make the reader feel even more immersed in the experience. For example, including specific sounds, scents, or textures could deepen the connection to autumn's ambiance. Additionally, you could explore the emotional transitions as the season prepares for winter to provide a reflective element to the piece.\\n\\nOverall, it's a lovely and evocative depiction of fall, evoking feelings of comfort and appreciation for nature's changing beauty. Great work!\", type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=294, completion_tokens=195), content=\"Thank you for your thoughtful feedback! I'm glad you enjoyed the imagery and warmth in the poem. To enhance the sensory experience and emotional depth, here's a revised version incorporating your suggestions:\\n\\n---\\n\\nGolden leaves in crisp air dance, \\nWhispering tales as they prance. \\nAmber hues paint the crunchy ground, \\nNature's symphony all around. \\n\\nSweaters hug with tender grace, \\nWhile pumpkins grin, a warm embrace. \\nChill winds hum through towering trees, \\nCrackling fires warm the breeze. \\n\\nApples in the orchard's glow, \\nSweet cider scents that overflow. \\nCrunch of paths beneath our feet, \\nCinnamon spice and toasty heat. \\n\\nHarvest moons in twilight's glow, \\nCasting magic on fields below. \\nFall's embrace, a gentle call, \\nReflects on life's inevitable thaw. \\n\\n--- \\n\\nI hope this version enhances the sensory and emotional elements of the season. Thank you again for your insights!\", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=506, completion_tokens=4), content='APPROVE', type='TextMessage')], stop_reason=\"Text 'APPROVE' mentioned\")"+ ]+ },+ "execution_count": 6,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "await team.reset() # Reset the team for a new task.\n",+ "await Console(team.run_stream(task=\"Write a short poem about the fall season.\")) # Stream the messages to the console."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Resetting a Team\n",+ "\n",+ "You can reset the team by calling the {py:meth}`~autogen_agentchat.teams.BaseGroupChat.reset` method. This method will clear the team's state, including all agents.\n",+ "It will call the each agent's {py:meth}`~autogen_agentchat.base.ChatAgent.on_reset` method to clear the agent's state."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "metadata": {},+ "outputs": [],+ "source": [+ "await team.reset() # Reset the team for the next run."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "It is usually a good idea to reset the team if the next task is not related to the previous task.\n",+ "However, if the next task is related to the previous task, you don't need to reset and you can instead\n",+ "resume the team."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Stopping a Team\n",+ "\n",+ "Apart from automatic termination conditions such as {py:class}`~autogen_agentchat.conditions.TextMentionTermination`\n",+ "that stops the team based on the internal state of the team, you can also stop the team\n",+ "from outside by using the {py:class}`~autogen_agentchat.conditions.ExternalTermination`.\n",+ "\n",+ "Calling {py:meth}`~autogen_agentchat.conditions.ExternalTermination.set` \n",+ "on {py:class}`~autogen_agentchat.conditions.ExternalTermination` will stop\n",+ "the team when the current agent's turn is over.\n",+ "Thus, the team may not stop immediately.\n",+ "This allows the current agent to finish its turn and broadcast the final message to the team\n",+ "before the team stops, keeping the team's state consistent."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 10,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "---------- user ----------\n",+ "Write a short poem about the fall season.\n",+ "---------- primary ----------\n",+ "Leaves of amber, gold, and red, \n",+ "Gently drifting from trees overhead. \n",+ "Whispers of wind through the crisp, cool air, \n",+ "Nature's canvas painted with care. \n",+ "\n",+ "Harvest moons and evenings that chill, \n",+ "Fields of plenty on every hill. \n",+ "Sweaters wrapped tight as twilight nears, \n",+ "Fall's charming embrace, as warm as it appears. \n",+ "\n",+ "Pumpkins aglow with autumn's light, \n",+ "Harvest feasts and stars so bright. \n",+ "In every leaf and breeze that calls, \n",+ "We find the magic of glorious fall. \n",+ "[Prompt tokens: 28, Completion tokens: 114]\n",+ "---------- Summary ----------\n",+ "Number of messages: 2\n",+ "Finish reason: External termination requested\n",+ "Total prompt tokens: 28\n",+ "Total completion tokens: 114\n",+ "Duration: 1.71 seconds\n"+ ]+ },+ {+ "data": {+ "text/plain": [+ "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, \\nGently drifting from trees overhead. \\nWhispers of wind through the crisp, cool air, \\nNature's canvas painted with care. \\n\\nHarvest moons and evenings that chill, \\nFields of plenty on every hill. \\nSweaters wrapped tight as twilight nears, \\nFall's charming embrace, as warm as it appears. \\n\\nPumpkins aglow with autumn's light, \\nHarvest feasts and stars so bright. \\nIn every leaf and breeze that calls, \\nWe find the magic of glorious fall. \", type='TextMessage')], stop_reason='External termination requested')"+ ]+ },+ "execution_count": 10,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# Create a new team with an external termination condition.\n",+ "external_termination = ExternalTermination()\n",+ "team = RoundRobinGroupChat(\n",+ " [primary_agent, critic_agent],\n",+ " termination_condition=external_termination | text_termination, # Use the bitwise OR operator to combine conditions.\n",+ ")\n",+ "\n",+ "# Run the team in a background task.\n",+ "run = asyncio.create_task(Console(team.run_stream(task=\"Write a short poem about the fall season.\")))\n",+ "\n",+ "# Wait for some time.\n",+ "await asyncio.sleep(0.1)\n",+ "\n",+ "# Stop the team.\n",+ "external_termination.set()\n",+ "\n",+ "# Wait for the team to finish.\n",+ "await run"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "From the ouput above, you can see the team stopped because the external termination condition was met,\n",+ "but the speaking agent was able to finish its turn before the team stopped."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Resuming a Team\n",+ "\n",+ "Teams are stateful and maintains the conversation history and context\n",+ "after each run, unless you reset the team.\n",+ "\n",+ "You can resume a team to continue from where it left off by calling the {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run` or {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run_stream` method again\n",+ "without a new task.\n",+ "{py:class}`~autogen_agentchat.teams.RoundRobinGroupChat` will continue from the next agent in the round-robin order."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 11,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "---------- critic ----------\n",+ "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:\n",+ "\n",+ "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.\"\n",+ "\n",+ "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.\n",+ "\n",+ "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.\n",+ "\n",+ "Overall, it’s a lovely depiction of fall. These suggestions are minor tweaks that might elevate the reader's experience even further. Nice work!\n",+ "\n",+ "Let me know if these feedbacks are addressed.\n",+ "[Prompt tokens: 159, Completion tokens: 237]\n",+ "---------- primary ----------\n",+ "Thank you for the thoughtful feedback! Here’s a revised version, incorporating your suggestions: \n",+ "\n",+ "Leaves of amber, gold—drifting like dreams, \n",+ "A golden rain from trees’ canopies. \n",+ "Whispers of wind—a gentle breath, \n",+ "Nature’s scented tapestry embracing earth. \n",+ "\n",+ "Harvest moons rise as evenings chill, \n",+ "Fields of plenty paint every hill. \n",+ "Sweaters wrapped tight as twilight nears— \n",+ "Fall’s embrace, warm as whispered years. \n",+ "\n",+ "Pumpkins aglow with autumn’s light, \n",+ "Crackling leaves underfoot in flight. \n",+ "In every leaf and breeze that calls, \n",+ "We find the magic of glorious fall. \n",+ "\n",+ "I hope these changes enhance the imagery and sensory experience. Thank you again for your feedback!\n",+ "[Prompt tokens: 389, Completion tokens: 150]\n",+ "---------- critic ----------\n",+ "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. \n",+ "\n",+ "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!\n",+ "\n",+ "APPROVE\n",+ "[Prompt tokens: 556, Completion tokens: 132]\n",+ "---------- Summary ----------\n",+ "Number of messages: 3\n",+ "Finish reason: Text 'APPROVE' mentioned\n",+ "Total prompt tokens: 1104\n",+ "Total completion tokens: 519\n",+ "Duration: 9.79 seconds\n"+ ]+ },+ {+ "data": {+ "text/plain": [+ "TaskResult(messages=[TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=159, completion_tokens=237), content='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:\\n\\n1. **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.\"\\n\\n2. **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.\\n\\n3. **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.\\n\\nOverall, it’s a lovely depiction of fall. These suggestions are minor tweaks that might elevate the reader\\'s experience even further. Nice work!\\n\\nLet me know if these feedbacks are addressed.', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=389, completion_tokens=150), content='Thank you for the thoughtful feedback! Here’s a revised version, incorporating your suggestions: \\n\\nLeaves of amber, gold—drifting like dreams, \\nA golden rain from trees’ canopies. \\nWhispers of wind—a gentle breath, \\nNature’s scented tapestry embracing earth. \\n\\nHarvest moons rise as evenings chill, \\nFields of plenty paint every hill. \\nSweaters wrapped tight as twilight nears— \\nFall’s embrace, warm as whispered years. \\n\\nPumpkins aglow with autumn’s light, \\nCrackling leaves underfoot in flight. \\nIn every leaf and breeze that calls, \\nWe find the magic of glorious fall. \\n\\nI hope these changes enhance the imagery and sensory experience. Thank you again for your feedback!', type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=556, completion_tokens=132), content='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. \\n\\nOverall, these changes bring greater vibrancy and life to the poem, allowing readers to truly experience the wonders of fall. Excellent work on the revisions!\\n\\nAPPROVE', type='TextMessage')], stop_reason=\"Text 'APPROVE' mentioned\")"+ ]+ },+ "execution_count": 11,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "await Console(team.run_stream()) # Resume the team to continue the last task."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "You can see the team resumed from where it left off in the output above,\n",+ "and the first message is from the next agent after the last agent that spoke\n",+ "before the team stopped.\n",+ "\n",+ "Let's resume the team again with a new task while keeping the context about the previous task."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 12,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "---------- user ----------\n",+ "将这首诗用中文唐诗风格写一遍。\n",+ "---------- primary ----------\n",+ "朔风轻拂叶飘金, \n",+ "枝上斜阳染秋林。 \n",+ "满山丰收人欢喜, \n",+ "月明归途衣渐紧。 \n",+ "\n",+ "南瓜影映灯火中, \n",+ "落叶沙沙伴归程。 \n",+ "片片秋意随风起, \n",+ "秋韵悠悠心自明。 \n",+ "[Prompt tokens: 700, Completion tokens: 77]\n",+ "---------- critic ----------\n",+ "这首改编的唐诗风格诗作成功地保留了原诗的意境与情感,体现出秋季特有的氛围和美感。通过“朔风轻拂叶飘金”、“枝上斜阳染秋林”等意象,生动地描绘出了秋天的景色,与唐诗中的自然意境相呼应。且“月明归途衣渐紧”、“落叶沙沙伴归程”让人感受到秋天的安宁与温暖。\n",+ "\n",+ "通过这些诗句,读者能够感受到秋天的惬意与宁静,勾起丰收与团圆的画面,是一次成功的翻译改编。\n",+ "\n",+ "APPROVE\n",+ "[Prompt tokens: 794, Completion tokens: 161]\n",+ "---------- Summary ----------\n",+ "Number of messages: 3\n",+ "Finish reason: Text 'APPROVE' mentioned\n",+ "Total prompt tokens: 1494\n",+ "Total completion tokens: 238\n",+ "Duration: 3.89 seconds\n"+ ]+ },+ {+ "data": {+ "text/plain": [+ "TaskResult(messages=[TextMessage(source='user', models_usage=None, content='将这首诗用中文唐诗风格写一遍。', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=700, completion_tokens=77), content='朔风轻拂叶飘金, \\n枝上斜阳染秋林。 \\n满山丰收人欢喜, \\n月明归途衣渐紧。 \\n\\n南瓜影映灯火中, \\n落叶沙沙伴归程。 \\n片片秋意随风起, \\n秋韵悠悠心自明。 ', type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=794, completion_tokens=161), content='这首改编的唐诗风格诗作成功地保留了原诗的意境与情感,体现出秋季特有的氛围和美感。通过“朔风轻拂叶飘金”、“枝上斜阳染秋林”等意象,生动地描绘出了秋天的景色,与唐诗中的自然意境相呼应。且“月明归途衣渐紧”、“落叶沙沙伴归程”让人感受到秋天的安宁与温暖。\\n\\n通过这些诗句,读者能够感受到秋天的惬意与宁静,勾起丰收与团圆的画面,是一次成功的翻译改编。\\n\\nAPPROVE', type='TextMessage')], stop_reason=\"Text 'APPROVE' mentioned\")"+ ]+ },+ "execution_count": 12,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# The new task is to translate the same poem to Chinese Tang-style poetry.\n",+ "await Console(team.run_stream(task=\"将这首诗用中文唐诗风格写一遍。\"))"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Aborting a Team\n",+ "\n",+ "You can abort a call to {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run` or {py:meth}`~autogen_agentchat.teams.BaseGroupChat.run_stream`\n",+ "during execution by setting a {py:class}`~autogen_core.CancellationToken` passed to the `cancellation_token` parameter.\n",+ "\n",+ "Different from stopping a team, aborting a team will immediately stop the team and raise a {py:class}`~asyncio.CancelledError` exception.\n",+ "\n",+ "```{note}\n",+ "The caller will get a {py:class}`~asyncio.CancelledError` exception when the team is aborted.\n",+ "```"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 15,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Task was cancelled.\n"+ ]+ }+ ],+ "source": [+ "# Create a cancellation token.\n",+ "cancellation_token = CancellationToken()\n",+ "\n",+ "# Use another coroutine to run the team.\n",+ "run = asyncio.create_task(\n",+ " team.run(\n",+ " task=\"Translate the poem to Spanish.\",\n",+ " cancellation_token=cancellation_token,\n",+ " )\n",+ ")\n",+ "\n",+ "# Cancel the run.\n",+ "cancellation_token.cancel()\n",+ "\n",+ "try:\n",+ " result = await run # This will raise a CancelledError.\n",+ "except asyncio.CancelledError:\n",+ " print(\"Task was cancelled.\")"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": ".venv",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.11.5"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2}