Practical building · Module 2

Multi-agent systems

In practice, when tasks cross more than a couple of domains, a single agent often degrades quickly.

1h 3 outcomes Practical building

Previously

Building your first agent

Let us build a production-ready single agent step by step.

This module

Multi-agent systems

In practice, when tasks cross more than a couple of domains, a single agent often degrades quickly.

Next

Workflow automation with n8n

n8n (pronounced "n-eight-n") is a workflow automation platform that lets you connect different apps and services.

Progress

Mark this module complete when you can explain it without rereading every paragraph.

Why this matters

A central supervisor routes requests to specialised sub-agents.

What you will be able to do

  • 1 Explain why multi-agent designs can outperform one general agent.
  • 2 Implement a supervisor pattern and a swarm pattern at a basic level.
  • 3 Design a simple communication protocol and boundaries between roles.

Before you begin

  • Core concepts completed or equivalent understanding
  • Basic confidence with workflow and integration terms

Common ways people get this wrong

  • Deadlock and loops. Agents can bounce tasks back and forth. Put time and step limits in the supervisor.
  • Shared state corruption. If workers write inconsistent state, the supervisor makes decisions on nonsense.

Main idea at a glance

Single vs Multi-Agent Performance

Stage 1

Single Agent

A single AI agent tries to handle all domains. It works well with one or two domains but degrades quickly as complexity grows. At five domains, success drops to just 20%.

I think single agents are fine for narrow, well-defined tasks. Once you cross two domains, quality suffers noticeably.

3.2.1 Why Multiple Agents?

In practice, when tasks cross more than a couple of domains, a single agent often degrades quickly. A multi-agent setup can hold quality steady because each specialist stays in a narrower problem space.

3.2.2 The Supervisor Pattern

A central supervisor routes requests to specialised sub-agents.

Supervisor Architecture

Stage 1

User Request

The user submits a task or question to the system.

I think the initial request should be clear, but the supervisor handles ambiguity.
"""
Multi-Agent Supervisor Pattern
==============================
A supervisor agent coordinates specialised sub-agents.
"""

from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from enum import Enum


class AgentRole(Enum):
    """Roles for specialised agents."""
    RESEARCHER = "researcher"
    WRITER = "writer"
    CODER = "coder"
    ANALYST = "analyst"


@dataclass
class AgentMessage:
    """Message passed between agents."""
    sender: str
    recipient: str
    content: str
    message_type: str  # "task", "result", "query", "status"
    metadata: Dict[str, Any] = None


class SpecialisedAgent:
    """A specialised agent with a specific focus area."""
    
    def __init__(
        self,
        name: str,
        role: AgentRole,
        system_prompt: str,
        tools: List = None
    ):
        self.name = name
        self.role = role
        self.system_prompt = system_prompt
        self.tools = tools or []
    
    def process(self, message: AgentMessage) -> AgentMessage:
        """Process an incoming message and return a response."""
        prompt = f"""You are {self.name}, a specialist {self.role.value}.

{self.system_prompt}

Task from supervisor:
{message.content}

Provide your expert response:
"""
        
        response = self._call_llm(prompt)
        
        return AgentMessage(
            sender=self.name,
            recipient=message.sender,
            content=response,
            message_type="result"
        )
    
    def _call_llm(self, prompt: str) -> str:
        """Call the underlying LLM."""
        import requests
        response = requests.post(
            "http://localhost:11434/api/generate",
            json={"model": "llama3.2:3b", "prompt": prompt, "stream": False}
        )
        return response.json().get("response", "")


class SupervisorAgent:
    """Supervisor that coordinates multiple specialised agents."""
    
    ROUTING_PROMPT = """You are a supervisor coordinating a team of specialists.

Available specialists:
{agents}

User request:
{query}

Decide which specialist should handle this. Respond with JSON:
{{"agent": "agent_name", "task": "specific task for them"}}
"""
    
    def __init__(self, agents: List[SpecialisedAgent]):
        self.agents = {agent.name: agent for agent in agents}
    
    def run(self, query: str) -> str:
        """Process a user query through the multi-agent system."""
        # Route to appropriate agent
        routing = self._route_request(query)
        
        agent_name = routing.get("agent")
        task = routing.get("task", query)
        
        if agent_name in self.agents:
            agent = self.agents[agent_name]
            message = AgentMessage(
                sender="supervisor",
                recipient=agent_name,
                content=task,
                message_type="task"
            )
            response = agent.process(message)
            return response.content
        
        return "No suitable agent found for this request."
    
    def _route_request(self, query: str) -> Dict:
        """Determine which agent should handle the request."""
        agents_desc = "\n".join(
            f"- {name}: {agent.role.value}"
            for name, agent in self.agents.items()
        )
        
        prompt = self.ROUTING_PROMPT.format(agents=agents_desc, query=query)
        
        import requests
        response = requests.post(
            "http://localhost:11434/api/generate",
            json={"model": "llama3.2:3b", "prompt": prompt, "stream": False}
        )
        
        import json
        try:
            return json.loads(response.json().get("response", "{}"))
        except:
            return {"agent": list(self.agents.keys())[0], "task": query}

3.2.3 The Swarm Pattern

In a swarm, agents hand off directly to each other without going through a supervisor.

Swarm Architecture

Stage 1

User

The user can interact with any agent in the swarm. The swarm decides who should respond or who needs to help.

I think users shouldn't need to know the swarm structure, but that adds complexity.

3.2.4 Framework comparison

Choosing a framework matters, but rankings age badly. Compare frameworks against the operating model you need rather than a momentary popularity chart.

🎯 Interactive. Agent workflow designer

Before diving into visual tools like n8n, use this interactive designer to understand how agent workflows are structured. Explore template workflows or design your own multi-step agent processes.

Interactive lab

Agent Workflow Designer

This module includes an interactive practice component. Open the deeper tool or workspace step when you want to test the idea rather than only read it.

Mental model

Coordination is the hard part

Multi agent systems work when each role is narrow and the coordinator can stop conflict.

  1. 1

    Supervisor

  2. 2

    Worker A

  3. 3

    Worker B

  4. 4

    Shared state

  5. 5

    Result

Assumptions to keep in mind

  • Roles are bounded. If every agent can do everything, you build a noisy committee.
  • Conflicts are resolved. You need a rule for disagreement. Voting, ranking, or escalation.

Failure modes to notice

  • Deadlock and loops. Agents can bounce tasks back and forth. Put time and step limits in the supervisor.
  • Shared state corruption. If workers write inconsistent state, the supervisor makes decisions on nonsense.

Check yourself

Quick check. Multi-agent systems

0 of 4 opened

Why can multiple specialised agents outperform one general agent

Each specialist stays in a narrower domain, which often improves quality and reduces drift.

What is the supervisor pattern in one sentence

A coordinator agent routes work to specialist agents and decides what to do with their outputs.

What is a swarm pattern in one sentence

Agents collaborate directly and hand off tasks to each other without a central supervisor.

Name one risk unique to multi-agent systems

Coordination failure. Agents can contradict each other, loop, or amplify a mistake if boundaries are unclear.

Artefact and reflection

Artefact

A role map you can reuse in future builds.

Reflection

Where in your work would explain why multi-agent designs can outperform one general agent. change a decision, and what evidence would make you trust that change?

Optional practice

Drag and connect agent components (LLM, tools, memory, guardrails) to design a complete agent system.

Also in this module

Simulate agent workflows

Run your agent architecture through test scenarios and watch how data flows between components.