Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

Supervisors, Handoffs and Agents as Tools

Compare the three main multi-agent interaction topologies (centralized supervisory routing, peer-to-peer handoffs and sub-agents wrapped as tools), and run code for supervisor routing and guarded handoffs.

Contentsand lesson path

On this page

  1. Topologies of Multi-Agent Collaboration
  2. Deep Dive: The Three Multi-Agent Topologies
  3. Verify Your Understanding
  4. Apply it
  5. Review prompt

Lessons of Multi-Agent Orchestration

  1. When More Agents Help and When They Hurt Concept · 15 min
  2. Supervisors, Handoffs and Agents as Tools Worked example · 25 min
  3. Lab: Parallel Sub-Agents with Isolated Context Lab · 25 min
  4. How Multi-Agent Systems Fail Concept · 15 min
  5. Single Versus Multi-Agent on One Task Set Lab · 25 min
  6. Check: Choose a Topology Knowledge check · 8 questions

What you will learn

  • Implement supervisor-worker and handoff topologies and explain how control and context pass between agents in each.

Prerequisites: Agent Loops & ReAct

01. Topologies of Multi-Agent Collaboration

When you build a system with several agents, the first choice is how they pass work and control to each other. If you simply let three LLM agents send messages to each other with no structure, you invite conversational ping-pong, runaway token use and runs that stall without finishing.

Three communication topologies come up again and again: Centralized Supervisory Orchestration, Peer-to-Peer Handoffs, and Agents as Tools (a sub-agent wrapped behind a tool). For example, the OpenAI Agents SDK documents handoffs and agents as tools as its two most common orchestration patterns, and Anthropic describes its research system as a lead agent that coordinates parallel workers. Each topology offers different trade-offs between centralized control, autonomous flexibility, and context isolation.

You could instead let many agents message each other freely, the way a human team chats. That is easy to start, but the route a request takes is then decided anew by the models on every run, so it is hard to trace which agent made a decision, to attribute token costs or to show an auditor why a run ended. The three patterns above keep handoffs, delegation depth and stopping conditions in code, and they are the patterns that the OpenAI and Anthropic sources above describe.

This worked example shows how control passes in each topology. The Python example runs the two patterns that need control logic of their own: the supervisor's routing function and guarded peer handoffs. Agents as tools needs no new control logic, because the sub-agent loop sits behind an ordinary tool function; the text describes it.

02. Deep Dive: The Three Multi-Agent Topologies

Here is how control flows through each pattern.

Supervisor (hub and spoke). In a supervisor topology, a central orchestrator agent is the single point of contact for the user. Worker agents never talk to one another; they talk only to the supervisor. When a complex request arrives, the supervisor breaks it into sub-tasks, sends each one to the right worker, collects the workers' structured responses and writes the final answer.

The main advantage of the supervisor pattern is control and observability. Because all control passes through the hub, you have one place to enforce global policies, check termination conditions and set limits on every worker. The disadvantage is that the supervisor becomes a throughput and token bottleneck, as every worker result must be read and re-processed by the supervisor model. In long multi-step operations, re-reading and re-summarising intermediate artifacts adds tokens on every round trip; measure how much on your own traces before choosing the hub for cost-sensitive flows.

Peer-to-peer handoffs. In a handoff topology, used by the OpenAI Agents SDK (the successor to OpenAI's experimental Swarm library), an agent can pass the whole conversation and the user interaction to another specialised agent. For example, a FrontDesk agent starts the triage; when the user asks to book a flight, FrontDesk calls a transfer_to_flight_agent function.

From then on FrontDesk is out of the loop. The FlightAgent receives the conversation history (or a filtered summary of it) and now talks to the user directly. If the user then asks to reserve a hotel room, the FlightAgent calls transfer_to_hotel_agent. What travels with a handoff is either the full history or a pruned version in which irrelevant earlier turns are dropped.

Handoffs remove the supervisor's re-reading step, because no central agent summarises every worker's output. However, without cycle detection and a maximum number of handoffs, peer agents can hand a user back and forth without end, or lose track of the original goal.

Agents as tools. In this pattern, a specialised sub-agent is wrapped behind an ordinary tool signature, such as a callable Python function. To the calling agent, the sub-agent looks like any other tool, like a database query or a web search. Behind the call, the tool runs a whole agent loop of its own, with several model turns and tool calls, before it returns a final string or JSON result.

This pattern gives the strongest context isolation: the parent agent sees only the final output of the sub-agent, not its scratchpad, intermediate tool errors or verbose logs. If a sub-agent runs ten SQL queries and retries three syntax errors, none of those intermediate tokens enters the parent's context, unless the wrapper chooses to return them.

Python · topologies.py
from typing import List, Optional, TypedDict

MAX_HOPS = 6


class OrchestrationState(TypedDict):
    user_goal: str
    current_agent: str
    handoff_count: int
    visited: List[str]  # every agent that has held the conversation, in order
    worker_artifacts: dict
    final_response: Optional[str]


def supervisor_route(state: OrchestrationState) -> str:
    """Supervisor hub: a routing function for a conditional edge.
    It returns the name of the next node; it does not write to state."""
    artifacts = state["worker_artifacts"]
    if "data" not in artifacts:
        return "data_collector_worker"
    if "audit" not in artifacts:
        return "compliance_auditor_worker"
    return "synthesizer"


def handoff(state: OrchestrationState, target: str) -> OrchestrationState:
    """Every peer handoff goes through here: it counts hops, records the path,
    and escalates on the hop cap or when a handoff edge repeats (A->B twice)."""
    visited = state["visited"]
    edges = set(zip(visited, visited[1:]))
    if state["handoff_count"] >= MAX_HOPS or (visited[-1], target) in edges:
        target = "escalation_support_node"
    return {**state, "current_agent": target, "visited": visited + [target],
            "handoff_count": state["handoff_count"] + 1}


if __name__ == "__main__":
    state = OrchestrationState(user_goal="refund and address change",
                               current_agent="billing", handoff_count=0,
                               visited=["billing"], worker_artifacts={},
                               final_response=None)
    for target in ["account", "billing", "account", "billing"]:
        state = handoff(state, target)
        print(f"hop {state['handoff_count']}: -> {state['current_agent']}")
        if state["current_agent"] == "escalation_support_node":
            break
    print("path:", " > ".join(state["visited"]))
    print("supervisor next:", supervisor_route(state))
Terminal (Python 3.12 or later)
python3 topologies.py
Expected output
hop 1: -> account
hop 2: -> billing
hop 3: -> escalation_support_node
path: billing > account > billing > escalation_support_node
supervisor next: data_collector_worker

supervisor_route returns a node name, which is what a conditional edge in a graph framework expects; it does not invent a state key that the schema lacks. handoff is the only way control moves between peers, so it is the one place that counts hops and keeps the visited path. Billing to account and back is allowed, because a user may really need both, but repeating the billing-to-account handoff is a ping-pong loop, and it is escalated on the third hop, long before the cap of six.

Which topology fits depends on how the sub-tasks relate to each other and on what you must be able to audit:

  • Choose a supervisor when one coordinator must combine findings from several independent domains into one report. It gives you one place to audit, enforce policy and track progress, at the cost of more tokens and the latency of the hub.

  • Choose peer-to-peer handoffs for conversational support or onboarding flows, where the user moves through phases one after another (Triage -> Authentication -> Resolution -> Survey) and only one specialist is needed at a time. Handoffs usually use fewer tokens and respond faster, provided that hop counters and cycle checks stop ping-pong loops.

  • Choose agents as tools when an existing agent sometimes needs a deep dive, such as investigating a complex SQL schema or doing web research, without filling its own context with hundreds of schema tokens. Of the three patterns, it isolates context most strongly.

03. Verify Your Understanding

Practice check · 3 questions

Multi-Agent Topologies Knowledge Check

Three questions on the handoff guard, routing functions and the cost of a supervisor.

Q1. Billing hands off to Accounts, Accounts hands back to Billing, and Billing hands to Accounts again. What does this lesson's guard do on that third handoff?
Q2. After the escalation, `topologies.py` prints `supervisor next: data_collector_worker`. Why does `supervisor_route` pick that node?
Q3. Why can a supervisor topology cost more tokens than peer handoffs for the same task?
Practice only: not graded, not saved, not evidence.

04. Apply it

Choose the topology for the research assistant you are building for this skill:

  1. Write down whether the lead agent must combine the findings of all three sub-questions into one answer. If it must, use a supervisor or agents as tools, not handoffs.
  2. Write the routing function as code that returns a node name, and test it with an empty, a partial and a complete set of findings.
  3. Decide what each sub-agent returns to the lead: a short structured result, not its whole scratchpad.
  4. If you add any peer handoff, route it through one function that counts hops and escalates on a repeated handoff edge.

05. Review prompt

Without looking back, describe how control moves in a supervisor topology, in peer-to-peer handoffs and in agents as tools. For each one, name its main advantage and its main risk. Then explain how the handoff guard in this lesson detects a ping-pong loop before the hop cap, and why a routing function returns a node name instead of writing to state.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check