Agents Working Together: Multi-Agent Systems, Collaboration Patterns & A2A Protocol

Michael BrenndoerferJuly 25, 202517 min read

Learn how multiple AI agents collaborate through specialization, parallel processing, and coordination. Explore cooperation patterns including sequential handoff, iterative refinement, and consensus building, plus real frameworks like Google's A2A Protocol.

Agents Working Together

Throughout this handbook, you've built a capable personal assistant that can reason, use tools, remember information, maintain state, interact with its environment, and even make plans. But what if instead of one agent doing everything, you had multiple agents working together, each specializing in what it does best?

Think about how humans collaborate. When you're planning a vacation, you might ask a travel expert for destination recommendations, a financial advisor about budgeting, and a local guide for insider tips. Each person brings specialized knowledge, and together they help you plan better than any single person could alone. AI agents can work the same way.

In this chapter, we'll explore what it means for multiple AI agents to cooperate. You'll see how agents can divide work, share information, and coordinate their actions to solve problems more effectively than a single agent working alone. We'll start with the fundamental concept of cooperation, then look at practical ways agents can work together, and finally examine real frameworks that make multi-agent collaboration possible.

Why Multiple Agents?

Before diving into how agents cooperate, let's understand why you'd want multiple agents in the first place. Our personal assistant has grown quite capable, but there are scenarios where a team of specialized agents makes more sense than one generalist.

Specialization Creates Expertise

Imagine you ask your assistant: "Research the best laptop for video editing under $2000, check if it's in stock locally, and schedule a time for me to visit the store."

This single request involves three distinct capabilities:

  1. Research Agent: Needs deep knowledge of hardware specs, performance benchmarks, and current market prices
  2. Inventory Agent: Must check real-time stock across multiple stores and compare availability
  3. Scheduling Agent: Requires access to your calendar and the store's hours

You could build one agent that does all three, but each capability requires different tools, different knowledge, and different reasoning approaches. A research agent benefits from access to product reviews and technical specifications. An inventory agent needs real-time connections to retail systems. A scheduling agent works best with calendar APIs and time-zone handling.

By splitting these into separate agents, each can be optimized for its specific task. The research agent can use specialized prompts that encourage detailed technical analysis. The inventory agent can handle API rate limits and retries without affecting the others. The scheduling agent can manage complex calendar logic independently.

Parallel Processing

When agents work together, they can tackle multiple tasks simultaneously. While one agent researches laptops, another could be checking your calendar availability, and a third could be looking up store locations. This parallelism makes the overall task complete faster than if a single agent had to do everything sequentially.

Robustness Through Redundancy

Multiple agents can also provide checks and balances. One agent might generate a recommendation, while another reviews it for accuracy or potential issues. This is similar to how software teams have code reviewers, or how important decisions often involve multiple people.

Let's see a simple example of how this might work in practice.

A Simple Collaboration Scenario

Let's extend our personal assistant with a basic multi-agent setup. We'll create two specialized agents:

  • User Interface Agent: Handles all interaction with you, understanding your requests and presenting results
  • Task Execution Agent: Works in the background on complex tasks that might take time

Here's how they might collaborate on a research request:

In[3]:
Code
## Using Claude Sonnet 4.5 for its superior agent reasoning and coordination
from anthropic import Anthropic
import json

client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

## User Interface Agent - handles conversation
def ui_agent(user_message, task_status=None):
    """
    The UI agent talks to the user and coordinates with the task agent.
    """
    system_prompt = """You are a friendly assistant that helps users with their requests.
    When a user asks for something that requires research or complex work, 
    you should acknowledge it and let them know the task agent is working on it.
    When you receive results from the task agent, present them clearly to the user."""
    
    messages = [{"role": "user", "content": user_message}]
    
    if task_status:
        # Include status update from task agent
        messages.append({
            "role": "assistant", 
            "content": f"Task update: {task_status}"
        })
    
    response = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        system=system_prompt,
        messages=messages
    )
    
    return response.content[0].text

## Task Execution Agent - does the heavy lifting
def task_agent(task_description):
    """
    The task agent focuses on executing complex tasks without worrying about user interaction.
    """
    system_prompt = """You are a task execution specialist. 
    You receive task descriptions and work through them methodically.
    Focus on accuracy and thoroughness. Return structured results."""
    
    response = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=2048,
        system=system_prompt,
        messages=[{"role": "user", "content": task_description}]
    )
    
    return response.content[0].text

## Coordination function
def handle_user_request(user_input):
    """
    Coordinates between UI and task agents.
    """
    # Step 1: UI agent receives and acknowledges request
    ui_response = ui_agent(user_input)
    print(f"UI Agent: {ui_response}")
    
    # Step 2: Determine if we need the task agent
    if "research" in user_input.lower() or "analyze" in user_input.lower():
        print("\n[System: Delegating to task agent...]\n")
        
        # Step 3: Task agent works on it
        task_result = task_agent(user_input)
        print(f"Task Agent: {task_result}")
        
        # Step 4: UI agent presents results
        final_response = ui_agent(
            "Present these results to the user in a friendly way",
            task_status=task_result
        )
        print(f"\nUI Agent: {final_response}")
    
    return ui_response

## Example usage
handle_user_request("Research the top 3 programming languages for data science and explain why")
Out[3]:
Console
UI Agent: I'll research the top 3 programming languages for data science and explain why they're preferred. Let me gather that information for you.

---

Based on current industry trends and usage, here are the **top 3 programming languages for data science**:

## 1. **Python** 🐍
**Why it's #1:**
- **Rich ecosystem**: Extensive libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and PyTorch
- **Easy to learn**: Simple, readable syntax makes it accessible for beginners
- **Versatile**: Works for data analysis, machine learning, deep learning, and web deployment
- **Strong community**: Massive support, tutorials, and active development
- **Industry standard**: Most widely adopted in both academia and industry

## 2. **R** 📊
**Why it's popular:**
- **Statistical focus**: Built specifically for statistical computing and data analysis
- **Visualization**: Exceptional plotting capabilities with ggplot2 and other packages
- **Specialized packages**: Over 18,000+ packages on CRAN for specific statistical methods
- **Academic roots**: Widely used in research and statistical modeling
- **Best for**: Statistical analysis, biostatistics, and academic research

## 3. **SQL** 🗄️
**Why it's essential:**
- **Data retrieval**: The standard language for querying databases
- **Universal skill**: Works across all major database systems (MySQL, PostgreSQL, etc.)
- **Big data**: Essential for working with large datasets stored in databases
- **Integration**: Often used alongside Python or R for complete data workflows
- **Job requirement**: Nearly every data science position requires SQL knowledge

**The verdict**: Most data scientists use a combination of these languages—Python or R for analysis and modeling, and SQL for data extraction and management.

[System: Delegating to task agent...]

Task Agent: # Top 3 Programming Languages for Data Science

## 1. **Python**

### Why It Dominates:
- **Rich Ecosystem**: Comprehensive libraries including NumPy, Pandas, Scikit-learn, TensorFlow, PyTorch, and Matplotlib
- **Ease of Learning**: Clean, readable syntax makes it accessible for beginners and researchers without CS backgrounds
- **Community Support**: Largest data science community with extensive documentation, tutorials, and Stack Overflow support
- **Versatility**: Handles everything from data cleaning to machine learning to deployment
- **Industry Standard**: Most widely adopted in both academia and industry (70%+ of data scientists use it)

### Key Use Cases:
- Machine learning and deep learning
- Data visualization
- Statistical analysis
- Web scraping and automation

---

## 2. **R**

### Why It Excels:
- **Statistical Foundation**: Built by statisticians for statistics, with unmatched statistical modeling capabilities
- **Visualization Power**: ggplot2 and other packages create publication-quality graphics
- **Specialized Packages**: Over 18,000 CRAN packages for specific statistical methods
- **Academic Preference**: Dominant in research institutions and biostatistics
- **Data Manipulation**: dplyr and tidyverse provide elegant data wrangling tools

### Key Use Cases:
- Statistical analysis and hypothesis testing
- Biostatistics and clinical trials
- Academic research
- Advanced data visualization

---

## 3. **SQL**

### Why It's Essential:
- **Data Access**: The universal language for querying databases where data actually lives
- **Performance**: Optimized for handling large-scale data retrieval and aggregation
- **Universal Skill**: Required in virtually every data role; works across all major database systems
- **Integration**: Works alongside Python/R for complete data pipelines
- **Business Intelligence**: Powers dashboards, reports, and analytics platforms

### Key Use Cases:
- Extracting data from relational databases
- Data warehousing and ETL processes
- Initial data exploration and filtering
- Production data pipelines

---

## Summary Recommendation:
- **Start with Python** for the broadest applicability
- **Add R** if working in statistics-heavy or academic environments
- **Master SQL** as a fundamental skill—it's non-negotiable for accessing real-world data

UI Agent: 

Most professional data scientists use **Python + SQL** as their core toolkit, with R as a valuable supplement for specialized statistical work.
"I'll research the top 3 programming languages for data science and explain why they're preferred. Let me gather that information for you.\n\n---\n\nBased on current industry trends and usage, here are the **top 3 programming languages for data science**:\n\n## 1. **Python** 🐍\n**Why it's #1:**\n- **Rich ecosystem**: Extensive libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and PyTorch\n- **Easy to learn**: Simple, readable syntax makes it accessible for beginners\n- **Versatile**: Works for data analysis, machine learning, deep learning, and web deployment\n- **Strong community**: Massive support, tutorials, and active development\n- **Industry standard**: Most widely adopted in both academia and industry\n\n## 2. **R** 📊\n**Why it's popular:**\n- **Statistical focus**: Built specifically for statistical computing and data analysis\n- **Visualization**: Exceptional plotting capabilities with ggplot2 and other packages\n- **Specialized packages**: Over 18,000+ packages on CRAN for specific statistical methods\n- **Academic roots**: Widely used in research and statistical modeling\n- **Best for**: Statistical analysis, biostatistics, and academic research\n\n## 3. **SQL** 🗄️\n**Why it's essential:**\n- **Data retrieval**: The standard language for querying databases\n- **Universal skill**: Works across all major database systems (MySQL, PostgreSQL, etc.)\n- **Big data**: Essential for working with large datasets stored in databases\n- **Integration**: Often used alongside Python or R for complete data workflows\n- **Job requirement**: Nearly every data science position requires SQL knowledge\n\n**The verdict**: Most data scientists use a combination of these languages—Python or R for analysis and modeling, and SQL for data extraction and management."

Let's unpack what's happening here. When you make a request, the UI agent receives it first. This agent is optimized for conversation. It knows how to interpret your intent and communicate clearly. If the request requires deep work (research, analysis, complex calculations), the UI agent delegates to the task agent.

The task agent doesn't worry about being conversational. It focuses purely on executing the task accurately and thoroughly. Once it completes the work, it returns structured results to the UI agent, which then presents them to you in a friendly, understandable way.

This division of labor has several benefits:

  • The UI agent stays responsive: It can immediately acknowledge your request rather than going silent while processing
  • The task agent can take its time: It can use longer reasoning chains or multiple tool calls without worrying about keeping you engaged
  • Each agent has a clear purpose: The UI agent optimizes for communication; the task agent optimizes for accuracy

Patterns of Cooperation

Now that you've seen a basic example, let's explore different ways agents can work together. These patterns emerge repeatedly in multi-agent systems.

Sequential Handoff

The simplest pattern is a relay race: Agent A completes its part, then hands off to Agent B, which does its part, then hands off to Agent C.

User Request → Agent A (Planning) → Agent B (Execution) → Agent C (Verification) → Result

Our example above used this pattern. The UI agent received the request, handed it to the task agent, then received the results back to present to you.

This pattern works well when tasks have clear stages that must happen in order. For instance:

  1. Planning Agent: Breaks down "plan my weekend" into specific tasks
  2. Booking Agent: Handles reservations and purchases
  3. Confirmation Agent: Verifies everything is set and sends you a summary

Each agent specializes in one stage of the pipeline.

Parallel Execution

When tasks are independent, agents can work simultaneously:

┌─ Agent A (Research) ─┐
User Request ─────┤                        ├─→ Combine Results → Final Answer
                    └─ Agent B (Calculate) ─┘

Imagine you ask: "What's the best time to launch our product based on market trends and our budget constraints?"

  • Market Research Agent: Analyzes industry trends, competitor launches, seasonal patterns
  • Financial Agent: Calculates budget implications, revenue projections, cost analysis

Both agents can work simultaneously because they're analyzing different aspects. Once both complete, a coordinator agent combines their insights into a single recommendation.

Iterative Refinement

Sometimes agents work in cycles, each improving on the previous agent's output:

Draft Agent → Review Agent → Draft Agent → Review Agent → Final Output

This is like having a writer and an editor collaborate. The draft agent generates content, the review agent suggests improvements, the draft agent incorporates feedback, and the cycle continues until the output meets quality standards.

Here's a simple example:

In[4]:
Code
## Using Claude Sonnet 4.5 for iterative refinement between agents
def draft_agent(topic, previous_feedback=None):
    """
    Generates content drafts, incorporating feedback if provided.
    """
    system_prompt = """You are a content writer. Create clear, engaging content.
    If you receive feedback, revise your work to address the concerns."""
    
    if previous_feedback:
        prompt = f"Topic: {topic}\n\nPrevious feedback: {previous_feedback}\n\nRevise your draft based on this feedback."
    else:
        prompt = f"Write a brief explanation of: {topic}"
    
    response = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        system=system_prompt,
        messages=[{"role": "user", "content": prompt}]
    )
    
    return response.content[0].text

def review_agent(draft):
    """
    Reviews content and provides constructive feedback.
    """
    system_prompt = """You are a content reviewer. Evaluate drafts for:
    - Clarity and accuracy
    - Completeness
    - Tone and readability
    
    Provide specific, actionable feedback. If the draft is excellent, say so."""
    
    response = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=512,
        system=system_prompt,
        messages=[{"role": "user", "content": f"Review this draft:\n\n{draft}"}]
    )
    
    return response.content[0].text

def collaborative_writing(topic, max_iterations=2):
    """
    Draft and review agents collaborate to create polished content.
    """
    draft = draft_agent(topic)
    print(f"Initial Draft:\n{draft}\n")
    
    for i in range(max_iterations):
        feedback = review_agent(draft)
        print(f"Review {i+1}:\n{feedback}\n")
        
        if "excellent" in feedback.lower():
            print("Draft approved!")
            break
            
        draft = draft_agent(topic, feedback)
        print(f"Revised Draft {i+1}:\n{draft}\n")
    
    return draft

## Example
final_content = collaborative_writing("How do neural networks learn?")
Out[4]:
Console
Initial Draft:
# How Do Neural Networks Learn?

Neural networks learn through a process called **training**, which mimics how our brains strengthen connections between neurons based on experience.

## The Basic Process

**1. Making Predictions**
The network receives input data (like an image) and makes an initial guess by passing information through layers of interconnected artificial neurons. Each connection has a "weight" that determines its influence.

**2. Measuring Mistakes**
The network compares its prediction to the correct answer using a "loss function"—essentially calculating how wrong it was.

**3. Adjusting Weights**
Using an algorithm called **backpropagation**, the network traces the error backward through its layers, determining which weights contributed most to the mistake. Then, using **gradient descent**, it adjusts these weights slightly to reduce future errors—like fine-tuning thousands of knobs simultaneously.

**4. Repeating**
This cycle repeats thousands or millions of times with different examples. Gradually, the network discovers patterns in the data—like recognizing edges, shapes, and eventually entire objects in images.

## The Key Insight

Neural networks don't follow programmed rules. Instead, they **learn patterns from examples**. Feed a network thousands of cat photos labeled "cat," and it learns to identify features that make something cat-like—without anyone explicitly programming what "cat" means.

This learning process enables neural networks to tackle complex tasks like language translation, speech recognition, and medical diagnosis that would be nearly impossible to solve with traditional programming.

Review 1:
# Content Review

## Overall Assessment
This is an **excellent draft** that successfully explains a complex topic in accessible terms. The structure is logical, the analogies are effective, and the writing is clear and engaging.

## Strengths

✓ **Perfect target audience pitch** - Assumes no prior knowledge while remaining substantive
✓ **Effective analogy** - The brain comparison in the opening immediately grounds the concept
✓ **Clear structure** - Numbered steps create an easy-to-follow learning path
✓ **Smart use of formatting** - Bold terms and headers aid scanning and comprehension
✓ **Strong conclusion** - "The Key Insight" section connects theory to practical applications
✓ **Appropriate length** - Comprehensive without overwhelming

## Minor Suggestions for Enhancement

### 1. Technical Precision (Optional)
The phrase "traces the error backward" is metaphorical but slightly vague. Consider:
> "Using an algorithm called **backpropagation**, the network **calculates how each weight contributed to the error** by working backward through its layers."

### 2. Strengthen the Analogy
The "fine-tuning thousands of knobs" is vivid. You might add scale context:
> "...like fine-tuning thousands (or even millions) of knobs simultaneously."

### 3. Minor Clarification
In "The Key Insight" section, consider specifying:
> "Feed a network thousands of cat photos **correctly** labeled 'cat'..."
This emphasizes the importance of accurate training data.

### 4. Consider Adding (Optional)
A brief sentence about limitations or challenges could add balance:
> "Of course, this learning process requires substantial computational power and quality training data—but once trained, networks can process new information remarkably quickly."

## Verdict
**Approve with optional minor refinements.** This draft effectively achieves its educational goal. The suggested changes are truly optional—the piece works well as written. The clarity, accuracy, and accessibility are all excellent.

Draft approved!

This pattern is powerful for tasks where quality matters more than speed. The review agent can catch errors, suggest improvements, or ensure the output meets specific criteria, while the draft agent focuses on generation.

Consensus Building

When you need a reliable answer, multiple agents can independently solve the same problem, then vote or discuss to reach consensus:

┌─ Agent A ─┐
                    ├─ Agent B ─┤
Problem ───────┤            ├─→ Compare & Decide → Final Answer
                    ├─ Agent C ─┤
                    └─ Agent D ─┘

This is particularly useful for critical decisions or when you want to reduce the chance of errors. If three out of four agents agree on an answer, you can be more confident it's correct.

Real-World Multi-Agent Frameworks

The patterns we've discussed are useful concepts, but implementing multi-agent systems from scratch can be complex. Fortunately, several frameworks have emerged to make this easier. Let's look at some of the most important ones.

The Agent-to-Agent (A2A) Protocol

One of the most significant developments in multi-agent systems is the Agent-to-Agent (A2A) Protocol, developed by Google as an open standard. Think of A2A as a common language that allows different AI agents to discover each other, understand what each can do, and work together, even if they were built by different teams using different technologies.

The key innovation of A2A is the concept of Agent Cards. Just as a business card tells you what someone does and how to contact them, an Agent Card describes an agent's capabilities, what inputs it accepts, what outputs it produces, and how other agents can communicate with it.

Here's what an Agent Card might look like conceptually:

{
  "agent_name": "Research Assistant",
  "capabilities": [
    "web_search",
    "document_analysis",
    "fact_checking"
  ],
  "input_format": {
    "type": "text",
    "max_length": 2000
  },
  "output_format": {
    "type": "structured_report",
    "includes": ["sources", "summary", "confidence_score"]
  },
  "endpoint": "https://api.example.com/research-agent",
  "authentication": "bearer_token"
}

With A2A, when your personal assistant needs research help, it can:

  1. Discover available research agents by querying an agent registry
  2. Understand what each agent can do by reading their Agent Cards
  3. Communicate with the chosen agent using the standardized protocol
  4. Receive results in a predictable format

This standardization is crucial because it means agents from different organizations, built with different frameworks, can still work together. Your assistant built with Anthropic's Claude could seamlessly collaborate with a specialized research agent built with OpenAI's GPT-5 or a data analysis agent built with Google's Gemini.

The A2A protocol also handles important practical concerns:

  • Security: Supports standard authentication and encrypted communication
  • Task Management: Provides structures for defining, tracking, and completing collaborative tasks
  • Modality Support: Works with text, audio, video, and other data types

Other Collaboration Frameworks

While A2A focuses on agent-to-agent communication, other frameworks address different aspects of multi-agent systems:

Model Context Protocol (MCP): Developed by Anthropic, MCP focuses on connecting agents with tools and data sources. While A2A helps agents talk to each other, MCP helps agents access the resources they need. In practice, you might use both: MCP to give your agents access to databases and APIs, and A2A to let those agents coordinate with each other.

Agent Development Kit (ADK): Google's ADK is a toolkit for building agents. Think of it this way: ADK helps you build individual agents, while A2A helps those agents communicate. They're complementary. ADK is the construction tool, A2A is the communication protocol.

LangGraph: A framework for building stateful, multi-agent applications with explicit control flow. LangGraph excels at defining complex workflows where agents need to maintain state and follow specific patterns of interaction.

Bringing It Together: A Multi-Agent Example

Let's build a more sophisticated example that demonstrates several cooperation patterns working together. We'll create a small team of agents that helps you plan a dinner party:

In[5]:
Code
## Using Claude Sonnet 4.5 for multi-agent coordination
from anthropic import Anthropic
from datetime import datetime

client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

class DinnerPlanningTeam:
    """
    A team of specialized agents that collaborate to plan dinner parties.
    """
    
    def __init__(self):
        self.model = "claude-sonnet-4-5"
    
    def coordinator_agent(self, user_request):
        """
        Coordinates the overall planning process and delegates to specialists.
        """
        system_prompt = """You are a dinner party planning coordinator.
        Break down the user's request into specific tasks for specialist agents:
        - Guest management (invitations, dietary restrictions)
        - Menu planning (recipes, ingredients)
        - Shopping (what to buy, where to buy it)
        
        Return a JSON list of tasks with agent assignments."""
        
        response = client.messages.create(
            model=self.model,
            max_tokens=1024,
            system=system_prompt,
            messages=[{"role": "user", "content": user_request}]
        )
        
        return response.content[0].text
    
    def guest_agent(self, task_description):
        """
        Handles guest-related tasks.
        """
        system_prompt = """You are a guest management specialist.
        Handle invitations, track RSVPs, note dietary restrictions and preferences.
        Be organized and detail-oriented."""
        
        response = client.messages.create(
            model=self.model,
            max_tokens=512,
            system=system_prompt,
            messages=[{"role": "user", "content": task_description}]
        )
        
        return response.content[0].text
    
    def menu_agent(self, task_description, guest_info=None):
        """
        Plans the menu based on guests and preferences.
        """
        system_prompt = """You are a menu planning specialist.
        Create balanced, delicious menus that accommodate dietary restrictions.
        Consider preparation time and skill level."""
        
        context = task_description
        if guest_info:
            context += f"\n\nGuest information: {guest_info}"
        
        response = client.messages.create(
            model=self.model,
            max_tokens=1024,
            system=system_prompt,
            messages=[{"role": "user", "content": context}]
        )
        
        return response.content[0].text
    
    def shopping_agent(self, menu_details):
        """
        Creates shopping lists from menu plans.
        """
        system_prompt = """You are a shopping specialist.
        Convert menu plans into organized shopping lists.
        Group items by store section and estimate quantities."""
        
        response = client.messages.create(
            model=self.model,
            max_tokens=1024,
            system=system_prompt,
            messages=[{"role": "user", "content": f"Create a shopping list for: {menu_details}"}]
        )
        
        return response.content[0].text
    
    def plan_dinner_party(self, user_request):
        """
        Orchestrates the full dinner planning process.
        """
        print("=== Dinner Party Planning Team ===\n")
        
        # Step 1: Coordinator breaks down the request
        print("Coordinator: Analyzing your request...")
        tasks = self.coordinator_agent(user_request)
        print(f"Plan: {tasks}\n")
        
        # Step 2: Guest agent works on guest list
        print("Guest Agent: Managing guest details...")
        guest_info = self.guest_agent("Compile guest information and dietary needs")
        print(f"Guest Info: {guest_info}\n")
        
        # Step 3: Menu agent creates menu (depends on guest info)
        print("Menu Agent: Planning the menu...")
        menu = self.menu_agent("Plan a dinner party menu", guest_info)
        print(f"Menu: {menu}\n")
        
        # Step 4: Shopping agent creates list (depends on menu)
        print("Shopping Agent: Creating shopping list...")
        shopping_list = self.shopping_agent(menu)
        print(f"Shopping List: {shopping_list}\n")
        
        # Step 5: Coordinator summarizes everything
        print("Coordinator: Finalizing your dinner party plan...")
        summary = self.coordinator_agent(
            f"Summarize this dinner party plan:\nGuests: {guest_info}\nMenu: {menu}\nShopping: {shopping_list}"
        )
        print(f"Final Plan: {summary}")
        
        return {
            "guests": guest_info,
            "menu": menu,
            "shopping": shopping_list,
            "summary": summary
        }

## Example usage
team = DinnerPlanningTeam()
result = team.plan_dinner_party(
    "I want to host a dinner party for 6 people next Saturday. "
    "Two guests are vegetarian and one is gluten-free. "
    "I'm a decent cook but nothing too complicated."
)
Out[5]:
Console
=== Dinner Party Planning Team ===

Coordinator: Analyzing your request...
Plan: ```json
{
  "tasks": [
    {
      "agent": "guest_manager",
      "task": "Track guest list and dietary requirements",
      "details": {
        "total_guests": 6,
        "dietary_restrictions": [
          "2 vegetarian guests",
          "1 gluten-free guest"
        ],
        "event_date": "next Saturday"
      },
      "priority": "high"
    },
    {
      "agent": "menu_planner",
      "task": "Create menu suitable for all dietary needs",
      "details": {
        "constraints": [
          "Must accommodate vegetarians",
          "Must have gluten-free options",
          "Intermediate cooking skill level",
          "Nothing too complicated"
        ],
        "servings": 6,
        "meal_type": "dinner party"
      },
      "priority": "high",
      "depends_on": ["guest_manager"]
    },
    {
      "agent": "menu_planner",
      "task": "Provide recipes with clear instructions",
      "details": {
        "requirements": [
          "Step-by-step instructions",
          "Timing guidance for coordination",
          "Make-ahead suggestions if possible"
        ]
      },
      "priority": "medium",
      "depends_on": ["menu_planner_menu_creation"]
    },
    {
      "agent": "shopping_coordinator",
      "task": "Generate comprehensive shopping list",
      "details": {
        "based_on": "finalized menu",
        "quantities": "for 6 people",
        "categories": [
          "Fresh produce",
          "Proteins",
          "Pantry items",
          "Gluten-free specialty items"
        ]
      },
      "priority": "medium",
      "depends_on": ["menu_planner"]
    },
    {
      "agent": "shopping_coordinator",
      "task": "Recommend shopping locations and timing",
      "details": {
        "considerations": [
          "Where to find gluten-free products",
          "When to shop for freshness",
          "Budget-friendly options"
        ]
      },
      "priority": "low",
      "depends_on": ["shopping_coordinator_list"]
    }
  ],
  "workflow_summary": "Guest requirements captured → Menu designed → Recipes provided → Shopping list created → Store recommendations given"
}
```

Guest Agent: Managing guest details...
Guest Info: # Guest Information & Dietary Needs Compilation

I'll help you organize guest information and dietary requirements. Let me create a comprehensive tracking system for you.

## Guest Information Template

### Current Guest List Status
*Please provide your guest list, and I'll help organize it with the following information:*

| Guest Name | Contact Info | Invitation Status | RSVP Status | Attending | Dietary Restrictions | Special Notes |
|------------|--------------|-------------------|-------------|-----------|---------------------|---------------|
| | | | | | | |

---

## Dietary Categories to Track

### 🥗 Common Dietary Restrictions
- **Vegetarian** (no meat, poultry, fish)
- **Vegan** (no animal products)
- **Gluten-Free** (celiac or sensitivity)
- **Dairy-Free/Lactose Intolerant**
- **Nut Allergies** (specify which nuts)
- **Shellfish Allergies**
- **Other Food Allergies**
- **Kosher**
- **Halal**
- **Low-Sodium**
- **Diabetic-Friendly**
- **Other Medical Restrictions**

### 👶 Special Considerations
- Children's meal preferences
- Baby food needs
- High chairs required
- Texture modifications (elderly guests)

---

## Information I Need From You

To compile your guest list effectively, please share:

1. **Guest names and contact information** (email/phone)
2. **Invitation sent dates**
3. **RSVP deadline**
4. **Current RSVP responses**
5. **Any known dietary restrictions or allergies**
6. **Plus-ones or additional guests**
7. **Seating preferences or constraints**

---

## Next Steps

Once you provide guest details, I can:
- ✅ Create an organized master list
- ✅ Summarize dietary restrictions by category
- ✅ Calculate meal counts for catering
- ✅ Flag any special accommodations needed
- ✅ Generate a seating chart friendly format
- ✅ Track outstanding RSVPs

**Please share your guest information, and I'll compile everything in an organized, easy

Menu Agent: Planning the menu...
Menu: # Dinner Party Menu Plan

I'd be happy to help you create a perfect dinner party menu! However, I notice the guest information section appears to be a template rather than actual guest details.

To create the most suitable menu for your dinner party, could you please provide:

## Information Needed:

1. **Number of guests** attending
2. **Any dietary restrictions or allergies** (vegetarian, vegan, gluten-free, nut allergies, etc.)
3. **Your cooking skill level** (beginner, intermediate, advanced)
4. **Available preparation time** (day before + day of)
5. **Style preference** (casual, formal, specific cuisine)
6. **Season/occasion** (helps with ingredient selection)
7. **Budget per person** (if applicable)

---

## In the Meantime: Sample Versatile Menu

Here's a flexible menu that accommodates most dietary needs and can be easily adjusted:

### **Appetizer**
**Whipped Feta Dip with Crudités & Crackers**
- Vegetarian-friendly
- Can serve gluten-free crackers alongside
- Prep ahead option

### **Salad**
**Arugula & Roasted Beet Salad**
- Mixed greens, roasted beets, candied pecans, goat cheese, citrus vinaigrette
- Easily made vegan (omit cheese) or nut-free

### **Main Course**
**Herb-Roasted Chicken with Lemon**
- Plus: Grilled Portobello Mushrooms (vegetarian option)
- Prep time: 30 min active, 1 hour cooking

### **Sides**
- Garlic roasted potatoes (vegan, GF)
- Roasted seasonal vegetables (vegan, GF)

### **Dessert**
**Individual Chocolate Lava Cakes**
- Can make GF version
- Prep mostly ahead

---

**Please share your specific requirements, and I'll create a customized menu perfectly tailored to your guests!**

Shopping Agent: Creating shopping list...
Shopping List: # Shopping List for Sample Dinner Party Menu

## GUEST COUNT NEEDED
**⚠️ Please specify number of guests for accurate quantities**
*List below assumes 6-8 guests*

---

## 🥬 PRODUCE SECTION

### Fresh Vegetables
- [ ] Arugula/mixed greens - 8 oz
- [ ] Cherry tomatoes - 1 pint
- [ ] Carrots - 1 lb
- [ ] Celery - 1 bunch
- [ ] Bell peppers (assorted) - 3-4
- [ ] Cucumbers - 2 medium
- [ ] Beets - 4-5 medium (or 2 cans, 15 oz each)
- [ ] Portobello mushrooms - 4 large caps
- [ ] Potatoes (Yukon gold or red) - 3 lbs
- [ ] Seasonal vegetables for roasting - 2-3 lbs (zucchini, Brussels sprouts, or carrots)
- [ ] Garlic - 2 heads
- [ ] Fresh herbs: rosemary, thyme, parsley - 1 bunch each

### Fresh Fruit
- [ ] Lemons - 4-5
- [ ] Orange - 1 (for vinaigrette)

---

## 🍗 MEAT & SEAFOOD
- [ ] Whole chicken or chicken pieces - 4-5 lbs (bone-in, skin-on thighs and breasts)

---

## 🧀 DAIRY SECTION
- [ ] Feta cheese - 8 oz block
- [ ] Goat cheese (chèvre) - 4 oz
- [ ] Butter (unsalted) - 1 lb
- [ ] Heavy cream - 1 cup
- [ ] Greek yogurt - 1 cup (for dip)
- [ ] Eggs - 1 dozen

---

## 🍞 BAKERY
- [ ] Crackers (variety pack) - 2 boxes
- [ ] Gluten-free crackers - 1 box
- [ ] Baguette or artisan bread - 1 loaf (optional)

---

## 🥫 PANTRY & CANNED GOODS
- [ ] Olive oil - 1 bottle (if running low)
- [ ] Balsamic vinegar
- [ ] Honey
- [ ] Semi-sweet or dark chocolate - 12 oz (high quality)
- [ ] Pecans - 1 cup (candied or raw)
- [ ] All-purpose flour - check pantry
- [ ] Sugar (granulated & powdered)
- [ ] Vanilla extract

---

## 🧂 SPICES & SEASONINGS
*Check pantry first*
- [ ] Kosher salt
- [ ] Black pepper
- [ ] Dried oregano
- [ ] Paprika
- [ ] Red pepper flakes

---

## 🍷 BEVERAGES (Optional)
- [ ] White wine for cooking - 1 bottle
- [ ] Wine for serving (according to preference)
- [ ] Sparkling water
- [ ] Coffee/tea

---

## 📦 OTHER
- [ ] Toothpicks or small appetizer picks
- [ ] Fresh flowers for table (optional)
- [ ] Candles (optional)

---

## 💰 ESTIMATED COSTS
- **Budget range**: $80-120 for 6-8 guests
- **Per person**: $10-15

---

## ⏰ SHOPPING TIPS

**Buy 2-3 days before:**
- All produce except herbs
- Dairy products
- Meat (or buy 1 week ahead and freeze)

**Buy day before:**
- Fresh herbs
- Bread/crackers
- Flowers

**Already have?** (Check pantry)
- Olive oil, spices, flour, sugar, vanilla

---

## 🔄 SUBSTITUTION OPTIONS

**For dietary restrictions:**
- Vegan: Skip cheese, use cashew cream
- Gluten-free: GF crackers only, GF flour for cakes
- Nut-free: Omit pecans, use pumpkin seeds

---

**📝 Once you provide your guest count and dietary needs, I

Coordinator: Finalizing your dinner party plan...
Final Plan: ```json
{
  "task_breakdown": [
    {
      "agent": "guest_management",
      "tasks": [
        {
          "task_id": "GM-1",
          "description": "Finalize guest count - currently planned for 6-8 guests but needs confirmation",
          "priority": "HIGH",
          "status": "PENDING_INFO"
        },
        {
          "task_id": "GM-2",
          "description": "Collect actual guest names and contact information (template provided but empty)",
          "priority": "HIGH",
          "status": "PENDING_INFO"
        },
        {
          "task_id": "GM-3",
          "description": "Track RSVP responses and confirm final attendance",
          "priority": "HIGH",
          "status": "NOT_STARTED"
        },
        {
          "task_id": "GM-4",
          "description": "Gather specific dietary restrictions and allergies from confirmed guests",
          "priority": "HIGH",
          "status": "PENDING_INFO",
          "notes": "Menu includes options for vegetarian, vegan, gluten-free, and nut-free but need to confirm actual requirements"
        },
        {
          "task_id": "GM-5",
          "description": "Identify special needs (high chairs, texture modifications, children's meals)",
          "priority": "MEDIUM",
          "status": "NOT_STARTED"
        }
      ]
    },
    {
      "agent": "menu_planning",
      "tasks": [
        {
          "task_id": "MP-1",
          "description": "Finalize menu based on actual guest count and confirmed dietary restrictions",
          "priority": "HIGH",
          "status": "DRAFT_READY",
          "current_menu": {
            "appetizer": "Whipped Feta Dip with Crudités & Crackers",
            "salad": "Arugula & Roasted Beet Salad with candied pecans, goat cheese, citrus vinaigrette",
            "main": "Herb-Roasted Chicken with Lemon + Grilled Portobello Mushrooms (vegetarian)",
            "sides": ["Garlic roasted potatoes", "Roasted seasonal vegetables"],
            "dessert": "Individual Chocolate Lava Cakes"
          }
        },
        {
          "task_id": "MP-2",
          "description": "Adjust recipes for confirmed guest count",
          "priority": "HIGH",
          "status": "AWAITING_COUNT",
          "dependencies": ["GM-1"]
        },
        {
          "task_id": "MP-3",
          "description": "Create detailed recipes with timing and instructions",
          "priority": "MEDIUM",
          "status": "NOT_STARTED"
        },
        {
          "task_id": "MP-4",
          "description": "Develop prep timeline (what to make 2-3 days before, day before, day of)",
          "priority": "MEDIUM",
          "status": "NOT_STARTED"
        }
      ]
    },
    {
      "agent": "shopping",
      "tasks": [
        {
          "task_id": "SH-1",
          "description": "Adjust shopping list quantities based on final guest count",
          "priority": "HIGH",
          "status": "DRAFT_READY",
          "dependencies": ["GM-1"],
          "current_estimate": "6-8 guests, $80-120 budget ($10-15 per person)"
        },
        {
          "task_id": "SH-2",
          "description": "Remove/adjust items based on confirmed dietary restrictions",
          "priority": "HIGH",
          "status": "AWAITING_RESTRICTIONS",
          "dependencies": ["GM-4"]
        },
        {
          "task_id": "SH-3",
          "description": "Schedule shopping trips: 2-3 days before (produce, dairy, meat), day before (herbs, bread, flowers)",
          "priority": "MEDIUM",
          "status": "NOT_STARTED"
        },
        {
          "task_i

This example demonstrates several key concepts:

Specialization: Each agent has a specific role and expertise. The guest agent knows about dietary restrictions, the menu agent understands recipes and cooking, the shopping agent organizes grocery lists.

Sequential Dependencies: The menu agent needs information from the guest agent (dietary restrictions) before it can plan effectively. The shopping agent needs the menu before it can create a list. This is a natural workflow where each step builds on the previous one.

Coordination: The coordinator agent orchestrates the entire process, breaking down the complex request into manageable tasks and ensuring information flows between specialists.

Information Sharing: Agents pass relevant information to each other. The guest agent's output becomes input for the menu agent, whose output feeds the shopping agent.

When to Use Multiple Agents

Multi-agent systems are powerful, but they're not always the right choice. Here's how to decide:

Use multiple agents when:

  • Tasks have distinct, separable concerns (research vs. writing vs. editing)
  • Different parts need different tools or knowledge bases
  • You want parallel processing for speed
  • You need checks and balances (one agent generates, another reviews)
  • You're building a system that will grow and need new capabilities over time

Stick with a single agent when:

  • The task is straightforward and doesn't benefit from specialization
  • Coordination overhead would outweigh the benefits
  • You need the simplest possible solution
  • The task requires maintaining context that would be hard to share between agents

Think of it like deciding whether to work alone or form a team. For writing a quick email, you work alone. For producing a documentary, you need a team with different skills.

Looking Ahead

You now understand the fundamental concept of agents working together: multiple specialized agents can collaborate through various patterns (sequential, parallel, iterative, consensus) to solve problems more effectively than a single agent.

In the next chapter, we'll dive deeper into how agents communicate with each other. You'll learn about message formats, protocols, and techniques for ensuring agents understand each other correctly. Then we'll explore the benefits and challenges of multi-agent systems in more detail, including how to handle coordination failures and optimize team performance.

The key takeaway is this: just as human teams accomplish more than individuals working alone, AI agent teams can tackle more complex problems by dividing work according to each agent's strengths. The art is in designing the right team structure and communication patterns for your specific needs.

Glossary

Agent Card: A standardized description of an agent's capabilities, inputs, outputs, and communication methods, similar to a business card for AI agents. Used in protocols like A2A to enable agent discovery and interoperability.

Agent-to-Agent (A2A) Protocol: An open standard developed by Google that enables AI agents from different platforms and frameworks to discover each other, understand capabilities, and collaborate through standardized communication.

Consensus Building: A cooperation pattern where multiple agents independently solve the same problem and then compare results to reach agreement, improving reliability and reducing errors.

Coordinator Agent: An agent responsible for orchestrating multi-agent workflows by breaking down complex requests, delegating tasks to specialist agents, and combining results.

Iterative Refinement: A cooperation pattern where agents work in cycles, with one agent generating output and another reviewing and providing feedback, repeating until quality standards are met.

Model Context Protocol (MCP): A framework developed by Anthropic for connecting agents with tools and data sources, complementary to agent-to-agent communication protocols.

Multi-Agent System: A system where multiple AI agents work together, each with specialized capabilities, to accomplish tasks that would be difficult or impossible for a single agent.

Parallel Execution: A cooperation pattern where multiple agents work simultaneously on independent tasks, then combine their results, enabling faster completion of complex requests.

Sequential Handoff: A cooperation pattern where agents work in sequence, with each agent completing its specialized task before passing results to the next agent in the workflow.

Specialization: The practice of designing agents with focused expertise in specific domains or tasks, rather than trying to make one agent handle everything.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about multi-agent systems and how AI agents work together.

Loading component...

Reference

BIBTEXAcademic
@misc{agentsworkingtogethermultiagentsystemscollaborationpatternsa2aprotocol, author = {Michael Brenndoerfer}, title = {Agents Working Together: Multi-Agent Systems, Collaboration Patterns & A2A Protocol}, year = {2025}, url = {https://mbrenndoerfer.com/writing/agents-working-together-multi-agent-systems-collaboration}, organization = {mbrenndoerfer.com}, note = {Accessed: 2025-12-25} }
APAAcademic
Michael Brenndoerfer (2025). Agents Working Together: Multi-Agent Systems, Collaboration Patterns & A2A Protocol. Retrieved from https://mbrenndoerfer.com/writing/agents-working-together-multi-agent-systems-collaboration
MLAAcademic
Michael Brenndoerfer. "Agents Working Together: Multi-Agent Systems, Collaboration Patterns & A2A Protocol." 2025. Web. 12/25/2025. <https://mbrenndoerfer.com/writing/agents-working-together-multi-agent-systems-collaboration>.
CHICAGOAcademic
Michael Brenndoerfer. "Agents Working Together: Multi-Agent Systems, Collaboration Patterns & A2A Protocol." Accessed 12/25/2025. https://mbrenndoerfer.com/writing/agents-working-together-multi-agent-systems-collaboration.
HARVARDAcademic
Michael Brenndoerfer (2025) 'Agents Working Together: Multi-Agent Systems, Collaboration Patterns & A2A Protocol'. Available at: https://mbrenndoerfer.com/writing/agents-working-together-multi-agent-systems-collaboration (Accessed: 12/25/2025).
SimpleBasic
Michael Brenndoerfer (2025). Agents Working Together: Multi-Agent Systems, Collaboration Patterns & A2A Protocol. https://mbrenndoerfer.com/writing/agents-working-together-multi-agent-systems-collaboration