Overview
Level 3: Advanced Interactions · Module 16: Agent Frameworks and Multi-Agent Systems · 20 min read · Extended Track
Last updated: November 2026
As language model applications scale from simple question-answering to multi-domain business workflows, a single agent overloaded with 50 distinct tools suffers from two fatal problems:
- Tool Selection Hallucination: Model accuracy in picking the right tool drops precipitously when the tool catalog exceeds 15-20 functions.
- Context Window Contamination: A customer support conversation polluted with low-level SQL queries, database schemas, and billing validation logs degrades the quality of user-facing empathy and formatting.
The OpenAI Agents SDK (and swarm pattern) solves this via the Handoff Paradigm: specialized micro-agents hand off the execution context directly to another agent when domain boundaries are crossed.
1. The Handoff Architecture Pattern
sequenceDiagram
actor User as User in Browser
participant Triage as Triage / Router Agent
participant Billing as Billing Specialist Agent
participant Stripe as Stripe Gateway API
User->>Triage: "I was billed twice for my Pro subscription"
Note over Triage: Inspects query intent.<br>Transfers control to Billing Agent.
Triage-->>Billing: Handoff(user_id, issue_type="refund")
Note over Billing: Billing Agent assumes context.<br>Equipped with refund tools.
Billing->>Stripe: refundCharge(chargeId="ch_98412")
Stripe-->>Billing: Status: Success
Billing->>User: "I have processed a refund of $29 for your duplicate charge."2. Code Walkthrough: Implementing Handoffs with OpenAI Agents SDK
Here is how multi-agent handoffs operate in practice using typed agents and function returns:
from typing import Dict, Any
from pydantic import BaseModel, Field
# 1. Base Agent Abstraction
class Agent:
def __init__(self, name: str, instructions: str, functions: list):
self.name = name
self.instructions = instructions
self.functions = functions
# 2. Domain Tool Functions
def refund_charge(charge_id: str, reason: str = "duplicate") -> str:
"""Executes a financial refund against payment processor."""
print(f"[Stripe API] Refunded charge: {charge_id} (Reason: {reason})")
return f"Refund successful for {charge_id}"
def search_knowledge_base(query: str) -> str:
"""Retrieves technical product documentation."""
return f"Knowledge base results for: {query}"
# 3. Handoff Functions (Transferring execution to target agent)
def transfer_to_billing() -> Agent:
"""Transfer the user immediately to the specialized Billing Support agent."""
print(">>> Transferring control: Triage -> Billing Agent")
return billing_agent
def transfer_to_tech_support() -> Agent:
"""Transfer the user immediately to the Technical Support agent."""
print(">>> Transferring control: Triage -> Tech Support Agent")
return tech_support_agent
# 4. Instantiate Specialized Agents
billing_agent = Agent(
name="Billing Agent",
instructions="You are an empathetic billing specialist. Process refunds and billing disputes accurately.",
functions=[refund_charge]
)
tech_support_agent = Agent(
name="Technical Support Agent",
instructions="You are a senior technical support engineer. Help users debug API keys and SDK integrations.",
functions=[search_knowledge_base]
)
triage_agent = Agent(
name="Triage Router",
instructions="Analyze the user request and immediately hand off to either Billing or Tech Support.",
functions=[transfer_to_billing, transfer_to_tech_support]
)
# 5. Execution Runner Simulation
def run_swarm_turn(current_agent: Agent, user_message: str):
print(f"\n[Active Agent: {current_agent.name}] Received message: '{user_message}'")
# In production, the LLM emits a tool_call matching transfer_to_billing
if "billed" in user_message or "refund" in user_message:
target_agent = transfer_to_billing()
print(f"[Handshake Complete] Context handed over to {target_agent.name}")
# Next turn executes strictly with billing_agent's isolated tools
result = refund_charge(charge_id="ch_2026_x89")
print(f"[{target_agent.name} Output]: {result}")
return target_agent
# Test the Swarm Handoff
active = triage_agent
active = run_swarm_turn(active, "I was billed twice on my invoice")3. Key Design Rules for Swarm Systems
- Prune Intermediate Context on Handoff: Do not forward 100 historical tool execution messages to the new agent. Pass only the summary and current intent frame.
- Maximum Hop Depth Guardrails: Set a hard limit on agent-to-agent transfers (e.g.
max_hops = 3) to prevent infinite ping-pong loops between confused agents. - Stateless vs Stateful Handoffs: In stateless swarms, each handoff simply returns the new active agent to the client session. In stateful swarms, state is synchronized via Redis or Postgres.
4. Interview Angle
Staff Engineer Question: "How does a multi-agent swarm architecture improve security and regulatory compliance compared to a single monolithic agent?"
Principal Answer: Principle of Least Privilege: In a monolithic agent, every prompt injection attempt has access to the complete tool whitelist, including destructive actions like database drops or refunds. In a swarm system, sensitive tools are strictly restricted to isolated sub-agents that can only be reached through explicit verification gates. An untrusted user chatting with the frontend triage agent cannot trick the LLM into calling
refund_charge()because that tool definition does not exist in the triage agent's context schema.