Agents Working Together › Patterns of Cooperation
AI Agent HandbookAll chapters Agents Working Together › Patterns of CooperationOne section · Sections in this chapter4 / 10 ↓
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) → ResultOur 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:
- Planning Agent: Breaks down "plan my weekend" into specific tasks
- Booking Agent: Handles reservations and purchases
- 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 OutputThis 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:
## 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?")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.