|
| 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\Platform\Message\Content\Text; |
| 21 | +use Symfony\AI\Platform\Message\Message; |
| 22 | +use Symfony\AI\Platform\Message\MessageBag; |
| 23 | +use Symfony\AI\Platform\Message\UserMessage; |
| 24 | +use Symfony\AI\Platform\Result\ResultInterface; |
| 25 | + |
| 26 | +/** |
| 27 | + * A multi-agent system that coordinates multiple specialized agents. |
| 28 | + * |
| 29 | + * This agent acts as a central orchestrator, delegating tasks to specialized agents |
| 30 | + * based on handoff rules and managing the conversation flow between agents. |
| 31 | + * |
| 32 | + * @author Oskar Stark <[email protected]> |
| 33 | + */ |
| 34 | +final class MultiAgent implements AgentInterface |
| 35 | +{ |
| 36 | + /** |
| 37 | + * @param Handoff[] $handoffs Handoff definitions for agent routing |
| 38 | + */ |
| 39 | + public function __construct( |
| 40 | + private AgentInterface $orchestrator, |
| 41 | + private array $handoffs, |
| 42 | + private string $name = 'multi-agent', |
| 43 | + private LoggerInterface $logger = new NullLogger(), |
| 44 | + ) { |
| 45 | + if ([] === $handoffs) { |
| 46 | + throw new InvalidArgumentException('Handoffs array cannot be empty.'); |
| 47 | + } |
| 48 | + |
| 49 | + if (\count($handoffs) < 2) { |
| 50 | + throw new InvalidArgumentException('MultiAgent requires at least 2 handoffs. For a single handoff, use the agent directly.'); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public function getName(): string |
| 55 | + { |
| 56 | + return $this->name; |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * @param array<string, mixed> $options |
| 61 | + * |
| 62 | + * @throws ExceptionInterface When the agent encounters an error during orchestration or handoffs |
| 63 | + */ |
| 64 | + public function call(MessageBag $messages, array $options = []): ResultInterface |
| 65 | + { |
| 66 | + $userMessages = $messages->withoutSystemMessage(); |
| 67 | + |
| 68 | + // Ask orchestrator which agent to target using JSON response format |
| 69 | + $userText = self::extractUserMessage($userMessages); |
| 70 | + $this->logger->debug('MultiAgent: Processing user message', ['user_text' => $userText]); |
| 71 | + |
| 72 | + // Log available handoffs and agents |
| 73 | + $agentDetails = array_map(fn ($handoff) => [ |
| 74 | + 'to' => $handoff->getTo()->getName(), |
| 75 | + 'when' => $handoff->getWhen(), |
| 76 | + ], $this->handoffs); |
| 77 | + $this->logger->debug('MultiAgent: Available agents for routing', ['agents' => $agentDetails]); |
| 78 | + |
| 79 | + $agentSelectionPrompt = $this->buildAgentSelectionPrompt($userText); |
| 80 | + $agentSelectionMessages = new MessageBag(Message::ofUser($agentSelectionPrompt)); |
| 81 | + |
| 82 | + $selectionResult = $this->orchestrator->call($agentSelectionMessages, $options); |
| 83 | + $responseContent = $selectionResult->getContent(); |
| 84 | + $this->logger->debug('MultiAgent: Received orchestrator response', ['response' => $responseContent]); |
| 85 | + |
| 86 | + // Parse JSON response |
| 87 | + $selectionData = json_decode($responseContent, true); |
| 88 | + if (\JSON_ERROR_NONE !== json_last_error()) { |
| 89 | + $this->logger->debug('MultiAgent: JSON parsing failed, falling back to orchestrator', ['json_error' => json_last_error_msg()]); |
| 90 | + |
| 91 | + return $this->orchestrator->call($messages, $options); |
| 92 | + } |
| 93 | + |
| 94 | + $agentName = $selectionData['agentName'] ?? null; |
| 95 | + $reasoning = $selectionData['reasoning'] ?? 'No reasoning provided'; |
| 96 | + $this->logger->debug('MultiAgent: Agent selection completed', [ |
| 97 | + 'selected_agent' => $agentName, |
| 98 | + 'reasoning' => $reasoning, |
| 99 | + ]); |
| 100 | + |
| 101 | + // If no specific agent is selected, fall back to orchestrator |
| 102 | + if (!$agentName || 'null' === $agentName) { |
| 103 | + $this->logger->debug('MultiAgent: Falling back to orchestrator', ['reason' => 'no_agent_selected']); |
| 104 | + |
| 105 | + return $this->orchestrator->call($messages, $options); |
| 106 | + } |
| 107 | + |
| 108 | + // Find the target agent by name |
| 109 | + $targetAgent = null; |
| 110 | + foreach ($this->handoffs as $handoff) { |
| 111 | + if ($handoff->getTo()->getName() === $agentName) { |
| 112 | + $targetAgent = $handoff->getTo(); |
| 113 | + break; |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + if (!$targetAgent) { |
| 118 | + $this->logger->debug('MultiAgent: Target agent not found, falling back to orchestrator', [ |
| 119 | + 'requested_agent' => $agentName, |
| 120 | + 'reason' => 'agent_not_found', |
| 121 | + ]); |
| 122 | + |
| 123 | + return $this->orchestrator->call($messages, $options); |
| 124 | + } |
| 125 | + |
| 126 | + $this->logger->debug('MultiAgent: Delegating to agent', ['agent_name' => $agentName]); |
| 127 | + $originalMessages = new MessageBag(self::findUserMessage($userMessages)); |
| 128 | + |
| 129 | + return $targetAgent->call($originalMessages, $options); |
| 130 | + } |
| 131 | + |
| 132 | + private static function extractUserMessage(MessageBag $messages): string |
| 133 | + { |
| 134 | + foreach ($messages->getMessages() as $message) { |
| 135 | + if ($message instanceof UserMessage) { |
| 136 | + $textParts = []; |
| 137 | + foreach ($message->content as $content) { |
| 138 | + if ($content instanceof Text) { |
| 139 | + $textParts[] = $content->text; |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + return implode(' ', $textParts); |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + throw new RuntimeException('No user message found in conversation.'); |
| 148 | + } |
| 149 | + |
| 150 | + private static function findUserMessage(MessageBag $messages): UserMessage |
| 151 | + { |
| 152 | + foreach ($messages->getMessages() as $message) { |
| 153 | + if ($message instanceof UserMessage) { |
| 154 | + return $message; |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + throw new RuntimeException('No user message found in conversation.'); |
| 159 | + } |
| 160 | + |
| 161 | + private function buildAgentSelectionPrompt(string $userQuestion): string |
| 162 | + { |
| 163 | + $agentDescriptions = []; |
| 164 | + $agentNames = ['null']; |
| 165 | + |
| 166 | + foreach ($this->handoffs as $handoff) { |
| 167 | + $triggers = implode(', ', $handoff->getWhen()); |
| 168 | + $agentName = $handoff->getTo()->getName(); |
| 169 | + $agentDescriptions[] = "- {$agentName}: {$triggers}"; |
| 170 | + $agentNames[] = $agentName; |
| 171 | + } |
| 172 | + |
| 173 | + $agentList = implode("\n", $agentDescriptions); |
| 174 | + $validAgents = implode('", "', $agentNames); |
| 175 | + |
| 176 | + return <<<PROMPT |
| 177 | + You are an intelligent agent orchestrator. Based on the user's question, determine which specialized agent should handle the request. |
| 178 | + |
| 179 | + User question: "{$userQuestion}" |
| 180 | + |
| 181 | + Available agents and their capabilities: |
| 182 | + {$agentList} |
| 183 | + |
| 184 | + Analyze the user's question and select the most appropriate agent. If no specific agent is needed, select "null". |
| 185 | + |
| 186 | + Respond with JSON in this exact format: |
| 187 | + { |
| 188 | + "agentName": "<one of: \"{$validAgents}\">", |
| 189 | + "reasoning": "<your reasoning for the selection>" |
| 190 | + } |
| 191 | + |
| 192 | + The agentName must be exactly one of the available agent names or "none". |
| 193 | + PROMPT; |
| 194 | + } |
| 195 | +} |
| 196 | + |
0 commit comments