ptrnsai

Swarm Intelligence

Advanced👥 Multi-Agent PatternsOpenAI / Academic Research

Intent

Many lightweight agents coordinate through simple local rules and handoffs, without centralized control.

Problem

Centralized supervisor architectures create bottlenecks and single points of failure. For some workflows, you need a more organic, flexible coordination model where agents can dynamically hand off work to whoever is best suited.

Solution

Create a swarm of agents, each with a defined specialty and a set of other agents it can hand off to. There's no central coordinator — instead, agents evaluate whether they're the right agent for the current task and transfer control when they're not. The 'intelligence' emerges from the collective behavior. This is inspired by biological swarms (ants, bees) where complex behavior arises from simple individual rules.

Diagram

User → [Triage Agent]
            ├─ handoff → [Sales Agent] ──→ handoff → [Billing Agent]
            ├─ handoff → [Support Agent] ─→ handoff → [Escalation Agent]
            └─ handoff → [FAQ Agent]

       Each agent decides: handle it or hand off to someone better suited

When to Use

  • Customer service with multiple specialties and fluid conversations
  • When conversations naturally flow between topics
  • Systems that need to scale without a coordination bottleneck
  • When agent roles map to natural handoff boundaries

When NOT to Use

  • Tasks requiring a single coherent strategy
  • When centralized control is needed for compliance
  • Simple workflows with predictable routing

Pros & Cons

Pros

  • No single point of failure or bottleneck
  • Scales well — just add more agents
  • Natural, flexible conversation flow
  • Each agent is simple and focused

Cons

  • Harder to debug — no central authority to inspect
  • Can loop (A hands to B, B hands back to A)
  • Global coherence is harder to maintain
  • Testing requires simulating multi-agent interactions

Implementation Steps

  1. 1Define agent roles and their specialties
  2. 2For each agent, define its handoff targets (which agents can it transfer to?)
  3. 3Implement handoff logic: when should an agent transfer control?
  4. 4Add loop detection to prevent circular handoffs
  5. 5Build conversation state that persists across handoffs
  6. 6Monitor handoff patterns to identify common flows and optimize

Real-World Example

Customer Service Swarm

User contacts support. Triage Agent identifies a billing issue and hands off to Billing Agent. During the conversation, the user mentions a bug — Billing Agent hands off to Technical Support Agent. Tech Support resolves the bug and the conversation ends naturally.

PythonAgent Handoff Swarm
from openai import OpenAI

client = OpenAI()

AGENTS = {
    "triage": {"system": "Route the user to the right department.", "handoffs": ["sales", "support", "billing"]},
    "sales": {"system": "Handle sales and product inquiries.", "handoffs": ["billing"]},
    "support": {"system": "Resolve technical support issues.", "handoffs": ["billing"]},
    "billing": {"system": "Handle billing and payment questions.", "handoffs": []},
}

def run_swarm(user_message: str, max_hops: int = 5) -> str:
    current = "triage"
    messages = [{"role": "user", "content": user_message}]

    for _ in range(max_hops):
        agent = AGENTS[current]
        hint = f"\nTo handoff, start with HANDOFF:<name>. Options: {agent['handoffs']}" if agent["handoffs"] else ""

        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "system", "content": agent["system"] + hint}] + messages,
        )
        reply = response.choices[0].message.content

        if reply.startswith("HANDOFF:"):
            current = reply.split(":")[1].strip().split()[0]
            continue

        return reply

    return "Max handoffs reached"

References