Agent Orchestration: Coordinating Multiple Agents
In our financial compliance example, we’ve successfully implemented a human-in-the-loop agent that processes transactions and flags suspicious ones for human approval. This works well for basic compliance checking, but what if we need to provide detailed summary reports after all transactions are processed?
We could expand the system message of our finance_bot
to include this functionality, but this approach isn’t scalable as requirements grow more complex. The finance_bot
would have multiple responsibilities, making it harder to maintain and extend.
The Need for Specialized Agents
As our financial compliance system evolves, we might need to:
- Generate formatted summary reports of all transactions
- Perform risk analysis on transaction patterns
- Create visualizations of financial data
- Send notifications to relevant stakeholders
Each of these tasks requires different specialized knowledge and skills. This is where AG2’s orchestration patterns come in - they allow us to coordinate multiple specialized agents to work together seamlessly.
Introducing the Group Chat Pattern
AG2 offers several orchestration patterns, and for our evolving financial compliance system, the Group Chat pattern is particularly powerful. It allows specialized agents to collaborate with dynamic handoffs to achieve complex workflows.
An Analogy for Group Chat Pattern:
Continuing our hospital treatment system analogy from the HITL. Think of the Group Chat pattern like a hospital emergency in the hospital:
- The patient first sees whichever specialist is most appropriate (a triage agent)
- Each specialist (specialized agent) handles a specific aspect of patient care
- After completing their work, specialists can explicitly transfer the patient to another specialist based on what they found (agent handoffs)
- If a specialist doesn’t specify who should see the patient next, we can revert to the hospital coordinator (Group chat manager) who can review the patient’s chart and decide which specialist would be most appropriate
- The patient record follows them through the entire process (shared context)
- The entire system works together to ensure the patient receives the right care at the right time
This pattern leverages specialized skills while maintaining a cohesive workflow across multiple participants, with both direct handoffs and intelligent coordination when needed.
From Concept to Implementation
Implementing a group chat in AG2 is a simple two-step process:
- First, create a pattern that defines how agents will interact
- Then, initialize the group chat using the pattern
The pattern defines the orchestration logic - which agents are involved, who speaks first, and how to transition between agents. AG2 provides several pre-defined patterns to choose from:
- DefaultPattern: A minimal pattern for simple agent interactions where the handoffs and transitions needs to be explicitly defined
- AutoPattern: Automatically selects the next speaker based on conversation context
- RoundRobinPattern: Agents speak in a defined sequence
- RandomPattern: Randomly selects the next speaker
- ManualPattern: Allows human selection of the next speaker
The easiest pattern to get started with is the AutoPattern, where a group manager agent automatically selects agents to speak by evaluating the messages in the chat and the descriptions of the agents. This creates a natural workflow where the most appropriate agent responds based on the conversation context.
Here’s how you implement a basic group chat:
Enhancing Our Financial Compliance System with Group Chat
Now that we understand the group chat pattern, let’s see how it solves our challenge of adding specialized summary reporting to our financial compliance system.
The Challenge
In our Human in the Loop example, we built a finance_bot
that could process transactions and get human approval for suspicious ones. However, we now need professional, formatted summary reports of all the transactions.
Our Group Chat Solution
Here’s how we’ll enhance our system:
- Keep the
finance_bot
focused on transaction processing and human approval - Create a new
summary_bot
specialized in generating formatted transaction reports - Use the group chat with
AutoPattern
pattern to automatically transition fromfinance_bot
tosummary_bot
when all transactions are processed - Maintain human oversight for suspicious transaction approval and to terminate the conversation
Implementation: Creating the Necessary Agents
Let’s create a new specialized agent for generating summary reports. We’ll also keep our existing finance_bot
for transaction processing and a human agent for oversight.
Initiating the Group Chat
Now let’s set up our group chat with these specialized agents. We will be using the AutoPattern
to manage the conversation flow.
Understanding the Group Chat Workflow
When we run this enhanced financial compliance system, here’s what happens:
-
Initial Processing: The
finance_bot
analyzes each transaction- Regular transactions are automatically approved
- Suspicious transactions are flagged for human review
-
Human Review: The human agent reviews flagged transactions
- The human can approve or reject each transaction
- This provides the crucial oversight required for compliance
-
Handoff to Summary Agent: After all transactions are processed, the Group Chat manager transitions control to the
summary_bot
- This transition happens automatically based on conversation context
- The
summary_bot
has access to the full conversation history
-
Report Generation: The
summary_bot
creates a report summarizing all transactions in a markdown table -
Final Review: The human agent reviews the summary and terminates the conversation
Complete Code Example
Here’s the complete, ready-to-run code for our enhanced financial compliance system using the Group Chat pattern:
???+ info “Complete Code Example”
How to Run This Example
- Save the code above to a file (e.g.,
financial_compliance.py
) - Set your OpenAI API key in your environment variable or use your preferred model provider
- Make sure you have AG2 installed:
pip install ag2[openai]
- Run the script: python
financial_compliance.py
Example Output
When you run this code, you’ll see a workflow similar to this:
Automatic Termination in Group Chats
In the example above, our workflow always ends with human review and manual termination.
However, in production systems, it would be more efficient to automatically terminate the workflow once all tasks are completed and seek for human input only for suspicious transactions. With AG2, we can easily achieve this by using a termination condition.
Let’s enhance our financial compliance system to automatically end after generating the summary report.
Creating a Termination Condition
First, we’ll modify our summary bot’s system message to include a special marker at the end of its output:
Next, we’ll define a termination function that checks for this marker:
The above function checks if the content of the message contains our termination marker. If it does, it returns True
, indicating that the conversation should end.
Finally, we’ll pass this termination function to the group manager:
Updated Flow with Automatic Termination
With these changes, our workflow becomes more streamlined:
Now the human agent only participates when needed for transaction approval, and the workflow automatically terminates after the summary report is generated.
Complete Code Example with Automatic Termination
Here’s the updated code that incorporates automatic termination:
???+ info “Complete Code Example with Automatic Termination”
Example Output with Automatic Termination
With automatic termination, the output will look similar to before, but the workflow terminates automatically after the summary is generated:
Notice that the conversation automatically ends after the summary is generated, without requiring the human to type “exit”.
Next Steps: Extending the System
Our financial compliance system demonstrates the power of the group chat pattern, but we’ve only scratched the surface. In our next section, we’ll explore how to enhance our system with specialized tools.
One common requirement in financial systems is detecting duplicate payments and avoiding them. Let’s dive into the next section and see how we can integrate specialized tools with our group chat agents to build even more powerful financial compliance workflows!