|
| 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 App\Timeline; |
| 13 | + |
| 14 | +use Symfony\AI\Agent\AgentInterface; |
| 15 | +use Symfony\AI\Platform\Message\Message; |
| 16 | +use Symfony\AI\Platform\Message\MessageBag; |
| 17 | +use Symfony\AI\Platform\Result\TextResult; |
| 18 | +use Symfony\Component\DependencyInjection\Attribute\Autowire; |
| 19 | +use Symfony\Component\HttpFoundation\RequestStack; |
| 20 | + |
| 21 | +/** |
| 22 | + * @author Camille Islasse <[email protected]> |
| 23 | + */ |
| 24 | +final class Chat |
| 25 | +{ |
| 26 | + private const SESSION_KEY = 'timeline-chat'; |
| 27 | + |
| 28 | + public function __construct( |
| 29 | + private readonly RequestStack $requestStack, |
| 30 | + #[Autowire(service: 'ai.agent.timeline')] |
| 31 | + private readonly AgentInterface $agent, |
| 32 | + ) { |
| 33 | + } |
| 34 | + |
| 35 | + public function loadMessages(): MessageBag |
| 36 | + { |
| 37 | + return $this->requestStack->getSession()->get(self::SESSION_KEY, new MessageBag()); |
| 38 | + } |
| 39 | + |
| 40 | + public function submitMessage(string $message): void |
| 41 | + { |
| 42 | + $messages = $this->loadMessages(); |
| 43 | + |
| 44 | + $messages->add(Message::ofUser($message)); |
| 45 | + $result = $this->agent->call($messages); |
| 46 | + |
| 47 | + \assert($result instanceof TextResult); |
| 48 | + |
| 49 | + $messages->add(Message::ofAssistant($result->getContent())); |
| 50 | + |
| 51 | + $this->saveMessages($messages); |
| 52 | + } |
| 53 | + |
| 54 | + public function reset(): void |
| 55 | + { |
| 56 | + $this->requestStack->getSession()->remove(self::SESSION_KEY); |
| 57 | + } |
| 58 | + |
| 59 | + private function saveMessages(MessageBag $messages): void |
| 60 | + { |
| 61 | + $this->requestStack->getSession()->set(self::SESSION_KEY, $messages); |
| 62 | + } |
| 63 | +} |
0 commit comments