|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\AI\Agent\MultiAgent; |
| 13 | + |
| 14 | +use Psr\Log\LoggerInterface; |
| 15 | +use Psr\Log\NullLogger; |
| 16 | +use Symfony\AI\Agent\AgentInterface; |
| 17 | +use Symfony\AI\Agent\Exception\ExceptionInterface; |
| 18 | +use Symfony\AI\Agent\Exception\InvalidArgumentException; |
| 19 | +use Symfony\AI\Agent\Exception\RuntimeException; |
| 20 | +use Symfony\AI\Agent\MultiAgent\Handoff\Decision; |
| 21 | +use Symfony\AI\Platform\Message\Message; |
| 22 | +use Symfony\AI\Platform\Message\MessageBag; |
| 23 | +use Symfony\AI\Platform\Result\ResultInterface; |
| 24 | + |
| 25 | +/** |
| 26 | + * A multi-agent system that coordinates multiple specialized agents. |
| 27 | + * |
| 28 | + * This agent acts as a central orchestrator, delegating tasks to specialized agents |
| 29 | + * based on handoff rules and managing the conversation flow between agents. |
| 30 | + * |
| 31 | + * @author Oskar Stark <[email protected]> |
| 32 | + */ |
| 33 | +final class MultiAgent implements AgentInterface |
| 34 | +{ |
| 35 | + /** |
| 36 | + * @param AgentInterface $orchestrator Agent responsible for analyzing requests and selecting appropriate handoffs |
| 37 | + * @param Handoff[] $handoffs Handoff definitions for agent routing |
| 38 | + * @param AgentInterface $fallback Fallback agent when no handoff conditions match |
| 39 | + * @param non-empty-string $name Name of the multi-agent |
| 40 | + * @param LoggerInterface $logger Logger for debugging handoff decisions |
| 41 | + */ |
| 42 | + public function __construct( |
| 43 | + private AgentInterface $orchestrator, |
| 44 | + private array $handoffs, |
| 45 | + private AgentInterface $fallback, |
| 46 | + private string $name = 'multi-agent', |
| 47 | + private LoggerInterface $logger = new NullLogger(), |
| 48 | + ) { |
| 49 | + if ([] === $handoffs) { |
| 50 | + throw new InvalidArgumentException('MultiAgent requires at least 1 handoff.'); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @return non-empty-string |
| 56 | + */ |
| 57 | + public function getName(): string |
| 58 | + { |
| 59 | + return $this->name; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @throws ExceptionInterface When the agent encounters an error during orchestration or handoffs |
| 64 | + */ |
| 65 | + public function call(MessageBag $messages, array $options = []): ResultInterface |
| 66 | + { |
| 67 | + $userMessages = $messages->withoutSystemMessage(); |
| 68 | + |
| 69 | + $userText = $userMessages->getUserMessageText(); |
| 70 | + if (null === $userText) { |
| 71 | + throw new RuntimeException('No user message found in conversation.'); |
| 72 | + } |
| 73 | + $this->logger->debug('MultiAgent: Processing user message', ['user_text' => $userText]); |
| 74 | + |
| 75 | + $this->logger->debug('MultiAgent: Available agents for routing', ['agents' => array_map(fn ($handoff) => [ |
| 76 | + 'to' => $handoff->getTo()->getName(), |
| 77 | + 'when' => $handoff->getWhen(), |
| 78 | + ], $this->handoffs)]); |
| 79 | + |
| 80 | + $agentSelectionPrompt = $this->buildAgentSelectionPrompt($userText); |
| 81 | + |
| 82 | + $decision = $this->orchestrator->call(new MessageBag(Message::ofUser($agentSelectionPrompt)), array_merge($options, [ |
| 83 | + 'output_structure' => Decision::class, |
| 84 | + ]))->getContent(); |
| 85 | + |
| 86 | + if (!$decision instanceof Decision) { |
| 87 | + $this->logger->debug('MultiAgent: Failed to get decision, falling back to orchestrator'); |
| 88 | + |
| 89 | + return $this->orchestrator->call($messages, $options); |
| 90 | + } |
| 91 | + |
| 92 | + $this->logger->debug('MultiAgent: Agent selection completed', [ |
| 93 | + 'selected_agent' => $decision->agentName, |
| 94 | + 'reasoning' => $decision->reasoning, |
| 95 | + ]); |
| 96 | + |
| 97 | + if (!$decision->hasAgent()) { |
| 98 | + $this->logger->debug('MultiAgent: Using fallback agent', ['reason' => 'no_agent_selected']); |
| 99 | + |
| 100 | + return $this->fallback->call($messages, $options); |
| 101 | + } |
| 102 | + |
| 103 | + // Find the target agent by name |
| 104 | + $targetAgent = null; |
| 105 | + foreach ($this->handoffs as $handoff) { |
| 106 | + if ($handoff->getTo()->getName() === $decision->agentName) { |
| 107 | + $targetAgent = $handoff->getTo(); |
| 108 | + break; |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + if (!$targetAgent) { |
| 113 | + $this->logger->debug('MultiAgent: Target agent not found, using fallback agent', [ |
| 114 | + 'requested_agent' => $decision->agentName, |
| 115 | + 'reason' => 'agent_not_found', |
| 116 | + ]); |
| 117 | + |
| 118 | + return $this->fallback->call($messages, $options); |
| 119 | + } |
| 120 | + |
| 121 | + $this->logger->debug('MultiAgent: Delegating to agent', ['agent_name' => $decision->agentName]); |
| 122 | + |
| 123 | + $userMessage = $userMessages->getUserMessage(); |
| 124 | + if (null === $userMessage) { |
| 125 | + throw new RuntimeException('No user message found in conversation.'); |
| 126 | + } |
| 127 | + |
| 128 | + // Call the selected agent with the original user question |
| 129 | + return $targetAgent->call(new MessageBag($userMessage), $options); |
| 130 | + } |
| 131 | + |
| 132 | + private function buildAgentSelectionPrompt(string $userQuestion): string |
| 133 | + { |
| 134 | + $agentDescriptions = []; |
| 135 | + $agentNames = []; |
| 136 | + |
| 137 | + foreach ($this->handoffs as $handoff) { |
| 138 | + $triggers = implode(', ', $handoff->getWhen()); |
| 139 | + $agentName = $handoff->getTo()->getName(); |
| 140 | + $agentDescriptions[] = "- {$agentName}: {$triggers}"; |
| 141 | + $agentNames[] = $agentName; |
| 142 | + } |
| 143 | + |
| 144 | + $agentDescriptions[] = "- {$this->fallback->getName()}: fallback agent for general/unmatched queries"; |
| 145 | + $agentNames[] = $this->fallback->getName(); |
| 146 | + |
| 147 | + $agentList = implode("\n", $agentDescriptions); |
| 148 | + $validAgents = implode('", "', $agentNames); |
| 149 | + |
| 150 | + return <<<PROMPT |
| 151 | + You are an intelligent agent orchestrator. Based on the user's question, determine which specialized agent should handle the request. |
| 152 | +
|
| 153 | + User question: "{$userQuestion}" |
| 154 | +
|
| 155 | + Available agents and their capabilities: |
| 156 | + {$agentList} |
| 157 | +
|
| 158 | + Analyze the user's question and select the most appropriate agent to handle this request. |
| 159 | + Return an empty string ("") for agentName if no specific agent matches the request criteria. |
| 160 | +
|
| 161 | + Available agent names: {$validAgents} |
| 162 | +
|
| 163 | + Provide your selection and explain your reasoning. |
| 164 | + PROMPT; |
| 165 | + } |
| 166 | +} |
0 commit comments