Add sub-agent support as tools

Merged
JV
6mo ago
+839-268

Agents can now be returned directly from the tools() method, allowing them to act as sub-agents. Following the industry-standard pattern of treating sub-agents as tools, the parent agent's LLM invokes sub-agents like any other tool, passing a task description and receiving the result text.

class ProjectManager implements Agent, HasTools
{
    use Promptable;

    public function instructions(): string
    {
        return 'You delegate research tasks to your sub-agent.';
    }

    public function tools(): iterable
    {
        return [
            new WebSearch,
            new ResearchAgent,
        ];
    }
}

Sub-agents are full agents, they support attributes, their own tools, structured output, and any other agent capability. Agents that declare a tool-facing identity implement the ActsAsTool interface:

#[Provider('anthropic')]
#[Model('claude-sonnet-4-5')]
#[MaxSteps(5)]
class ResearchAgent implements Agent, HasTools, ActsAsTool
{
    use Promptable;

    public function name(): string
    {
        return 'research_agent';
    }

    public function description(): string
    {
        return 'Research a topic in depth and return a summary.';
    }

    public function instructions(): string
    {
        return 'You are a research agent. Summarize your findings concisely.';
    }

    public function tools(): iterable
    {
        return [new WebSearch];
    }
}

Sub-agents that implement ActsAsTool define name() and description() for explicit tool identification. If omitted, the class basename and a generic description are used as fallbacks so internal instructions are never leaked to the parent LLM.

Each sub-agent invocation runs with isolated context, no conversation history is shared from the parent, keeping context clean and preventing bloat.

Approach

  • AgentTool: adapter class that wraps an Agent as a Tool with a { task: string } schema
  • ActsAsTool: interface for agents that declare their tool-facing name and description
  • GeneratesText::resolveTools(): automatically wraps any Agent found in tools() into an AgentTool
  • Both GeneratesText and StreamsText use resolveTools() instead of reading tools() directly
  • Sub-agent errors are caught and returned as tool results instead of killing the parent flow

Ref: #75, #58