|
| 1 | +<?php |
| 2 | + |
| 3 | +use PhpLlm\LlmChain\Chain; |
| 4 | +use PhpLlm\LlmChain\Message\Message; |
| 5 | +use PhpLlm\LlmChain\Message\MessageBag; |
| 6 | +use PhpLlm\LlmChain\OpenAI\Model\Gpt; |
| 7 | +use PhpLlm\LlmChain\OpenAI\Model\Gpt\Version; |
| 8 | +use PhpLlm\LlmChain\OpenAI\Platform\OpenAI; |
| 9 | +use PhpLlm\LlmChain\StructuredOutput\ChainProcessor as StructuredOutputProcessor; |
| 10 | +use PhpLlm\LlmChain\StructuredOutput\ResponseFormatFactory; |
| 11 | +use PhpLlm\LlmChain\ToolBox\ChainProcessor as ToolProcessor; |
| 12 | +use PhpLlm\LlmChain\ToolBox\Tool\Clock; |
| 13 | +use PhpLlm\LlmChain\ToolBox\ToolAnalyzer; |
| 14 | +use PhpLlm\LlmChain\ToolBox\ToolBox; |
| 15 | +use Symfony\Component\Clock\Clock as SymfonyClock; |
| 16 | +use Symfony\Component\Dotenv\Dotenv; |
| 17 | +use Symfony\Component\HttpClient\HttpClient; |
| 18 | +use Symfony\Component\Serializer\Encoder\JsonEncoder; |
| 19 | +use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
| 20 | +use Symfony\Component\Serializer\Serializer; |
| 21 | + |
| 22 | +require_once dirname(__DIR__).'/vendor/autoload.php'; |
| 23 | +(new Dotenv())->loadEnv(dirname(__DIR__).'/.env'); |
| 24 | + |
| 25 | +if (empty($_ENV['OPENAI_API_KEY'])) { |
| 26 | + echo 'Please set the OPENAI_API_KEY environment variable.'.PHP_EOL; |
| 27 | + exit(1); |
| 28 | +} |
| 29 | + |
| 30 | +$platform = new OpenAI(HttpClient::create(), $_ENV['OPENAI_API_KEY']); |
| 31 | +$llm = new Gpt($platform, Version::gpt4oMini()); |
| 32 | + |
| 33 | +$clock = new Clock(new SymfonyClock()); |
| 34 | +$toolBox = new ToolBox(new ToolAnalyzer(), [$clock]); |
| 35 | +$toolProcessor = new ToolProcessor($toolBox); |
| 36 | +$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); |
| 37 | +$structuredOutputProcessor = new StructuredOutputProcessor(new ResponseFormatFactory(), $serializer); |
| 38 | +$chain = new Chain($llm, [$toolProcessor, $structuredOutputProcessor], [$toolProcessor, $structuredOutputProcessor]); |
| 39 | + |
| 40 | +$messages = new MessageBag(Message::ofUser('What date and time is it?')); |
| 41 | +$response = $chain->call($messages, ['response_format' => [ |
| 42 | + 'type' => 'json_schema', |
| 43 | + 'json_schema' => [ |
| 44 | + 'name' => 'clock', |
| 45 | + 'strict' => true, |
| 46 | + 'schema' => [ |
| 47 | + 'type' => 'object', |
| 48 | + 'properties' => [ |
| 49 | + 'date' => ['type' => 'string', 'description' => 'The current date in the format YYYY-MM-DD.'], |
| 50 | + 'time' => ['type' => 'string', 'description' => 'The current time in the format HH:MM:SS.'], |
| 51 | + ], |
| 52 | + 'required' => ['date', 'time'], |
| 53 | + 'additionalProperties' => false, |
| 54 | + ], |
| 55 | + ], |
| 56 | +]]); |
| 57 | + |
| 58 | +dump($response->getContent()); |
0 commit comments