You can create specialized agents that collaborate by using WithHandoffs. When an agent is added via WithHandoffs, it is exposed to the model as a tool named handoff_to_<agent name>.
Key Details:
- Name Sanitization: Agent names are automatically sanitized to match Model API requirements (regex
^[a-zA-Z0-9_-]+$). For example, Weather Agent becomes handoff_to_Weather_Agent. - Validation: Use
agent.ValidateName to check names manually. - Result Tracking: After a handoff sequence,
result.LastAgent identifies the agent that produced the final output.
To implement this, define specialized agents with their own tools and instructions, then define a coordinator (frontend) agent that includes the specialized agents in its handoffs.
// Create specialized agents
mathAgent := agent.NewAgent("Math Agent")
mathAgent.SetModelProvider(provider)
mathAgent.WithModel("gemma-3-4b-it")
mathAgent.SetSystemInstructions("You are a specialized math agent.")
mathAgent.WithTools(calculatorTool)
weatherAgent := agent.NewAgent("Weather Agent")
weatherAgent.SetModelProvider(provider)
weatherAgent.WithModel("gemma-3-4b-it")
weatherAgent.SetSystemInstructions("You provide weather information.")
weatherAgent.WithTools(weatherTool)
// Create a frontend agent that coordinates tasks
frontendAgent := agent.NewAgent("Frontend Agent")
frontendAgent.SetModelProvider(provider)
frontendAgent.WithModel("gemma-3-4b-it")
frontendAgent.SetSystemInstructions(`You coordinate requests by delegating to specialized agents.
For math calculations, delegate to the Math Agent.
For weather information, delegate to the Weather Agent. `)
frontendAgent.WithHandoffs(mathAgent, weatherAgent)
// Run the frontend agent
result, err := runner.RunSync(frontendAgent, &runner.RunOptions{
Input: "What is 42 divided by 6 and what's the weather in Paris?",
MaxTurns: 20,
})