GraphFlow (Workflows)#
In this section you’ll learn how to create an multi-agent workflow using GraphFlow
, or simply “flow” for short.
It uses structured execution and precisely controls how agents interact to accomplish a task.
We’ll first show you how to create and run a flow. We’ll then explain how to observe and debug flow behavior, and discuss important operations for managing execution.
AutoGen AgentChat provides a team for directed graph execution:
GraphFlow
: A team that follows aDiGraph
to control the execution flow between agents. Supports sequential, parallel, conditional, and looping behaviors.
Note
When should you use GraphFlow
?
Use Graph when you need strict control over the order in which agents act, or when different outcomes must lead to different next steps.
Start with a simple team such as RoundRobinGroupChat
or SelectorGroupChat
if ad-hoc conversation flow is sufficient.
Transition to a structured workflow when your task requires deterministic control,
conditional branching, or handling complex multi-step processes with cycles.
Warning:
GraphFlow
is an experimental feature. Its API, behavior, and capabilities are subject to change in future releases.
Creating and Running a Flow#
DiGraphBuilder
is a fluent utility that lets you easily construct execution graphs for workflows. It supports building:
Sequential chains
Parallel fan-outs
Conditional branching
Loops with safe exit conditions
Each node in the graph represents an agent, and edges define the allowed execution paths. Edges can optionally have conditions based on agent messages.
Sequential Flow#
We will begin by creating a simple workflow where a writer drafts a paragraph and a reviewer provides feedback. This graph terminates after the reviewer comments on the writer.
Note, the flow automatically computes all the source and leaf nodes of the graph and the execution starts at all the source nodes in the graph and completes execution when no nodes are left to execute.
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import DiGraphBuilder, GraphFlow
from autogen_ext.models.openai import OpenAIChatCompletionClient
# Create an OpenAI model client
client = OpenAIChatCompletionClient(model="gpt-4.1-nano")
# Create the writer agent
writer = AssistantAgent("writer", model_client=client, system_message="Draft a short paragraph on climate change.")
# Create the reviewer agent
reviewer = AssistantAgent("reviewer", model_client=client, system_message="Review the draft and suggest improvements.")
# Build the graph
builder = DiGraphBuilder()
builder.add_node(writer).add_node(reviewer)
builder.add_edge(writer, reviewer)
# Build and validate the graph
graph = builder.build()
# Create the flow
flow = GraphFlow([writer, reviewer], graph=graph)
# Use `asyncio.run(...)` and wrap the below in a async function when running in a script.
stream = flow.run_stream(task="Write a short paragraph about climate change.")
async for event in stream: # type: ignore
print(event)
# Use Console(flow.run_stream(...)) for better formatting in console.
source='user' models_usage=None metadata={} content='Write a short paragraph about climate change.' type='TextMessage'
source='writer' models_usage=RequestUsage(prompt_tokens=28, completion_tokens=95) metadata={} content='Climate change refers to long-term shifts in temperature, precipitation, and other atmospheric patterns, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These changes contribute to rising global temperatures, melting ice caps, more frequent and severe weather events, and adverse impacts on ecosystems and human communities. Addressing climate change requires global cooperation to reduce greenhouse gas emissions, transition to renewable energy sources, and implement sustainable practices to protect the planet for future generations.' type='TextMessage'
source='reviewer' models_usage=RequestUsage(prompt_tokens=127, completion_tokens=144) metadata={} content="The paragraph provides a clear overview of climate change, its causes, and its impacts. To enhance clarity and engagement, consider adding specific examples or emphasizing the urgency of action. Here's a revised version:\n\nClimate change is a long-term alteration of Earth's climate patterns caused primarily by human activities such as burning fossil fuels, deforestation, and industrial emissions. These actions increase greenhouse gases in the atmosphere, leading to rising global temperatures, melting ice caps, and more frequent extreme weather events like hurricanes and droughts. The effects threaten ecosystems, disrupt agriculture, and endanger communities worldwide. Addressing this crisis requires urgent, coordinated global efforts to reduce emissions, adopt renewable energy, and promote sustainable practices to safeguard the planet for future generations." type='TextMessage'
source='DiGraphStopAgent' models_usage=None metadata={} content='Digraph execution is complete' type='StopMessage'
messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Write a short paragraph about climate change.', type='TextMessage'), TextMessage(source='writer', models_usage=RequestUsage(prompt_tokens=28, completion_tokens=95), metadata={}, content='Climate change refers to long-term shifts in temperature, precipitation, and other atmospheric patterns, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These changes contribute to rising global temperatures, melting ice caps, more frequent and severe weather events, and adverse impacts on ecosystems and human communities. Addressing climate change requires global cooperation to reduce greenhouse gas emissions, transition to renewable energy sources, and implement sustainable practices to protect the planet for future generations.', type='TextMessage'), TextMessage(source='reviewer', models_usage=RequestUsage(prompt_tokens=127, completion_tokens=144), metadata={}, content="The paragraph provides a clear overview of climate change, its causes, and its impacts. To enhance clarity and engagement, consider adding specific examples or emphasizing the urgency of action. Here's a revised version:\n\nClimate change is a long-term alteration of Earth's climate patterns caused primarily by human activities such as burning fossil fuels, deforestation, and industrial emissions. These actions increase greenhouse gases in the atmosphere, leading to rising global temperatures, melting ice caps, and more frequent extreme weather events like hurricanes and droughts. The effects threaten ecosystems, disrupt agriculture, and endanger communities worldwide. Addressing this crisis requires urgent, coordinated global efforts to reduce emissions, adopt renewable energy, and promote sustainable practices to safeguard the planet for future generations.", type='TextMessage'), StopMessage(source='DiGraphStopAgent', models_usage=None, metadata={}, content='Digraph execution is complete', type='StopMessage')] stop_reason='Stop message received'
Parallel Flow with Join#
We now create a slightly more complex flow:
A writer drafts a paragraph.
Two editors independently edit for grammar and style (parallel fan-out).
A final reviewer consolidates their edits (join).
Execution starts at the writer, fans out to editor1 and editor2 simultaneously, and then both feed into the final reviewer.
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import DiGraphBuilder, GraphFlow
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
# Create an OpenAI model client
client = OpenAIChatCompletionClient(model="gpt-4.1-nano")
# Create the writer agent
writer = AssistantAgent("writer", model_client=client, system_message="Draft a short paragraph on climate change.")
# Create two editor agents
editor1 = AssistantAgent("editor1", model_client=client, system_message="Edit the paragraph for grammar.")
editor2 = AssistantAgent("editor2", model_client=client, system_message="Edit the paragraph for style.")
# Create the final reviewer agent
final_reviewer = AssistantAgent(
"final_reviewer",
model_client=client,
system_message="Consolidate the grammar and style edits into a final version.",
)
# Build the workflow graph
builder = DiGraphBuilder()
builder.add_node(writer).add_node(editor1).add_node(editor2).add_node(final_reviewer)
# Fan-out from writer to editor1 and editor2
builder.add_edge(writer, editor1)
builder.add_edge(writer, editor2)
# Fan-in both editors into final reviewer
builder.add_edge(editor1, final_reviewer)
builder.add_edge(editor2, final_reviewer)
# Build and validate the graph
graph = builder.build()
# Create the flow
flow = GraphFlow(
participants=builder.get_participants(),
graph=graph,
)
# Run the workflow
await Console(flow.run_stream(task="Write a short paragraph about climate change."))
---------- TextMessage (user) ----------
Write a short paragraph about climate change.
---------- TextMessage (writer) ----------
Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.
---------- TextMessage (editor1) ----------
Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.
---------- TextMessage (editor2) ----------
Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities like burning fossil fuels, deforestation, and industrial processes. These actions elevate levels of greenhouse gases such as carbon dioxide and methane, resulting in global warming. Its consequences are widespread, including more frequent and intense storms, rising sea levels, melting glaciers, and disturbances to ecosystems and agriculture. Combating this crisis demands international collaboration, a swift transition to renewable energy, and sustainable practices to cut carbon emissions, ensuring a healthier planet for future generations.
---------- TextMessage (final_reviewer) ----------
Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities such as burning fossil fuels, deforestation, and industrial processes. These actions increase levels of greenhouse gases like carbon dioxide and methane, leading to global warming. Its consequences include more frequent and intense storms, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this crisis requires international collaboration, a swift transition to renewable energy, and sustainable practices to reduce carbon emissions, ensuring a healthier planet for future generations.
---------- StopMessage (DiGraphStopAgent) ----------
Digraph execution is complete
TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Write a short paragraph about climate change.', type='TextMessage'), TextMessage(source='writer', models_usage=RequestUsage(prompt_tokens=28, completion_tokens=113), metadata={}, content='Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.', type='TextMessage'), TextMessage(source='editor1', models_usage=RequestUsage(prompt_tokens=144, completion_tokens=113), metadata={}, content='Climate change refers to long-term shifts in weather patterns and global temperatures, largely driven by human activities such as burning fossil fuels, deforestation, and industrial processes. These activities increase concentrations of greenhouse gases like carbon dioxide and methane in the atmosphere, leading to global warming. The impacts of climate change include more frequent and severe weather events, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this urgent issue requires international cooperation, significant shifts toward renewable energy sources, and sustainable practices to reduce our carbon footprint and protect the planet for future generations.', type='TextMessage'), TextMessage(source='editor2', models_usage=RequestUsage(prompt_tokens=263, completion_tokens=107), metadata={}, content='Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities like burning fossil fuels, deforestation, and industrial processes. These actions elevate levels of greenhouse gases such as carbon dioxide and methane, resulting in global warming. Its consequences are widespread, including more frequent and intense storms, rising sea levels, melting glaciers, and disturbances to ecosystems and agriculture. Combating this crisis demands international collaboration, a swift transition to renewable energy, and sustainable practices to cut carbon emissions, ensuring a healthier planet for future generations.', type='TextMessage'), TextMessage(source='final_reviewer', models_usage=RequestUsage(prompt_tokens=383, completion_tokens=104), metadata={}, content='Climate change involves long-term alterations in weather patterns and global temperatures, primarily caused by human activities such as burning fossil fuels, deforestation, and industrial processes. These actions increase levels of greenhouse gases like carbon dioxide and methane, leading to global warming. Its consequences include more frequent and intense storms, rising sea levels, melting glaciers, and disruptions to ecosystems and agriculture. Addressing this crisis requires international collaboration, a swift transition to renewable energy, and sustainable practices to reduce carbon emissions, ensuring a healthier planet for future generations.', type='TextMessage'), StopMessage(source='DiGraphStopAgent', models_usage=None, metadata={}, content='Digraph execution is complete', type='StopMessage')], stop_reason='Stop message received')
Message Filtering#
Execution Graph vs. Message Graph#
In GraphFlow
, the execution graph is defined using
DiGraph
, which controls the order in which agents execute.
However, the execution graph does not control what messages an agent receives from other agents.
By default, all messages are sent to all agents in the graph.
Message filtering is a separate feature that allows you to filter the messages received by each agent and limiting their model context to only the relevant information. The set of message filters defines the message graph in the flow.
Specifying the message graph can help with:
Reduce hallucinations
Control memory load
Focus agents only on relevant information
You can use MessageFilterAgent
together with MessageFilterConfig
and PerSourceFilter
to define these rules.
from autogen_agentchat.agents import AssistantAgent, MessageFilterAgent, MessageFilterConfig, PerSourceFilter
from autogen_agentchat.teams import DiGraphBuilder, GraphFlow
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
# Model client
client = OpenAIChatCompletionClient(model="gpt-4.1-nano")
# Create agents
researcher = AssistantAgent(
"researcher", model_client=client, system_message="Summarize key facts about climate change."
)
analyst = AssistantAgent("analyst", model_client=client, system_message="Review the summary and suggest improvements.")
presenter = AssistantAgent(
"presenter", model_client=client, system_message="Prepare a presentation slide based on the final summary."
)
# Apply message filtering
filtered_analyst = MessageFilterAgent(
name="analyst",
wrapped_agent=analyst,
filter=MessageFilterConfig(per_source=[PerSourceFilter(source="researcher", position="last", count=1)]),
)
filtered_presenter = MessageFilterAgent(
name="presenter",
wrapped_agent=presenter,
filter=MessageFilterConfig(per_source=[PerSourceFilter(source="analyst", position="last", count=1)]),
)
# Build the flow
builder = DiGraphBuilder()
builder.add_node(researcher).add_node(filtered_analyst).add_node(filtered_presenter)
builder.add_edge(researcher, filtered_analyst).add_edge(filtered_analyst, filtered_presenter)
# Create the flow
flow = GraphFlow(
participants=builder.get_participants(),
graph=builder.build(),
)
# Run the flow
await Console(flow.run_stream(task="Summarize key facts about climate change."))
---------- TextMessage (user) ----------
Summarize key facts about climate change.
---------- TextMessage (researcher) ----------
Certainly! Here are some key facts about climate change:
1. **Global Warming**: Earth's average surface temperature has increased significantly over the past century, primarily due to human activities.
2. **Greenhouse Gas Emissions**: The main contributors are carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O), resulting from burning fossil fuels, deforestation, and industrial processes.
3. **Impacts on Weather and Climate**: Climate change leads to more frequent and severe heatwaves, storms, droughts, and heavy rainfall.
4. **Rising Sea Levels**: Melting polar ice caps and glaciers, along with thermal expansion of seawater, are causing sea levels to rise.
5. **Effects on Ecosystems**: Altered habitats threaten plant and animal species, leading to biodiversity loss.
6. **Human Health and Societies**: Climate change contributes to health issues, food and water insecurity, and displacement of populations.
7. **Global Response**: International efforts like the Paris Agreement aim to limit temperature rise, promote renewable energy, and reduce emissions.
8. **Urgency**: Addressing climate change requires immediate, concerted actions to mitigate further damage and adapt to changes.
Let me know if you want more detailed information on any of these points!
---------- TextMessage (analyst) ----------
Your summary effectively covers the fundamental aspects of climate change and presents them clearly. Here are some suggestions to improve clarity, depth, and engagement:
1. Enhance structure with subheadings: Organize points into thematic sections (e.g., Causes, Effects, Responses) for easier navigation.
2. Add recent context or data: Incorporate the latest statistics or notable recent events to emphasize urgency.
3. Emphasize solutions: Briefly mention specific mitigation and adaptation strategies beyond international agreements.
4. Use more precise language: For example, specify the amount of temperature increase globally (~1.2°C since pre-industrial times).
5. Incorporate the importance of individual actions: Highlight how personal choices contribute to climate efforts.
6. Mention climate feedback loops: Briefly note how certain effects (like melting ice) can accelerate warming.
**Improved Version:**
---
**Overview of Climate Change**
**Causes:**
- Human activities, especially burning fossil fuels, deforestation, and industrial processes, have led to increased concentrations of greenhouse gases such as carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O).
- Since the late 19th century, Earth's average surface temperature has risen by approximately 1.2°C, with the past decade being the warmest on record.
**Impacts:**
- The changing climate causes more frequent and intense heatwaves, storms, droughts, and heavy rainfall events.
- Melting polar ice caps and glaciers, along with thermal expansion, are raising sea levels, threatening coastal communities.
- Ecosystems are shifting, leading to habitat loss and risking biodiversity, with some species facing extinction.
- Human health and societies are affected through increased heat-related illnesses, food and water insecurity, and displacement due to extreme weather events.
**Global Response and Solutions:**
- International agreements like the Paris Agreement aim to limit global temperature rise well below 2°C.
- Strategies include transitioning to renewable energy sources, increasing energy efficiency, reforestation, and sustainable land use.
- Community and individual actions—reducing carbon footprints, supporting sustainable policies, and raising awareness—are essential components.
**Urgency and Call to Action:**
- Immediate, coordinated efforts are critical to mitigate irreversible damage and adapt to ongoing changes.
- Every sector, from government to individual, has a role to play in creating a sustainable future.
---
Let me know if you'd like a more detailed explanation of any section or additional statistical data!
---------- TextMessage (presenter) ----------
**Slide Title:**
**Climate Change: Causes, Impacts & Solutions**
**Causes:**
- Emissions from burning fossil fuels, deforestation, industrial activities
- Greenhouse gases (CO₂, CH₄, N₂O) have increased significantly
- Global temperature has risen by ~1.2°C since pre-industrial times
**Impacts:**
- More frequent heatwaves, storms, droughts, and heavy rainfall
- Melting ice caps and rising sea levels threaten coastal areas
- Habitat loss and decreased biodiversity
- Health risks and societal disruptions
**Responses & Solutions:**
- International efforts like the Paris Agreement aim to limit warming
- Transitioning to renewable energy, energy efficiency, reforestation
- Community and individual actions: reducing carbon footprints and raising awareness
**Urgency:**
- Immediate, coordinated action is essential to prevent irreversible damage
- Everyone has a role in building a sustainable future
---------- StopMessage (DiGraphStopAgent) ----------
Digraph execution is complete
TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Summarize key facts about climate change.', type='TextMessage'), TextMessage(source='researcher', models_usage=RequestUsage(prompt_tokens=30, completion_tokens=267), metadata={}, content="Certainly! Here are some key facts about climate change:\n\n1. **Global Warming**: Earth's average surface temperature has increased significantly over the past century, primarily due to human activities.\n2. **Greenhouse Gas Emissions**: The main contributors are carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O), resulting from burning fossil fuels, deforestation, and industrial processes.\n3. **Impacts on Weather and Climate**: Climate change leads to more frequent and severe heatwaves, storms, droughts, and heavy rainfall.\n4. **Rising Sea Levels**: Melting polar ice caps and glaciers, along with thermal expansion of seawater, are causing sea levels to rise.\n5. **Effects on Ecosystems**: Altered habitats threaten plant and animal species, leading to biodiversity loss.\n6. **Human Health and Societies**: Climate change contributes to health issues, food and water insecurity, and displacement of populations.\n7. **Global Response**: International efforts like the Paris Agreement aim to limit temperature rise, promote renewable energy, and reduce emissions.\n8. **Urgency**: Addressing climate change requires immediate, concerted actions to mitigate further damage and adapt to changes.\n\nLet me know if you want more detailed information on any of these points!", type='TextMessage'), TextMessage(source='analyst', models_usage=RequestUsage(prompt_tokens=287, completion_tokens=498), metadata={}, content="Your summary effectively covers the fundamental aspects of climate change and presents them clearly. Here are some suggestions to improve clarity, depth, and engagement:\n\n1. Enhance structure with subheadings: Organize points into thematic sections (e.g., Causes, Effects, Responses) for easier navigation.\n2. Add recent context or data: Incorporate the latest statistics or notable recent events to emphasize urgency.\n3. Emphasize solutions: Briefly mention specific mitigation and adaptation strategies beyond international agreements.\n4. Use more precise language: For example, specify the amount of temperature increase globally (~1.2°C since pre-industrial times).\n5. Incorporate the importance of individual actions: Highlight how personal choices contribute to climate efforts.\n6. Mention climate feedback loops: Briefly note how certain effects (like melting ice) can accelerate warming.\n\n**Improved Version:**\n\n---\n\n**Overview of Climate Change**\n\n**Causes:**\n- Human activities, especially burning fossil fuels, deforestation, and industrial processes, have led to increased concentrations of greenhouse gases such as carbon dioxide (CO₂), methane (CH₄), and nitrous oxide (N₂O).\n- Since the late 19th century, Earth's average surface temperature has risen by approximately 1.2°C, with the past decade being the warmest on record.\n\n**Impacts:**\n- The changing climate causes more frequent and intense heatwaves, storms, droughts, and heavy rainfall events.\n- Melting polar ice caps and glaciers, along with thermal expansion, are raising sea levels, threatening coastal communities.\n- Ecosystems are shifting, leading to habitat loss and risking biodiversity, with some species facing extinction.\n- Human health and societies are affected through increased heat-related illnesses, food and water insecurity, and displacement due to extreme weather events.\n\n**Global Response and Solutions:**\n- International agreements like the Paris Agreement aim to limit global temperature rise well below 2°C.\n- Strategies include transitioning to renewable energy sources, increasing energy efficiency, reforestation, and sustainable land use.\n- Community and individual actions—reducing carbon footprints, supporting sustainable policies, and raising awareness—are essential components.\n\n**Urgency and Call to Action:**\n- Immediate, coordinated efforts are critical to mitigate irreversible damage and adapt to ongoing changes.\n- Every sector, from government to individual, has a role to play in creating a sustainable future.\n\n---\n\nLet me know if you'd like a more detailed explanation of any section or additional statistical data!", type='TextMessage'), TextMessage(source='presenter', models_usage=RequestUsage(prompt_tokens=521, completion_tokens=192), metadata={}, content='**Slide Title:** \n**Climate Change: Causes, Impacts & Solutions**\n\n**Causes:** \n- Emissions from burning fossil fuels, deforestation, industrial activities \n- Greenhouse gases (CO₂, CH₄, N₂O) have increased significantly \n- Global temperature has risen by ~1.2°C since pre-industrial times \n\n**Impacts:** \n- More frequent heatwaves, storms, droughts, and heavy rainfall \n- Melting ice caps and rising sea levels threaten coastal areas \n- Habitat loss and decreased biodiversity \n- Health risks and societal disruptions \n\n**Responses & Solutions:** \n- International efforts like the Paris Agreement aim to limit warming \n- Transitioning to renewable energy, energy efficiency, reforestation \n- Community and individual actions: reducing carbon footprints and raising awareness \n\n**Urgency:** \n- Immediate, coordinated action is essential to prevent irreversible damage \n- Everyone has a role in building a sustainable future', type='TextMessage'), StopMessage(source='DiGraphStopAgent', models_usage=None, metadata={}, content='Digraph execution is complete', type='StopMessage')], stop_reason='Stop message received')
🔁 Advanced Example: Conditional Loop + Filtered Summary#
This example demonstrates:
A loop between generator and reviewer (which exits when reviewer says “APPROVE”)
A summarizer agent that only sees the first user input and the last reviewer message
from autogen_agentchat.agents import AssistantAgent, MessageFilterAgent, MessageFilterConfig, PerSourceFilter
from autogen_agentchat.teams import (
DiGraphBuilder,
GraphFlow,
)
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
# Agents
generator = AssistantAgent("generator", model_client=model_client, system_message="Generate a list of creative ideas.")
reviewer = AssistantAgent(
"reviewer",
model_client=model_client,
system_message="Review ideas and provide feedbacks, or just 'APPROVE' for final approval.",
)
summarizer_core = AssistantAgent(
"summary", model_client=model_client, system_message="Summarize the user request and the final feedback."
)
# Filtered summarizer
filtered_summarizer = MessageFilterAgent(
name="summary",
wrapped_agent=summarizer_core,
filter=MessageFilterConfig(
per_source=[
PerSourceFilter(source="user", position="first", count=1),
PerSourceFilter(source="reviewer", position="last", count=1),
]
),
)
# Build graph with conditional loop
builder = DiGraphBuilder()
builder.add_node(generator).add_node(reviewer).add_node(filtered_summarizer)
builder.add_edge(generator, reviewer)
builder.add_edge(reviewer, filtered_summarizer, condition=lambda msg: "APPROVE" in msg.to_model_text())
builder.add_edge(reviewer, generator, condition=lambda msg: "APPROVE" not in msg.to_model_text())
builder.set_entry_point(generator) # Set entry point to generator. Required if there are no source nodes.
graph = builder.build()
# Create the flow
flow = GraphFlow(
participants=builder.get_participants(),
graph=graph,
)
# Run the flow and pretty print the output in the console
await Console(flow.run_stream(task="Brainstorm ways to reduce plastic waste."))
---------- TextMessage (user) ----------
Brainstorm ways to reduce plastic waste.
---------- TextMessage (generator) ----------
1. **Refill Stations**: Set up refill stations for common household products such as laundry detergent, shampoo, and cleaning supplies in grocery stores and public spaces.
2. **Bulk Buying Incentives**: Create incentives for consumers to buy in bulk, reducing the amount of packaging waste.
3. **Eco-friendly Packaging**: Encourage companies to develop biodegradable or compostable packaging for their products.
4. **Upcycling Workshops**: Organize community workshops that teach people how to repurpose plastic items into practical or decorative objects.
5. **Community Clean-Up Events**: Host regular community clean-up events focused on collecting plastic waste from parks, beaches, and roadsides.
6. **Education Campaigns**: Launch educational campaigns in schools and communities about the impact of plastic waste and sustainable alternatives.
7. **Plastic-Free Challenges**: Initiate a monthly plastic-free challenge encouraging individuals and families to reduce their plastic consumption.
8. **Support Local Artisan Products**: Promote local artisans who create products from recycled materials, fostering a circular economy.
9. **Rewards Programs**: Develop a rewards program for individuals and businesses who actively reduce their plastic usage, such as discounts or points for using reusable bags and containers.
10. **Zero-Waste Grocery Stores**: Support the establishment of zero-waste grocery stores where customers can bring their own containers and buy loose, unpackaged products.
11. **Legislation and Policy Changes**: Advocate for policies that ban single-use plastics and promote alternatives in both public and private sectors.
12. **Environmentally Friendly Innovations**: Invest in and promote innovations in materials science that create alternatives to plastic from natural materials.
13. **Plastic Bank Initiatives**: Start or support initiatives that allow people to exchange plastic waste for products or services, incentivizing recycling.
14. **DIY Tutorials**: Create and share DIY tutorials for making your own household products to reduce reliance on plastic-packaged goods.
15. **Corporate Sustainability Partnerships**: Encourage collaboration between businesses to share best practices in reducing plastic use and waste.
16. **Public Art Installations**: Organize public art projects using collected plastic waste to raise awareness and promote discussions on plastic pollution.
17. **Sustainable Fashion Initiatives**: Promote clothing and accessories made from recycled plastics, highlighting those companies that commit to eco-friendly practices.
18. **Digital Outreach**: Use social media and digital platforms to raise awareness about the impact of plastic waste and promote sustainable lifestyle choices.
19. **Composting Services**: Establish services that help compost food waste and other biodegradable materials, reducing reliance on plastic bags for disposal.
20. **Sustainable Event Planning**: Collaborate with event planners to create guidelines for low-plastic events, encouraging the use of sustainable materials and practices.
---------- TextMessage (reviewer) ----------
These ideas provide a comprehensive approach to reducing plastic waste, addressing various aspects such as consumer behavior, community involvement, and corporate responsibility. Here are some feedbacks and suggestions for improvement:
1. **Refill Stations**: Provide clear labeling and education about the environmental benefits of using refill stations to encourage more participation.
2. **Bulk Buying Incentives**: Consider incorporating a loyalty program that rewards frequent bulk buyers with additional discounts or promotions.
3. **Eco-friendly Packaging**: Collaborate with universities and research institutions to foster innovation in eco-friendly packaging designs.
4. **Upcycling Workshops**: Expand on this idea by partnering with local artists who can lead sessions, making it more appealing and engaging for the community.
5. **Community Clean-Up Events**: Provide incentive programs for participants, such as raffle entries or recognition awards, to boost engagement.
6. **Education Campaigns**: Tailor campaigns for different age groups, using age-appropriate messaging and methods to enhance understanding and retention.
7. **Plastic-Free Challenges**: Involve local businesses by offering discounts or promotions to participants, creating a community effort with tangible rewards.
8. **Support Local Artisan Products**: Connect artisans with online marketplaces to broaden their reach and sales, promoting a circular economy.
9. **Rewards Programs**: Build a mobile app dedicated to tracking individuals' sustainable habits, providing insights and rewards for achievements.
10. **Zero-Waste Grocery Stores**: Consider including workshops in these stores to educate customers on zero-waste practices and encourage community engagement.
11. **Legislation and Policy Changes**: Engage with policymakers and present real data on plastic waste reduction impacts to advocate for meaningful changes.
12. **Environmentally Friendly Innovations**: Host hackathons or competitions to stimulate creativity and collaboration in developing sustainable alternatives.
13. **Plastic Bank Initiatives**: Collaborate with local businesses to create a network where people can exchange more types of waste for various community services.
14. **DIY Tutorials**: Offer a platform where community members can share their own tutorials and experiences, fostering a supportive network for sustainable living.
15. **Corporate Sustainability Partnerships**: Encourage companies to share their sustainability stories, motivating others while boosting their brand image.
16. **Public Art Installations**: Use social media campaigns to further engage the public in these projects, encouraging them to participate and share their own creations.
17. **Sustainable Fashion Initiatives**: Create pop-up shops or fashion shows featuring sustainable lines, helping to raise awareness in a fun and engaging way.
18. **Digital Outreach**: Utilize influencers or local celebrities to amplify your message and reach wider audiences, particularly younger populations.
19. **Composting Services**: Develop an educational program on composting benefits to accompany the service, helping customers understand its environmental importance.
20. **Sustainable Event Planning**: Include a checklist for event planners detailing low-plastic options and provide resources to make the transition easier.
Overall, these ideas are solid and can significantly contribute to reducing plastic waste, but implementing them effectively will require collaboration, education, and community involvement. Great job! APPROVE.
---------- TextMessage (summary) ----------
The user requested brainstorming ideas to reduce plastic waste. The final feedback provided by the reviewer highlighted that the ideas were comprehensive, covering various facets such as consumer behavior, community involvement, and corporate responsibility. Specific suggestions for improvement included enhancing refill stations with clear labeling, incentivizing bulk buying through loyalty programs, collaborating on eco-friendly packaging, expanding upcycling workshops with local artists, and engaging in educational campaigns tailored to different age groups. The reviewer approved the ideas overall, noting the importance of collaboration, education, and community involvement in effective implementation.
---------- StopMessage (DiGraphStopAgent) ----------
Digraph execution is complete
TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, created_at=datetime.datetime(2025, 6, 5, 4, 16, 39, 836409, tzinfo=datetime.timezone.utc), content='Brainstorm ways to reduce plastic waste.', type='TextMessage'), TextMessage(source='generator', models_usage=RequestUsage(prompt_tokens=27, completion_tokens=555), metadata={}, created_at=datetime.datetime(2025, 6, 5, 4, 16, 48, 788854, tzinfo=datetime.timezone.utc), content='1. **Refill Stations**: Set up refill stations for common household products such as laundry detergent, shampoo, and cleaning supplies in grocery stores and public spaces.\n\n2. **Bulk Buying Incentives**: Create incentives for consumers to buy in bulk, reducing the amount of packaging waste.\n\n3. **Eco-friendly Packaging**: Encourage companies to develop biodegradable or compostable packaging for their products.\n\n4. **Upcycling Workshops**: Organize community workshops that teach people how to repurpose plastic items into practical or decorative objects.\n\n5. **Community Clean-Up Events**: Host regular community clean-up events focused on collecting plastic waste from parks, beaches, and roadsides.\n\n6. **Education Campaigns**: Launch educational campaigns in schools and communities about the impact of plastic waste and sustainable alternatives.\n\n7. **Plastic-Free Challenges**: Initiate a monthly plastic-free challenge encouraging individuals and families to reduce their plastic consumption.\n\n8. **Support Local Artisan Products**: Promote local artisans who create products from recycled materials, fostering a circular economy.\n\n9. **Rewards Programs**: Develop a rewards program for individuals and businesses who actively reduce their plastic usage, such as discounts or points for using reusable bags and containers.\n\n10. **Zero-Waste Grocery Stores**: Support the establishment of zero-waste grocery stores where customers can bring their own containers and buy loose, unpackaged products.\n\n11. **Legislation and Policy Changes**: Advocate for policies that ban single-use plastics and promote alternatives in both public and private sectors.\n\n12. **Environmentally Friendly Innovations**: Invest in and promote innovations in materials science that create alternatives to plastic from natural materials.\n\n13. **Plastic Bank Initiatives**: Start or support initiatives that allow people to exchange plastic waste for products or services, incentivizing recycling.\n\n14. **DIY Tutorials**: Create and share DIY tutorials for making your own household products to reduce reliance on plastic-packaged goods.\n\n15. **Corporate Sustainability Partnerships**: Encourage collaboration between businesses to share best practices in reducing plastic use and waste.\n\n16. **Public Art Installations**: Organize public art projects using collected plastic waste to raise awareness and promote discussions on plastic pollution.\n\n17. **Sustainable Fashion Initiatives**: Promote clothing and accessories made from recycled plastics, highlighting those companies that commit to eco-friendly practices.\n\n18. **Digital Outreach**: Use social media and digital platforms to raise awareness about the impact of plastic waste and promote sustainable lifestyle choices.\n\n19. **Composting Services**: Establish services that help compost food waste and other biodegradable materials, reducing reliance on plastic bags for disposal.\n\n20. **Sustainable Event Planning**: Collaborate with event planners to create guidelines for low-plastic events, encouraging the use of sustainable materials and practices.', type='TextMessage'), TextMessage(source='reviewer', models_usage=RequestUsage(prompt_tokens=599, completion_tokens=625), metadata={}, created_at=datetime.datetime(2025, 6, 5, 4, 16, 58, 552656, tzinfo=datetime.timezone.utc), content="These ideas provide a comprehensive approach to reducing plastic waste, addressing various aspects such as consumer behavior, community involvement, and corporate responsibility. Here are some feedbacks and suggestions for improvement:\n\n1. **Refill Stations**: Provide clear labeling and education about the environmental benefits of using refill stations to encourage more participation.\n\n2. **Bulk Buying Incentives**: Consider incorporating a loyalty program that rewards frequent bulk buyers with additional discounts or promotions.\n\n3. **Eco-friendly Packaging**: Collaborate with universities and research institutions to foster innovation in eco-friendly packaging designs.\n\n4. **Upcycling Workshops**: Expand on this idea by partnering with local artists who can lead sessions, making it more appealing and engaging for the community.\n\n5. **Community Clean-Up Events**: Provide incentive programs for participants, such as raffle entries or recognition awards, to boost engagement.\n\n6. **Education Campaigns**: Tailor campaigns for different age groups, using age-appropriate messaging and methods to enhance understanding and retention.\n\n7. **Plastic-Free Challenges**: Involve local businesses by offering discounts or promotions to participants, creating a community effort with tangible rewards.\n\n8. **Support Local Artisan Products**: Connect artisans with online marketplaces to broaden their reach and sales, promoting a circular economy.\n\n9. **Rewards Programs**: Build a mobile app dedicated to tracking individuals' sustainable habits, providing insights and rewards for achievements.\n\n10. **Zero-Waste Grocery Stores**: Consider including workshops in these stores to educate customers on zero-waste practices and encourage community engagement.\n\n11. **Legislation and Policy Changes**: Engage with policymakers and present real data on plastic waste reduction impacts to advocate for meaningful changes.\n\n12. **Environmentally Friendly Innovations**: Host hackathons or competitions to stimulate creativity and collaboration in developing sustainable alternatives.\n\n13. **Plastic Bank Initiatives**: Collaborate with local businesses to create a network where people can exchange more types of waste for various community services.\n\n14. **DIY Tutorials**: Offer a platform where community members can share their own tutorials and experiences, fostering a supportive network for sustainable living.\n\n15. **Corporate Sustainability Partnerships**: Encourage companies to share their sustainability stories, motivating others while boosting their brand image.\n\n16. **Public Art Installations**: Use social media campaigns to further engage the public in these projects, encouraging them to participate and share their own creations.\n\n17. **Sustainable Fashion Initiatives**: Create pop-up shops or fashion shows featuring sustainable lines, helping to raise awareness in a fun and engaging way.\n\n18. **Digital Outreach**: Utilize influencers or local celebrities to amplify your message and reach wider audiences, particularly younger populations.\n\n19. **Composting Services**: Develop an educational program on composting benefits to accompany the service, helping customers understand its environmental importance.\n\n20. **Sustainable Event Planning**: Include a checklist for event planners detailing low-plastic options and provide resources to make the transition easier.\n\nOverall, these ideas are solid and can significantly contribute to reducing plastic waste, but implementing them effectively will require collaboration, education, and community involvement. Great job! APPROVE.", type='TextMessage'), TextMessage(source='summary', models_usage=RequestUsage(prompt_tokens=663, completion_tokens=106), metadata={}, created_at=datetime.datetime(2025, 6, 5, 4, 17, 0, 865057, tzinfo=datetime.timezone.utc), content='The user requested brainstorming ideas to reduce plastic waste. The final feedback provided by the reviewer highlighted that the ideas were comprehensive, covering various facets such as consumer behavior, community involvement, and corporate responsibility. Specific suggestions for improvement included enhancing refill stations with clear labeling, incentivizing bulk buying through loyalty programs, collaborating on eco-friendly packaging, expanding upcycling workshops with local artists, and engaging in educational campaigns tailored to different age groups. The reviewer approved the ideas overall, noting the importance of collaboration, education, and community involvement in effective implementation.', type='TextMessage'), StopMessage(source='DiGraphStopAgent', models_usage=None, metadata={}, created_at=datetime.datetime(2025, 6, 5, 4, 17, 0, 866337, tzinfo=datetime.timezone.utc), content='Digraph execution is complete', type='StopMessage')], stop_reason='Stop message received')
🔁 Advanced Example: Cycles With Activation Group Examples#
The following examples demonstrate how to use activation_group
and activation_condition
to handle complex dependency patterns in cyclic graphs, especially when multiple paths lead to the same target node.
Example 1: Loop with Multiple Paths - “All” Activation (A→B→C→B)#
In this scenario, we have A → B → C → B, where B has two incoming edges (from A and from C). By default, B requires all its dependencies to be satisfied before executing.
This example shows a review loop where both the initial input (A) and the feedback (C) must be processed before B can execute again.
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import DiGraphBuilder, GraphFlow
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
# Model client
client = OpenAIChatCompletionClient(model="gpt-4o-mini")
# Create agents for A→B→C→B→E scenario
agent_a = AssistantAgent("A", model_client=client, system_message="Start the process and provide initial input.")
agent_b = AssistantAgent(
"B",
model_client=client,
system_message="Process input from A or feedback from C. Say 'CONTINUE' if it's from A or 'STOP' if it's from C.",
)
agent_c = AssistantAgent("C", model_client=client, system_message="Review B's output and provide feedback.")
agent_e = AssistantAgent("E", model_client=client, system_message="Finalize the process.")
# Build the graph with activation groups
builder = DiGraphBuilder()
builder.add_node(agent_a).add_node(agent_b).add_node(agent_c).add_node(agent_e)
# A → B (initial path)
builder.add_edge(agent_a, agent_b, activation_group="initial")
# B → C
builder.add_edge(agent_b, agent_c, condition="CONTINUE")
# C → B (loop back - different activation group)
builder.add_edge(agent_c, agent_b, activation_group="feedback")
# B → E (exit condition)
builder.add_edge(agent_b, agent_e, condition="STOP")
# Build and create flow
graph = builder.build()
flow = GraphFlow(participants=[agent_a, agent_b, agent_c], graph=graph)
print("=== Example 1: A→B→C→B with 'All' Activation ===")
print("B will exit when it receives a message from C")
# await Console(flow.run_stream(task="Start a review process for a document."))
Example 2: Loop with Multiple Paths - “Any” Activation (A→B→(C1,C2)→B)#
In this more complex scenario, we have A → B → (C1, C2) → B, where:
B fans out to both C1 and C2 in parallel
Both C1 and C2 feed back to B
B uses “any” activation, meaning it executes as soon as either C1 or C2 completes
This is useful for scenarios where you want the fastest response to trigger the next step.
# Create agents for A→B→(C1,C2)→B scenario
agent_a2 = AssistantAgent("A", model_client=client, system_message="Initiate a task that needs parallel processing.")
agent_b2 = AssistantAgent(
"B",
model_client=client,
system_message="Coordinate parallel tasks. Say 'PROCESS' to start parallel work or 'DONE' to finish.",
)
agent_c1 = AssistantAgent("C1", model_client=client, system_message="Handle task type 1. Say 'C1_COMPLETE' when done.")
agent_c2 = AssistantAgent("C2", model_client=client, system_message="Handle task type 2. Say 'C2_COMPLETE' when done.")
agent_e = AssistantAgent("E", model_client=client, system_message="Finalize the process.")
# Build the graph with "any" activation
builder2 = DiGraphBuilder()
builder2.add_node(agent_a2).add_node(agent_b2).add_node(agent_c1).add_node(agent_c2).add_node(agent_e)
# A → B (initial)
builder2.add_edge(agent_a2, agent_b2)
# B → C1 and B → C2 (parallel fan-out)
builder2.add_edge(agent_b2, agent_c1, condition="PROCESS")
builder2.add_edge(agent_b2, agent_c2, condition="PROCESS")
# B → E (exit condition)
builder2.add_edge(agent_b2, agent_e, condition=lambda msg: "DONE" in msg.to_model_text())
# C1 → B and C2 → B (both in same activation group with "any" condition)
builder2.add_edge(
agent_c1, agent_b2, activation_group="loop_back_group", activation_condition="any", condition="C1_COMPLETE"
)
builder2.add_edge(
agent_c2, agent_b2, activation_group="loop_back_group", activation_condition="any", condition="C2_COMPLETE"
)
# Build and create flow
graph2 = builder2.build()
flow2 = GraphFlow(participants=[agent_a2, agent_b2, agent_c1, agent_c2, agent_e], graph=graph2)
print("=== Example 2: A→B→(C1,C2)→B with 'Any' Activation ===")
print("B will execute as soon as EITHER C1 OR C2 completes (whichever finishes first)")
# await Console(flow2.run_stream(task="Start a parallel processing task."))
Example 3: Mixed Activation Groups#
This example shows how different activation groups can coexist in the same graph. We have a scenario where:
Node D receives inputs from multiple sources with different activation requirements
Some dependencies use “all” activation (must wait for all inputs)
Other dependencies use “any” activation (proceed on first input)
This pattern is useful for complex workflows where different types of dependencies have different urgency levels.
# Create agents for mixed activation scenario
agent_a3 = AssistantAgent("A", model_client=client, system_message="Provide critical input that must be processed.")
agent_b3 = AssistantAgent("B", model_client=client, system_message="Provide secondary critical input.")
agent_c3 = AssistantAgent("C", model_client=client, system_message="Provide optional quick input.")
agent_d3 = AssistantAgent("D", model_client=client, system_message="Process inputs based on different priority levels.")
# Build graph with mixed activation groups
builder3 = DiGraphBuilder()
builder3.add_node(agent_a3).add_node(agent_b3).add_node(agent_c3).add_node(agent_d3)
# Critical inputs that must ALL be present (activation_group="critical", activation_condition="all")
builder3.add_edge(agent_a3, agent_d3, activation_group="critical", activation_condition="all")
builder3.add_edge(agent_b3, agent_d3, activation_group="critical", activation_condition="all")
# Optional input that can trigger execution on its own (activation_group="optional", activation_condition="any")
builder3.add_edge(agent_c3, agent_d3, activation_group="optional", activation_condition="any")
# Build and create flow
graph3 = builder3.build()
flow3 = GraphFlow(participants=[agent_a3, agent_b3, agent_c3, agent_d3], graph=graph3)
print("=== Example 3: Mixed Activation Groups ===")
print("D will execute when:")
print("- BOTH A AND B complete (critical group with 'all' activation), OR")
print("- C completes (optional group with 'any' activation)")
print("This allows for both required dependencies and fast-path triggers.")
# await Console(flow3.run_stream(task="Process inputs with mixed priority levels."))
Key Takeaways for Activation Groups#
activation_group
: Groups edges that point to the same target node, allowing you to define different dependency patterns.activation_condition
:"all"
(default): Target node waits for ALL edges in the group to be satisfied"any"
: Target node executes as soon as ANY edge in the group is satisfied
Use Cases:
Cycles with multiple entry points: Different activation groups prevent conflicts
Priority-based execution: Mix “all” and “any” conditions for different urgency levels
Parallel processing with early termination: Use “any” to proceed with the fastest result
Best Practices:
Use descriptive group names (
"critical"
,"optional"
,"feedback"
, etc.)Keep activation conditions consistent within the same group
Test your graph logic with different execution paths
These patterns enable sophisticated workflow control while maintaining clear, understandable execution semantics.