OpenAI Agents Python 21 files ยท 0 subfolders
Copy to Workspace 06_HANDOFFS Shared from "OpenAI Agents Python" on Inkdown
Handoffs - Comprehensive Deep Dive
Overview
Handoffs are the mechanism that enables multi-agent workflows in the OpenAI Agents SDK. A handoff occurs when one agent delegates a task to another agent. Think of handoffs as "transfer of control" or "referral" - just like a doctor might refer you to a specialist, agents can hand off tasks to other specialized agents.
Core Concepts
What is a Handoff?
A handoff is when an agent decides that another agent is better suited to handle the current task and transfers control to that agent. The handoff includes:
The target agent (who to hand off to)
The context/information to pass along
Optional filtering of what information to pass
Optional custom logic for the handoff
Why Handoffs Matter
Specialization - Different agents can specialize in different domains
Modularity - Build complex workflows from simple, focused agents
01_AGENT_SYSTEM.md
Efficiency - Route tasks to the most capable agent
Scalability - Add new capabilities by adding new agents
Clarity - Clear separation of concerns
Handoff vs Agent as Tool Handoffs and "agents as tools" both involve multiple agents, but they work differently:
The new agent receives the full conversation history
The new agent takes over the conversation
The original agent is no longer involved
Good for: Domain specialization, expertise routing
The new agent receives generated input (not full history)
The new agent runs as a tool and returns
The original agent continues the conversation
Good for: Subtasks, specific queries, calculations
Handoff Class
Handoff Structure
Creating Handoffs The simplest way is using the handoff() helper:
The handoff() function creates a Handoff object
It generates a tool name (e.g., transfer_to_specialist)
It generates a tool description
It creates an empty JSON schema (no arguments by default)
It sets up the invocation function to return the specialist agent
Handoff Configuration
Custom Tool Name Override the default tool name:
Custom Tool Description Override the default description:
Handoff with Input Pass structured input to the handoff:
The LLM generates JSON arguments matching HandoffInput
The arguments are validated against the schema
The on_handoff function is called with the validated input
The function can perform side effects (logging, tracking, etc.)
The specialist agent is still returned
Handoff Without Input Handoff without structured input (simpler):
Input Filter Filter what information is passed to the next agent:
HandoffInputData structure:
Nested Handoff History Control how conversation history is passed:
None (default) - Use run-level configuration
True - Collapse history into a single summary message
False - Pass full conversation history
True - For deep handoff chains to reduce token usage
False - When the next agent needs full context
Dynamic Enablement Handoffs can be dynamically enabled or disabled:
Feature flags
User tier-based access
Context-dependent availability
A/B testing
Handoff Execution Flow
Complete Handoff Flow
Handoff History Management
Default Behavior (Full History) By default, the full conversation history is passed to the next agent:
Full context preserved
No information loss
Agent can reference earlier conversation
Higher token usage
Potential for confusion in deep chains
Slower for long conversations
Nested History (Collapsed) When nest_handoff_history=True, history is collapsed:
Lower token usage
Cleaner context for deep chains
Faster for long conversations
Some detail lost in summary
Agent can't reference specific earlier messages
Depends on quality of summary
Custom History Mapping Provide a custom function to transform history:
Input Filter for Fine-Grained Control Use input filters for precise control:
Handoff Patterns
1. Triage Pattern One agent routes to specialists:
Customer support systems
Help desk workflows
Multi-domain support
2. Supervisor Pattern One agent supervises and delegates:
Complex task breakdown
Project management
Quality assurance
3. Escalation Pattern Escalate from general to specialist:
Tiered support systems
Escalation workflows
Progressive problem solving
4. Collaboration Pattern Agents collaborate on different aspects:
Content creation workflows
Multi-stage processes
Quality assurance pipelines
5. Context Switching Pattern Switch context based on user request:
General-purpose assistants
Multi-domain bots
Context-aware routing
Handoff and Sessions
Session Continuity Handoffs maintain session continuity:
Session History with Handoffs The session tracks which agent generated each item:
Compaction with Handoffs For long conversations with many handoffs:
Handoff Tracing
Handoff Spans Handoffs create trace spans:
Handoff Events Handoffs emit events during streaming:
Handoff Best Practices
1. Clear Handoff Descriptions Write clear descriptions for the LLM:
2. Appropriate Handoff Granularity Design handoffs at the right level:
3. Use Input Filters for Context Use input filters to control context:
4. Handle Handoff Failures Handle cases where handoffs might fail:
5. Test Handoff Paths Test all possible handoff paths:
Common Handoff Issues
1. Handoff Loops Problem: Agents hand off back and forth infinitely.
Solution: Use handoff history tracking:
2. Lost Context Problem: Important context is lost in handoff.
Solution: Use appropriate history management:
3. Ambiguous Handoffs Problem: LLM unsure which handoff to use.
Solution: Clear descriptions and maybe input types:
4. Too Many Handoffs Problem: Excessive handoffs slow down response.
Solution: Consolidate similar agents:
Handoff vs Agent as Tool Decision
When to Use Handoffs
The new agent needs full conversation context
The new agent takes over the conversation
Domain expertise routing is needed
Long-running specialized tasks
When to Use Agent as Tool
The subtask is self-contained
The parent agent should continue the conversation
The subtask returns specific data
Parallel execution of multiple subtasks
Example Comparison
Summary Handoffs enable powerful multi-agent workflows. Key takeaways:
Handoffs transfer control from one agent to another
handoff() helper creates handoff objects
Tool name/description can be customized
Structured input allows passing data to handoffs
Input filters control what information is passed
Nested history collapses conversation to save tokens
Dynamic enablement allows context-dependent handoffs
Full history preserves complete context
Collapsed history reduces token usage
Custom mappers provide fine-grained control
Triage pattern routes to specialists
Supervisor pattern delegates tasks
Escalation pattern moves up tiers
Collaboration pattern chains agents
Context switching changes domains
Sessions maintain continuity across handoffs
Tracing tracks handoff events
Clear descriptions help the LLM choose correctly
Appropriate granularity avoids too many agents
vs Agent as Tool - different use cases
Handoffs are essential for building sophisticated multi-agent systems with clear separation of concerns.