Introduction & Overview

Welcome to another lesson about agentic patterns! In the previous lesson, you mastered orchestrating agents as tools, where a central planner agent could dynamically delegate tasks to specialist agents and receive their results back. Today, we're exploring a fundamentally different approach called the handoff pattern, where agents can completely transfer control to other specialized agents rather than just calling them as tools.

In this lesson, you'll extend the Agent class constructor to support handoff targets, create a handoff tool schema that enables control transfers, and implement the core handoff logic that passes conversation context between agents. We'll build a practical example with a general assistant that can hand off mathematical problems to a specialized calculator assistant, demonstrating how agents make intelligent decisions about when to transfer control versus handling tasks themselves.

Understanding the Handoff Pattern

The handoff pattern represents a different philosophy of agent collaboration compared to the tool delegation approach you learned previously. When an agent uses another agent as a tool, it's essentially asking for help while maintaining responsibility for the final response. When an agent performs a handoff, it's saying, "this other agent is better equipped to handle this entire conversation from here on."

Consider the difference in conversation flow. In tool delegation, the user interacts with the orchestrator throughout: the user asks a question, the orchestrator calls a specialist tool, receives the result, and then provides its own response incorporating that information. The user never directly interacts with the specialist agent.

In the handoff pattern, the conversation flow changes completely. The user starts by talking to one agent, but that agent recognizes that another agent should take over. The first agent transfers not just the task, but the entire conversation context to the specialist. From that point forward, the specialist agent is directly responding to the user, and the original agent is no longer involved. This pattern is particularly powerful when you have agents with very different capabilities or when the nature of a request clearly falls into one agent's domain of expertise.

Extending the Agent Class Constructor

To implement handoffs, we need to extend our existing Agent class with the ability to transfer control to other agents. This requires adding a new parameter to track available handoff targets and creating a special handoff tool that agents can use to transfer control.

class Agent:
    BASE_SYSTEM_PROMPT = (
        "You are an autonomous agent that can take multiple tool-calling steps when helpful. "
        "The user only sees your response when you stop using tools, not your tool usage or reasoning steps. "
        "When you provide your answer without calling tools, make it complete and standalone.\n"
        "Additional instructions:\n"
    )

    def __init__(
        self,
        name,
        system_prompt="You are a helpful assistant.",
        model="gpt-5",
        tools=None,
        tool_schemas=None,
        handoffs=None,  # New parameter for handoff targets
        max_turns=10,
        reasoning_effort="low"
    ):
        self.client = OpenAI()
        self.name = name
        self.model = model
        self.system_prompt = self.BASE_SYSTEM_PROMPT + system_prompt
        self.max_turns = max_turns
        self.reasoning_effort = reasoning_effort

        # Avoid shared mutable defaults and protect against external mutation
        self.tools = {} if tools is None else dict(tools)
        self.tool_schemas = [] if tool_schemas is None else list(tool_schemas)
        self.handoffs = [] if handoffs is None else list(handoffs)  # List of agents for handoffs

The handoffs parameter accepts a list of other Agent instances to which this agent can transfer control. We store this as a list rather than a dictionary because agents are identified by their name attribute, and we want to maintain the flexibility to search through available agents dynamically.

The reasoning_effort parameter controls how much computational effort the model invests in reasoning through problems. Setting it to "low" provides faster responses for straightforward tasks, while higher values like "medium" or "high" enable deeper analysis for complex problems. For handoff decisions and basic task routing, low reasoning effort is typically sufficient.

With the constructor updated, we need to create the handoff tool schema that will enable agents to request control transfers.

Creating the Handoff Tool Schema

Next, we need to create a tool schema that allows the agent to request handoffs. This schema will be automatically added to the agent's available tools when handoff targets are provided.

# Define handoff tool schema
self.handoff_schema = {
    "type": "function",
    "name": "handoff",
    "description": "Transfer control to another specialized agent. Use this when the user's request is better handled by a different agent.",
    "parameters": {
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": f"Name of the agent to handoff to. Available agents: {[agent.name for agent in self.handoffs]}"
            },
            "reason": {
                "type": "string", 
                "description": "Brief explanation of why this handoff is needed"
            }
        },
        "required": ["name", "reason"],
        "additionalProperties": False
    }
}

The handoff schema follows OpenAI's function calling format with a type of "function", a descriptive name, and a parameters object defining the expected inputs. The schema includes two required parameters: the name of the target agent and a reason for the handoff. The reason parameter serves both as documentation for debugging and as a way to help the agent think through whether a handoff is truly necessary.

Notice how we dynamically include the list of available agents in the description, helping the model understand which handoff options are available. The additionalProperties: False constraint ensures that only the specified parameters can be passed, preventing unexpected inputs. Now we need to make this handoff schema available to the agent alongside its other tools.

Building Tool Schemas in the Run Method

To make handoffs work seamlessly, we need to build a complete list of available tools that includes both regular tool schemas and the handoff schema when appropriate. Unlike some agent frameworks that use a separate method for building request arguments, our implementation constructs the tool list directly within the run method before each API call.

def run(self, input_messages):
    # Create a copy of the input messages to avoid modifying the original
    messages = input_messages.copy()

    # Loop until the model returns a final answer or the max turns is reached
    turn = 0
    while turn < self.max_turns:
        turn += 1

        # Build the complete tool schemas list
        all_tools = []
        
        # Add regular tool schemas if they exist
        if self.tool_schemas:
            all_tools.extend(self.tool_schemas)
        
        # Add handoff schema if handoffs are available
        if self.handoffs:
            all_tools.append(self.handoff_schema)
        
        response = self.client.responses.create(
            model=self.model,
            instructions=self.system_prompt,
            input=messages,
            tools=all_tools,
            reasoning={"effort": self.reasoning_effort},
            store=False
        )

This approach builds the all_tools list fresh for each turn by first extending it with any regular tool schemas, then appending the handoff schema if handoff targets are configured. The list is passed directly to responses.create() as the tools parameter. This inline construction ensures that the handoff tool is automatically available to any agent that has handoff targets configured, without requiring separate schema management methods.

With the handoff tool now available to agents, we need to implement the logic that actually performs the control transfer when this tool is called.

Implementing the Handoff Logic

The core of the handoff pattern lies in the call_handoff method, which handles the actual transfer of control from one agent to another. This method performs several critical operations:

def call_handoff(self, function_call, messages):
    # Extract the agent name from the handoff tool input
    args = json.loads(function_call.arguments or "{}")
    agent_name = args.get("name")
    reason = args.get("reason", "No reason provided")
    
    print(f"🔄 Handoff to: {agent_name}")
    print(f"📝 Reason: {reason}")
    
    try:
        # Find the agent with the given name (raises StopIteration if not found)
        target_agent = next(agent for agent in self.handoffs if agent.name == agent_name)
        
        # Handoff the control to the other agent
        return True, target_agent.run(messages)
        
    except StopIteration:
        # Agent not found
        return False, {
            "type": "function_call_output",
            "call_id": function_call.call_id,
            "output": json.dumps({"result": f"Handoff failed: Agent '{agent_name}' not found. Available agents: {[agent.name for agent in self.handoffs]}"})
        }
    except Exception as e:
        # Any other error during handoff execution
        return False, {
            "type": "function_call_output",
            "call_id": function_call.call_id,
            "output": json.dumps({"result": f"Handoff failed: Error during handoff to '{agent_name}': {str(e)}"})
        }

The method executes the following steps in sequence:

  1. Parameter extraction: Since function_call.arguments is a JSON string, we use json.loads() to parse it into a dictionary, then extract the target agent's name and handoff reason for logging and agent lookup.

  2. Agent lookup: Uses next() with a generator expression to find the first agent in the handoffs list matching the requested name. The next() function raises StopIteration if no matching agent is found, which we catch to handle the "agent not found" scenario gracefully.

  3. Control transfer: Calls the target agent's run method with the messages history, effectively transferring complete control of the conversation.

  4. Success return: Returns (True, target_agent_response) — the tuple return format (success_boolean, result_data) is crucial because it allows the main execution loop to distinguish between two fundamentally different outcomes: successful handoffs that should end the current agent's processing versus failed handoffs that should continue as normal tool interactions.

  5. Error handling: Catches StopIteration when no matching agent exists and returns (False, function_call_output_dict) — the tuple indicates this handoff failed and should be treated as a regular function result, allowing the current agent to continue processing and potentially respond with alternatives. The output is wrapped in json.dumps() because function outputs must be JSON strings.

Now we need to modify the main execution loop to handle handoff function calls differently from regular tools.

Integrating Handoffs into the Execution Flow

The main execution loop in the run method needs to detect handoff function calls and handle them differently from regular tools. When a handoff succeeds, it should immediately return the target agent's response rather than continuing the current agent's execution.

def run(self, input_messages):
    messages = input_messages.copy()

    turn = 0
    while turn < self.max_turns:
        turn += 1

        # Build the complete tool schemas list
        all_tools = []
        
        # Add regular tool schemas if they exist
        if self.tool_schemas:
            all_tools.extend(self.tool_schemas)
        
        # Add handoff schema if handoffs are available
        if self.handoffs:
            all_tools.append(self.handoff_schema)
        
        response = self.client.responses.create(
            model=self.model,
            instructions=self.system_prompt,
            input=messages,
            tools=all_tools,
            reasoning={"effort": self.reasoning_effort},
            store=False
        )

        # Check if the model wants to use any tools
        function_calls = [
            item for item in response.output
            if item.type == "function_call"
        ]

        if function_calls:
            function_outputs = []
            for function_call in function_calls:
                # If the tool use is a handoff
                if function_call.name == "handoff":
                    # Try to transfer control to another agent
                    handoff_success, handoff_result = self.call_handoff(function_call, messages)
                    # If handoff was successful, return the result from the other agent
                    if handoff_success:
                        return handoff_result
                    # If handoff failed, treat it as a regular tool result
                    else:
                        function_outputs.append(handoff_result)
                else:
                    # Add function call to messages
                    messages.append({
                        "type": "function_call",
                        "name": function_call.name,
                        "arguments": function_call.arguments,
                        "call_id": function_call.call_id
                    })
                    # Execute regular tools
                    tool_result = self.call_tool(function_call)
                    # Add result to tool results list
                    function_outputs.append(tool_result)

            # Add all tool results to messages
            messages.extend(function_outputs)
    
        else:
            # Return if no tools are requested
            messages.append({
                "role": "assistant",
                "content": response.output_text
            })

            return messages, response.output_text

The key difference from the previous tool delegation pattern is how we handle specific function calls. We filter response.output to build a list of all items with type == "function_call", just as we've done before. However, now we check each function call's name to determine if it's a handoff request that requires special handling.

When processing each function call, we check if function_call.name == "handoff". For handoff calls, we attempt the control transfer and immediately return if successful, bypassing normal tool result processing. This is what makes handoffs different from tool calls: instead of collecting the result and continuing the conversation, a successful handoff ends the current agent's involvement and returns the target agent's complete response.

For regular tools, we add the function call to messages, execute the tool, and collect the result. All function outputs (both from failed handoffs and regular tools) are then added to the message history for the next turn.

With all the handoff mechanics in place, let's create a complete example to test the system.

Setting Up the Agent System

Let's create a complete example that demonstrates how agents make intelligent handoff decisions. We'll set up a general assistant that can hand off mathematical problems to a specialized calculator assistant.

import json
from agent import Agent
from functions import sum_numbers, multiply_numbers, subtract_numbers, divide_numbers, power, square_root

# Load tool schemas (OpenAI Responses API format)
with open('schemas.json', 'r') as f:
    tool_schemas = json.load(f)

# Build specialist agents
calculator_assistant = Agent(
    name="calculator_assistant",
    system_prompt=(
        "You are a calculator assistant. You specialize in mathematical calculations and solving equations. "
        "Always use your available tools to compute."
    ),
    tools={
        "sum_numbers": sum_numbers,
        "multiply_numbers": multiply_numbers,
        "subtract_numbers": subtract_numbers,
        "divide_numbers": divide_numbers,
        "power": power,
        "square_root": square_root
    },
    tool_schemas=tool_schemas
)

# General assistant that can hand off to the calculator
helpful_assistant = Agent(
    name="helpful_assistant",
    system_prompt="You are a helpful assistant. You can assist with various tasks, but should always handoff specific tasks to specialist agents.",
    handoffs=[calculator_assistant]
)

Notice how we create the calculator assistant first without any handoffs, then create the general assistant with the calculator in its handoffs list. This creates a clear hierarchy where the general assistant can transfer control to the specialist, but not vice versa.

Now let's test the system with different types of questions to see how it makes handoff decisions.

Testing General Knowledge Questions

Let's test the system with a general knowledge question to see how the agent decides whether to handle the task itself or perform a handoff.

# Example 1: General knowledge (no handoff expected)
messages = [{"role": "user", "content": "What is the capital of France?"}]
_, response = helpful_assistant.run(messages)
print(response)

When we run this test, the general assistant recognizes that this is a straightforward factual question that doesn't require mathematical expertise:

Paris.

The agent handled this question directly without any handoffs or tool calls, demonstrating that it can distinguish between tasks it should handle itself and those requiring specialist expertise. Now let's test with a mathematical problem that should trigger a handoff to see the complete control transfer process in action.

Testing Mathematical Problem Handoffs

Now let's test with a mathematical problem that should trigger a handoff to demonstrate the complete control transfer process.

# Example 2: Math problem (handoff expected to calculator assistant)
messages = [{"role": "user", "content": "Solve x^2 - 5x + 6 = 0."}]
_, response = helpful_assistant.run(messages)

print("\n=== Final Response ===\n")
print(response)

This test demonstrates the complete handoff process in action:

🔄 Handoff to: calculator_assistant
📝 Reason: The user asked to solve a quadratic equation, which involves equation solving.
🔧 Tool called: power({'base': -5, 'exponent': 2})
🔧 Tool called: subtract_numbers({'a': 25, 'b': 24})
🔧 Tool called: square_root({'number': 1})
🔧 Tool called: sum_numbers({'a': 5, 'b': 1})
🔧 Tool called: subtract_numbers({'a': 5, 'b': 1})
🔧 Tool called: divide_numbers({'a': 6, 'b': 2})

=== Final Response ===

Answer:
x = 2 or x = 3

The execution trace shows the complete handoff process: the general assistant recognized that this was a mathematical problem requiring specialist expertise, initiated a handoff to the calculator assistant with a clear reason, and then the calculator assistant took complete control of the conversation. The calculator assistant used its mathematical tools to solve the equation step by step and provided the final response directly to the user.

When to Use Agents as Tools vs Handoffs

Understanding when to apply each pattern is crucial for building effective agent systems.

Use agents as tools when you need an orchestrating agent to maintain control and synthesize multiple specialist inputs into a unified response. This works well for complex tasks requiring coordination across different domains, like planning a trip that involves flights, hotels, and restaurants.

Use handoffs when a specialist is clearly better equipped to handle the entire conversation from a certain point forward. This is ideal when the task falls entirely within one domain of expertise and the specialist can provide more value through direct interaction than filtered through an orchestrator.

The key question: Does the task require orchestration and synthesis, or does it need deep specialization with direct user interaction? Choose accordingly.

Best Practices and Common Pitfalls

When implementing handoffs, success depends heavily on designing clear decision boundaries and robust error handling. The most effective handoff systems define explicit criteria in agent prompts, helping agents make confident transfer decisions rather than hesitating between options. For example, your general assistant should know precisely when mathematical problems warrant a calculator handoff versus when they can provide basic arithmetic directly.

Key practices for reliable handoffs include:

  • Define clear handoff criteria in agent prompts so agents know exactly when to transfer control
  • Implement robust error handling for failed handoffs with graceful fallbacks
  • Use descriptive handoff reasons for debugging and system transparency
  • Design handoff chains with clear direction to avoid circular transfers

The biggest pitfall to avoid is creating circular handoffs where agents pass control back and forth indefinitely. Design your handoff chains with clear directionality and avoid giving agents too many transfer options, which can lead to decision paralysis. Remember that handoffs should feel like natural conversation flows, similar to being transferred to the right department in a well-organized company rather than bouncing between confused representatives.

Summary & Preparation for Practice

You've now mastered the handoff pattern, a powerful approach for building agent systems where specialists can take complete control of conversations when their expertise is needed. This pattern differs fundamentally from agent-as-tool delegation because it transfers not just the task, but the entire conversation ownership to the most appropriate agent.

In your upcoming practice exercises, you'll build multi-agent systems with complex handoff chains, where agents can intelligently route conversations through multiple specialists based on the evolving needs of each interaction. This foundation will enable you to create sophisticated agent ecosystems that can handle diverse, complex tasks while maintaining clear specialization and efficient resource utilization.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal