agent_transfer.go
Overview
The agent_transfer.go file implements the logic and tools necessary for enabling agent-to-agent transfer within the large language model (LLM) agent framework. It orchestrates how an LLM agent, which may have sub-agents and a parent agent, can transfer control or delegate a user request to another agent better suited to answer the query. The file primarily supports two flow types:
SingleFlow: Restricts agent transfers with no sub-agents and disallows transfers to parents or peers.
AutoFlow: Allows transfers between parent and sub-agents and among peer agents under specific conditions.
This transfer mechanism is critical for enabling complex agent hierarchies and delegation patterns, facilitating modular and scalable AI workflows.
Key Components
AgentTransferRequestProcessor
func AgentTransferRequestProcessor(ctx agent.InvocationContext, req *model.LLMRequest) error
Purpose: Entry point to process an LLM request with potential agent transfer capabilities.
Parameters:
ctx: Agent invocation context that provides access to the current agent and parent agents.req: The LLM request to be processed and possibly augmented with transfer instructions/tools.
Returns: An error if processing or tool appending fails; otherwise,
nil.Description:
Checks if the current agent supports
AutoFlowtransfer.Retrieves parent agents from context.
Determines valid transfer targets (sub-agents, parent, peers).
If valid targets exist, constructs transfer instructions and appends the
TransferToAgentToolto the request.
Usage: Automatically invoked in the agent invocation lifecycle to inject transfer logic.
TransferToAgentTool (implements tool.Tool)
A tool that enables transferring the current request handling to a different agent.
Methods:
Description() string
Returns a string describing the tool’s purpose: to transfer the question to another agent better suited to answer.Name() string
Returns the tool name"transfer_to_agent".IsLongRunning() bool
Returnsfalseindicating the tool is not long-running.Declaration() *genai.FunctionDeclaration
Defines the function signature for LLM function call integration. It accepts an object with a required string property"agent_name".ProcessRequest(ctx tool.Context, req *model.LLMRequest) error
Ensures the tool is appended to the request tools.Run(ctx tool.Context, args any) (map[string]any, error)
Core runtime method that processes a transfer command:Expects
argsto be a map containing"agent_name"(string).Validates the argument and sets
ctx.Actions().TransferToAgentto the target agent name.Returns an empty result map or an error.
Example Usage:
An LLM can call the "transfer_to_agent" function with {"agent_name": "agentX"} to hand off the request handling.
Transfer Target Computation
transferTargets
func transferTargets(agent, parent agent.Agent) []agent.Agent
Purpose: Determines the list of agents to which the current agent can transfer control.
Parameters:
agent: The current agent.parent: The parent of the current agent.
Returns: Slice of
agent.Agentrepresenting valid transfer targets.Logic:
Starts with the current agent’s sub-agents.
Adds the parent agent if transfers to parent are allowed.
Adds peer agents (other sub-agents of the parent) if peer transfers are allowed and the parent is an LLM agent using AutoFlow.
Notes: This respects flags like
DisallowTransferToParentandDisallowTransferToPeers.
Helper Functions
asLLMAgent(agent agent.Agent) Agent
Casts the supplied agent to the localAgentinterface type if possible, else returnsnil.shouldUseAutoFlow(agent agent.Agent) bool
Returnstrueif the agent supports AutoFlow transfers, i.e., it has sub-agents or allows transfer to parent/peers.appendTools(r *model.LLMRequest, tools ...tool.Tool) error
Safely appends new tools to the LLM request, ensuring no duplicates or nameless tools are added. Also manages the function declarations for tools in the request config.
Instruction Template for Transfer
The instructions injected into the LLM prompt to guide it on how to transfer control are generated by:
func instructionsForTransferToAgent(curAgent, parent agent.Agent, targets []agent.Agent, transferTool tool.Tool) (string, error)
Uses a Go
template(agentTransferInstructionTemplate) to produce human-readable instructions listing possible agent targets with names and descriptions.Includes guidance to call the transfer tool function when another agent is better suited.
Mentions the parent agent as a fallback transfer target if applicable.
Important Implementation Details
The file draws inspiration from Python implementations in
auto_flow.pyandagent_transfer.pywithin the same codebase.Transfer directions are carefully controlled via agent configuration flags to prevent unwanted delegation loops or invalid transfers.
The transfer tool is implemented as a first-class tool in the system, allowing the LLM to invoke it as a function call.
Transfer instructions are dynamically generated based on the current agent hierarchy and capabilities.
The transfer mechanism is integrated into the request processing pipeline, modifying the request before it reaches the LLM or tool execution phase.
Interaction with Other System Components
Agent Invocation Context (
agent.InvocationContext): Provides access to the current agent and parents, pivotal for determining transfer possibilities.Agent Hierarchy (
agent.Agent): The transfer logic depends on the agent’s sub-agents and parent relationships.Tool Framework (
tool.Tool): TheTransferToAgentToolintegrates with the tool system to be callable by LLM or agent runners.LLM Request Model (
model.LLMRequest): The transfer instructions and tool declarations are appended to the LLM request to guide the LLM’s behavior.Parent Map (
parentmap.FromContext): Supplies parent agents for the current agent, essential for transfer target computation.Templates (
safehtml/template): Used to generate instructions for the LLM based on agent metadata.Utility Functions (
utils.AppendInstructions): Used to add instructions to the LLM request's prompt.
Mermaid Diagram: Structure of agent_transfer.go
classDiagram
class AgentTransferRequestProcessor {
+error(ctx, req)
}
class TransferToAgentTool {
+Description()
+Name()
+IsLongRunning()
+Declaration()
+ProcessRequest(ctx, req)
+Run(ctx, args)
}
class Agent {
+Name()
+SubAgents()
+internal()
}
class LLMRequest {
+Tools
+Config
}
class FunctionDeclaration {
+Name
+Description
+Parameters
}
AgentTransferRequestProcessor --> TransferToAgentTool : uses
AgentTransferRequestProcessor --> Agent : reads
AgentTransferRequestProcessor --> LLMRequest : modifies
TransferToAgentTool ..> FunctionDeclaration : returns
Detailed Explanation of Main Functions and Methods
AgentTransferRequestProcessor
Checks if the current agent supports the AutoFlow transfer mechanism.
Retrieves parent agents from context.
Computes transfer targets (sub-agents, parent, peers).
If targets exist, creates transfer instructions and appends the transfer tool to the request.
Returns errors if any step fails.
TransferToAgentTool Methods
Description: Explains the purpose of the tool for transferring questions to other agents.
Name: Returns
"transfer_to_agent".IsLongRunning: Returns
false.Declaration: Defines the schema for the LLM function call interface:
Input: JSON object with required
"agent_name"string property.Purpose: To allow LLMs to invoke transfer via function call.
ProcessRequest: Appends itself to the request tools.
Run: Processes the transfer request during execution:
Validates args.
Sets transfer action in context.
Returns empty response or error.
transferTargets
Clones the current agent’s sub-agents as initial targets.
Adds parent agent if allowed.
Adds peer agents if allowed and parent is AutoFlow-enabled LLM agent.
Returns the final list of valid transfer targets.
appendTools
Adds tools to the LLM request’s tool map.
Checks for duplicates and unnamed tools.
Aggregates function declarations for tools supporting
FunctionTool.Adds function declarations to the request config under
genai.Tool.
instructionsForTransferToAgent
Renders a prompt template listing target agents and transfer instructions.
Includes parent agent if transfer to parent is allowed.
Provides instructions for LLM to transfer control by calling the transfer tool function.
References to Related Topics
This file is closely related to the LLM Integration and Agents topic for managing agent flows and tool integration.
It relies on Agent Invocation Context for context and parent relationships.
The tool implementation follows patterns described in Tooling System.
The flow and transfer logic connects with Agent Workflow Management for orchestrating sub-agent delegation.
Instruction template processing is related to Instruction Template Processing and Instruction Injection.
Usage Example
In an agent invocation lifecycle, before processing a user question, AgentTransferRequestProcessor is called:
err := AgentTransferRequestProcessor(ctx, llmRequest)
if err != nil {
// handle error
}
// The request now includes transfer instructions and the transfer tool
During LLM execution, the agent may decide to transfer:
{
"function_call": {
"name": "transfer_to_agent",
"arguments": "{\"agent_name\": \"specialist_agent\"}"
}
}
Upon running the tool, the transfer action is recorded, and control is delegated accordingly.
This completes the detailed technical overview and documentation of the agent_transfer.go file.