Claude Code & MCP MasterclassModule 3

3.1Multi-Agent Orchestration — Haiku Workers, Sonnet Managers, Opus Architects

35 min 8 code blocks Practice Lab Quiz (4Q)

Multi-Agent Orchestration

Multi-agent systems coordinate multiple Claude instances to solve complex problems. Agent 1 might research, Agent 2 analyzes, Agent 3 writes. This lesson teaches orchestration patterns used by Pakistani startups to automate 80% of their workflows.

Agent Architecture Patterns

Pattern 1: Pipeline (Sequential)

code
Researcher Agent → Analyzer Agent → Writer Agent → Publisher

Each agent passes output to next agent.

Pattern 2: Hierarchical (Decision Tree)

code
Coordinator Agent
├── Researcher Agent (if research needed)
├── Coder Agent (if coding needed)
└── Design Agent (if UI/UX needed)

Coordinator decides which agents to invoke.

Pattern 3: Peer-to-Peer (Debate)

code
Agent A ←→ Agent B ←→ Agent C
(Agents debate, reach consensus)

Building Multi-Agent System with Claude Code

File: main.py

python
import asyncio
from anthropic import Anthropic

client = Anthropic()

# Agent 1: Researcher
async def research_agent(topic: str):
    response = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=1500,
        system="You are a research expert. Provide detailed research on topics.",
        messages=[{"role": "user", "content": f"Research: {topic}"}]
    )
    return response.content[0].text

# Agent 2: Analyzer
async def analyzer_agent(research: str):
    response = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=1500,
        system="You are an analyst. Extract key insights from research.",
        messages=[{"role": "user", "content": f"Analyze this research: {research}"}]
    )
    return response.content[0].text

# Agent 3: Writer
async def writer_agent(analysis: str):
    response = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=2000,
        system="You are a professional writer. Write compelling articles.",
        messages=[{"role": "user", "content": f"Write article based on analysis: {analysis}"}]
    )
    return response.content[0].text

# Orchestrator
async def orchestrate(topic: str):
    print(f"Researching: {topic}")
    research = await research_agent(topic)

    print("Analyzing...")
    analysis = await analyzer_agent(research)

    print("Writing...")
    article = await writer_agent(analysis)

    return article

# Run
if __name__ == "__main__":
    article = asyncio.run(orchestrate("AI in Pakistan"))
    print(article)

Pakistani Use Case: SEO Content Pipeline

Pakistani SaaS builds content automation system:

code
Topic List (100 keywords)
    ↓
Keyword Agent (pick best keyword, target audience)
    ↓
Outline Agent (create 2,000-word outline)
    ↓
Draft Agent (write full article)
    ↓
Editor Agent (improve grammar, flow, Pakistan context)
    ↓
SEO Agent (optimize for keywords, add links)
    ↓
Publish Agent (schedule to WordPress, social)

6 agents, fully automated. 100 articles in 1 week (vs. 2-3 weeks manually).

Agent Communication: Shared Context

Agents should share context (memory) to avoid redundant work:

python
class AgentContext:
    def __init__(self):
        self.memory = {}

    def set(self, key, value):
        self.memory[key] = value

    def get(self, key):
        return self.memory.get(key)

# Shared context
context = AgentContext()

async def research_agent(topic):
    # Store findings in context
    research = "... findings ..."
    context.set("research_findings", research)
    return research

async def analyzer_agent(topic):
    # Access research from context (no need to pass)
    research = context.get("research_findings")
    analysis = f"Analyzing: {research}"
    context.set("analysis", analysis)
    return analysis

Error Handling & Retries

Agents sometimes fail. Handle gracefully:

python
async def agent_with_retry(agent_func, *args, retries=3):
    for attempt in range(retries):
        try:
            return await agent_func(*args)
        except Exception as e:
            if attempt < retries - 1:
                wait_time = 2 ** attempt  # Exponential backoff
                print(f"Attempt {attempt + 1} failed. Retrying in {wait_time}s...")
                await asyncio.sleep(wait_time)
            else:
                raise

# Usage
result = await agent_with_retry(researcher_agent, "AI in Pakistan")

Monitoring & Logging

Track agent performance:

python
import time
import logging

logging.basicConfig(level=logging.INFO)

async def monitored_agent(agent_name, agent_func, *args):
    start = time.time()
    try:
        result = await agent_func(*args)
        duration = time.time() - start
        logging.info(f"✓ {agent_name}: {duration:.2f}s")
        return result
    except Exception as e:
        logging.error(f"✗ {agent_name}: {e}")
        raise

# Usage
result = await monitored_agent("Researcher", research_agent, "AI Pakistan")

Pakistan Example: Entrepreneurship Podcast AI

Pakistani founder built AI system generating podcast episodes:

Agent 1: Topic Selector — Picks trending topics (AI, startup stories, fintech) Agent 2: Guest Interviewer — Generates interview questions Agent 3: Script Writer — Writes podcast script with guest answers Agent 4: Editor — Adds timestamps, removes filler words Agent 5: Promoter — Generates social media clips and captions Agent 6: Publisher — Uploads to Spotify, Apple Podcasts, YouTube

Pipeline: 30 seconds → 50-minute podcast. One person, 10 podcasts/week.

Revenue: 10,000 listeners × PKR 100/month Patreon = PKR 1,000,000/month.

Practice Lab

Practice Lab

Task 1: Three-Agent Pipeline — Build pipeline: Research → Analyze → Write. Test on 3 topics.

Task 2: Production Multi-Agent — Build your own 5+ agent system for your niche. Document architecture, performance, output quality.

Conclusion

Multi-agent systems are the future of AI-powered businesses. Master orchestration, and you can automate entire workflows (content, coding, analysis, design). Pakistani builders using multi-agent systems are outpacing competitors 5-10x.

Lesson Summary

Includes hands-on practice lab8 runnable code examples4-question knowledge check below

Multi-Agent Orchestration Quiz

4 questions to test your understanding. Score 60% or higher to pass.