Agents Working Together › Bringing It Together: A Multi-Agent Example
AI Agent HandbookAll chapters Agents Working Together › Bringing It Together: A Multi-Agent ExampleOne section · Sections in this chapter6 / 10 ↓
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:
## 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."
)=== 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_iThis 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.