|
| 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 | +use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory; |
| 13 | +use Symfony\AI\Platform\EventListener\TemplateRendererListener; |
| 14 | +use Symfony\AI\Platform\Message\Message; |
| 15 | +use Symfony\AI\Platform\Message\MessageBag; |
| 16 | +use Symfony\AI\Platform\Message\Template; |
| 17 | +use Symfony\AI\Platform\Message\TemplateRenderer\ChainTemplateRenderer; |
| 18 | +use Symfony\AI\Platform\Message\TemplateRenderer\StringTemplateRenderer; |
| 19 | +use Symfony\Component\EventDispatcher\EventDispatcher; |
| 20 | + |
| 21 | +require_once dirname(__DIR__, 2).'/bootstrap.php'; |
| 22 | + |
| 23 | +$eventDispatcher = new EventDispatcher(); |
| 24 | +$rendererRegistry = new ChainTemplateRenderer([ |
| 25 | + new StringTemplateRenderer(), |
| 26 | +]); |
| 27 | +$templateListener = new TemplateRendererListener($rendererRegistry); |
| 28 | +$eventDispatcher->addSubscriber($templateListener); |
| 29 | + |
| 30 | +$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client(), eventDispatcher: $eventDispatcher); |
| 31 | + |
| 32 | +echo "Multiple messages with templates\n"; |
| 33 | +echo "=================================\n\n"; |
| 34 | + |
| 35 | +$systemTemplate = Template::string('You are a {domain} assistant.'); |
| 36 | +$userTemplate = Template::string('Calculate {operation}'); |
| 37 | + |
| 38 | +$messages = new MessageBag( |
| 39 | + Message::forSystem($systemTemplate), |
| 40 | + Message::ofUser($userTemplate) |
| 41 | +); |
| 42 | + |
| 43 | +$result = $platform->invoke('gpt-4o-mini', $messages, [ |
| 44 | + 'template_vars' => [ |
| 45 | + 'domain' => 'math', |
| 46 | + 'operation' => '2 + 2', |
| 47 | + ], |
| 48 | +]); |
| 49 | + |
| 50 | +echo "System template: You are a {domain} assistant.\n"; |
| 51 | +echo "User template: Calculate {operation}\n"; |
| 52 | +echo "Variables: ['domain' => 'math', 'operation' => '2 + 2']\n"; |
| 53 | +echo 'Response: '.$result->asText()."\n"; |
0 commit comments