|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace LLM\Agents\PromptGenerator\Interceptors; |
| 6 | + |
| 7 | +use LLM\Agents\Agent\AgentInterface; |
| 8 | +use LLM\Agents\Agent\AgentRepositoryInterface; |
| 9 | +use LLM\Agents\LLM\AgentPromptGeneratorInterface; |
| 10 | +use LLM\Agents\LLM\Prompt\Chat\MessagePrompt; |
| 11 | +use LLM\Agents\LLM\Prompt\Chat\Prompt; |
| 12 | +use LLM\Agents\LLM\Prompt\Chat\PromptInterface; |
| 13 | +use LLM\Agents\LLM\PromptContextInterface; |
| 14 | +use LLM\Agents\PromptGenerator\PromptInterceptorInterface; |
| 15 | +use LLM\Agents\Solution\AgentLink; |
| 16 | +use LLM\Agents\Tool\SchemaMapperInterface; |
| 17 | + |
| 18 | +final readonly class LinkedAgentsInjector implements PromptInterceptorInterface |
| 19 | +{ |
| 20 | + public function __construct( |
| 21 | + private AgentRepositoryInterface $agents, |
| 22 | + private SchemaMapperInterface $schemaMapper, |
| 23 | + ) {} |
| 24 | + |
| 25 | + public function generate( |
| 26 | + AgentInterface $agent, |
| 27 | + \Stringable|string $userPrompt, |
| 28 | + PromptInterface $prompt, |
| 29 | + PromptContextInterface $context, |
| 30 | + AgentPromptGeneratorInterface $next, |
| 31 | + ): PromptInterface { |
| 32 | + \assert($prompt instanceof Prompt); |
| 33 | + |
| 34 | + if (\count($agent->getAgents()) === 0) { |
| 35 | + return $next->generate( |
| 36 | + agent: $agent, |
| 37 | + userPrompt: $userPrompt, |
| 38 | + context: $context, |
| 39 | + prompt: $prompt, |
| 40 | + ); |
| 41 | + } |
| 42 | + |
| 43 | + $associatedAgents = \array_map( |
| 44 | + fn(AgentLink $agent): array => [ |
| 45 | + 'agent' => $this->agents->get($agent->getName()), |
| 46 | + 'output_schema' => \json_encode($this->schemaMapper->toJsonSchema($agent->outputSchema)), |
| 47 | + ], |
| 48 | + $agent->getAgents(), |
| 49 | + ); |
| 50 | + |
| 51 | + return $next->generate( |
| 52 | + agent: $agent, |
| 53 | + userPrompt: $userPrompt, |
| 54 | + context: $context, |
| 55 | + prompt: $prompt |
| 56 | + ->withAddedMessage( |
| 57 | + MessagePrompt::system( |
| 58 | + prompt: <<<'PROMPT' |
| 59 | +There are agents {linked_agents} associated with you. You can ask them for help if you need it. |
| 60 | +Use the `ask_agent` tool and provide the agent key. |
| 61 | +Always follow rules: |
| 62 | +- Don't make up the agent key. Use only the ones from the provided list. |
| 63 | +PROMPT, |
| 64 | + ), |
| 65 | + ) |
| 66 | + ->withValues( |
| 67 | + values: [ |
| 68 | + 'linked_agents' => \implode( |
| 69 | + PHP_EOL, |
| 70 | + \array_map( |
| 71 | + static fn(array $agent): string => \json_encode([ |
| 72 | + 'key' => $agent['agent']->getKey(), |
| 73 | + 'description' => $agent['agent']->getDescription(), |
| 74 | + 'output_schema' => $agent['output_schema'], |
| 75 | + ]), |
| 76 | + $associatedAgents, |
| 77 | + ), |
| 78 | + ), |
| 79 | + ], |
| 80 | + ), |
| 81 | + ); |
| 82 | + } |
| 83 | +} |
0 commit comments