-
-
Notifications
You must be signed in to change notification settings - Fork 123
[Chat] Introduce DoctrineDbalMessageStore
#884
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+486
−0
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the Symfony package. | ||
| * | ||
| * (c) Fabien Potencier <fabien@symfony.com> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| use Doctrine\DBAL\DriverManager; | ||
| use Symfony\AI\Agent\Agent; | ||
| use Symfony\AI\Chat\Bridge\Doctrine\DoctrineDbalMessageStore; | ||
| use Symfony\AI\Chat\Chat; | ||
| use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory; | ||
| use Symfony\AI\Platform\Message\Message; | ||
| use Symfony\AI\Platform\Message\MessageBag; | ||
|
|
||
| require_once dirname(__DIR__).'/bootstrap.php'; | ||
|
|
||
| $platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client()); | ||
|
|
||
| $connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]); | ||
|
|
||
| $store = new DoctrineDbalMessageStore('symfony', $connection); | ||
| $store->setup(); | ||
|
|
||
| $agent = new Agent($platform, 'gpt-4o-mini'); | ||
| $chat = new Chat($agent, $store); | ||
|
|
||
| $messages = new MessageBag( | ||
| Message::forSystem('You are a helpful assistant. You only answer with short sentences.'), | ||
| ); | ||
|
|
||
| $chat->initiate($messages); | ||
| $chat->submit(Message::ofUser('My name is Christopher.')); | ||
| $message = $chat->submit(Message::ofUser('What is my name?')); | ||
|
|
||
| echo $message->getContent().\PHP_EOL; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
src/chat/src/Bridge/Doctrine/DoctrineDbalMessageStore.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the Symfony package. | ||
| * | ||
| * (c) Fabien Potencier <fabien@symfony.com> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Symfony\AI\Chat\Bridge\Doctrine; | ||
|
|
||
| use Doctrine\DBAL\Connection; | ||
| use Doctrine\DBAL\Connection as DBALConnection; | ||
| use Doctrine\DBAL\Platforms\OraclePlatform; | ||
| use Doctrine\DBAL\Result; | ||
| use Doctrine\DBAL\Schema\Name\Identifier; | ||
| use Doctrine\DBAL\Schema\Name\UnqualifiedName; | ||
| use Doctrine\DBAL\Schema\PrimaryKeyConstraint; | ||
| use Doctrine\DBAL\Schema\Schema; | ||
| use Doctrine\DBAL\Types\Types; | ||
| use Symfony\AI\Chat\Exception\InvalidArgumentException; | ||
| use Symfony\AI\Chat\ManagedStoreInterface; | ||
| use Symfony\AI\Chat\MessageNormalizer; | ||
| use Symfony\AI\Chat\MessageStoreInterface; | ||
| use Symfony\AI\Platform\Message\MessageBag; | ||
| use Symfony\AI\Platform\Message\MessageInterface; | ||
| use Symfony\Component\Serializer\Encoder\JsonEncoder; | ||
| use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; | ||
| use Symfony\Component\Serializer\Serializer; | ||
| use Symfony\Component\Serializer\SerializerInterface; | ||
|
|
||
| /** | ||
| * @author Guillaume Loulier <personal@guillaumeloulier.fr> | ||
| */ | ||
| final class DoctrineDbalMessageStore implements ManagedStoreInterface, MessageStoreInterface | ||
| { | ||
| public function __construct( | ||
| private readonly string $tableName, | ||
| private readonly DBALConnection $dbalConnection, | ||
| private readonly SerializerInterface $serializer = new Serializer([ | ||
| new ArrayDenormalizer(), | ||
| new MessageNormalizer(), | ||
| ], [new JsonEncoder()]), | ||
| ) { | ||
| } | ||
|
|
||
| public function setup(array $options = []): void | ||
| { | ||
| if ([] !== $options) { | ||
| throw new InvalidArgumentException('No supported options.'); | ||
| } | ||
|
|
||
| $schema = $this->dbalConnection->createSchemaManager()->introspectSchema(); | ||
|
|
||
| if ($schema->hasTable($this->tableName)) { | ||
| return; | ||
| } | ||
|
|
||
| $this->addTableToSchema($schema); | ||
| } | ||
|
|
||
| public function drop(): void | ||
| { | ||
| $schema = $this->dbalConnection->createSchemaManager()->introspectSchema(); | ||
|
|
||
| if (!$schema->hasTable($this->tableName)) { | ||
| return; | ||
| } | ||
|
|
||
| $queryBuilder = $this->dbalConnection->createQueryBuilder() | ||
| ->delete($this->tableName); | ||
|
|
||
| $this->dbalConnection->transactional(fn (Connection $connection): Result => $connection->executeQuery( | ||
| $queryBuilder->getSQL(), | ||
| )); | ||
| } | ||
|
|
||
| public function save(MessageBag $messages): void | ||
| { | ||
| $queryBuilder = $this->dbalConnection->createQueryBuilder() | ||
| ->insert($this->tableName) | ||
| ->values([ | ||
| 'messages' => '?', | ||
| ]); | ||
|
|
||
| $this->dbalConnection->transactional(fn (Connection $connection): Result => $connection->executeQuery( | ||
| $queryBuilder->getSQL(), | ||
| [ | ||
| $this->serializer->serialize($messages->getMessages(), 'json'), | ||
| ], | ||
| $queryBuilder->getParameterTypes(), | ||
| )); | ||
| } | ||
|
|
||
| public function load(): MessageBag | ||
| { | ||
| $queryBuilder = $this->dbalConnection->createQueryBuilder() | ||
| ->select('messages') | ||
| ->from($this->tableName) | ||
| ; | ||
|
|
||
| $result = $this->dbalConnection->transactional(static fn (Connection $connection): Result => $connection->executeQuery( | ||
| $queryBuilder->getSQL(), | ||
| )); | ||
|
|
||
| $messages = array_map( | ||
| fn (array $payload): array => $this->serializer->deserialize($payload['messages'], MessageInterface::class.'[]', 'json'), | ||
| $result->fetchAllAssociative(), | ||
| ); | ||
|
|
||
| return new MessageBag(...array_merge(...$messages)); | ||
| } | ||
|
|
||
| private function addTableToSchema(Schema $schema): void | ||
| { | ||
| $table = $schema->createTable($this->tableName); | ||
| $table->addOption('_symfony_ai_chat_table_name', $this->tableName); | ||
| $idColumn = $table->addColumn('id', Types::BIGINT) | ||
| ->setAutoincrement(true) | ||
| ->setNotnull(true); | ||
| $table->addColumn('messages', Types::TEXT) | ||
| ->setNotnull(true); | ||
| if (class_exists(PrimaryKeyConstraint::class)) { | ||
| $table->addPrimaryKeyConstraint(new PrimaryKeyConstraint(null, [ | ||
| new UnqualifiedName(Identifier::unquoted('id')), | ||
| ], true)); | ||
| } else { | ||
| $table->setPrimaryKey(['id']); | ||
| } | ||
|
|
||
| // We need to create a sequence for Oracle and set the id column to get the correct nextval | ||
| if ($this->dbalConnection->getDatabasePlatform() instanceof OraclePlatform) { | ||
| $serverVersion = $this->dbalConnection->executeQuery("SELECT version FROM product_component_version WHERE product LIKE 'Oracle Database%'")->fetchOne(); | ||
| if (version_compare($serverVersion, '12.1.0', '>=')) { | ||
| $idColumn->setAutoincrement(false); // disable the creation of SEQUENCE and TRIGGER | ||
| $idColumn->setDefault($this->tableName.'_seq.nextval'); | ||
|
|
||
| $schema->createSequence($this->tableName.'_seq'); | ||
| } | ||
| } | ||
|
|
||
| foreach ($schema->toSql($this->dbalConnection->getDatabasePlatform()) as $sql) { | ||
| $this->dbalConnection->executeQuery($sql); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.