|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpLlm\LlmChain; |
| 6 | + |
| 7 | +use PhpLlm\LlmChain\Message\Message; |
| 8 | +use PhpLlm\LlmChain\Message\MessageBag; |
| 9 | +use PhpLlm\LlmChain\StructuredOutput\ResponseFormatFactory; |
| 10 | +use PhpLlm\LlmChain\ToolBox\RegistryInterface; |
| 11 | +use Symfony\Component\Serializer\SerializerInterface; |
| 12 | + |
| 13 | +final readonly class Chain |
| 14 | +{ |
| 15 | + public function __construct( |
| 16 | + private LanguageModel $llm, |
| 17 | + private ?RegistryInterface $toolRegistry = null, |
| 18 | + private ?ResponseFormatFactory $responseFormatFactory = null, |
| 19 | + private ?SerializerInterface $serializer = null, |
| 20 | + ) { |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * @param array<string, mixed> $options |
| 25 | + */ |
| 26 | + public function call(MessageBag $messages, array $options = []): string|object |
| 27 | + { |
| 28 | + $llmOptions = $options; |
| 29 | + |
| 30 | + if (!array_key_exists('tools', $llmOptions) && null !== $this->toolRegistry && $this->llm->hasToolSupport()) { |
| 31 | + $llmOptions['tools'] = $this->toolRegistry->getMap(); |
| 32 | + } |
| 33 | + |
| 34 | + if (array_key_exists('output_structure', $llmOptions) && null !== $this->responseFormatFactory && $this->llm->hasStructuredOutputSupport()) { |
| 35 | + $llmOptions['response_format'] = $this->responseFormatFactory->create($llmOptions['output_structure']); |
| 36 | + unset($llmOptions['output_structure']); |
| 37 | + } |
| 38 | + |
| 39 | + $response = $this->llm->call($messages, $llmOptions); |
| 40 | + |
| 41 | + while ($response->hasToolCalls()) { |
| 42 | + $clonedMessages = clone $messages; |
| 43 | + $clonedMessages[] = Message::ofAssistant(toolCalls: $response->getToolCalls()); |
| 44 | + |
| 45 | + foreach ($response->getToolCalls() as $toolCall) { |
| 46 | + $result = $this->toolRegistry->execute($toolCall); |
| 47 | + $clonedMessages[] = Message::ofToolCall($toolCall, $result); |
| 48 | + } |
| 49 | + |
| 50 | + $response = $this->llm->call($clonedMessages, $llmOptions); |
| 51 | + } |
| 52 | + |
| 53 | + if (!array_key_exists('output_structure', $options) || null === $this->serializer) { |
| 54 | + return $response->getContent(); |
| 55 | + } |
| 56 | + |
| 57 | + return $this->serializer->deserialize($response->getContent(), $options['output_structure'], 'json'); |
| 58 | + } |
| 59 | +} |
0 commit comments