|
| 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 Symfony\AI\Store\Bridge\MariaDB; |
| 13 | + |
| 14 | +use Doctrine\DBAL\Connection; |
| 15 | +use Doctrine\DBAL\Exception as DBALException; |
| 16 | +use Symfony\AI\Platform\Vector\Vector; |
| 17 | +use Symfony\AI\Store\Document\Metadata; |
| 18 | +use Symfony\AI\Store\Document\VectorDocument; |
| 19 | +use Symfony\AI\Store\Exception\InvalidArgumentException; |
| 20 | +use Symfony\AI\Store\InitializableStoreInterface; |
| 21 | +use Symfony\AI\Store\VectorStoreInterface; |
| 22 | +use Symfony\Component\Uid\Uuid; |
| 23 | + |
| 24 | +/** |
| 25 | + * Requires MariaDB >=11.7. |
| 26 | + * |
| 27 | + * @see https://mariadb.org/rag-with-mariadb-vector/ |
| 28 | + * |
| 29 | + * @author Valtteri R <[email protected]> |
| 30 | + */ |
| 31 | +final readonly class Store implements VectorStoreInterface, InitializableStoreInterface |
| 32 | +{ |
| 33 | + /** |
| 34 | + * @param string $tableName The name of the table |
| 35 | + * @param string $indexName The name of the vector search index |
| 36 | + * @param string $vectorFieldName The name of the field in the index that contains the vector |
| 37 | + */ |
| 38 | + public function __construct( |
| 39 | + private \PDO $connection, |
| 40 | + private string $tableName, |
| 41 | + private string $indexName, |
| 42 | + private string $vectorFieldName, |
| 43 | + ) { |
| 44 | + } |
| 45 | + |
| 46 | + public static function fromPdo(\PDO $connection, string $tableName, string $indexName = 'embedding', string $vectorFieldName = 'embedding'): self |
| 47 | + { |
| 48 | + return new self($connection, $tableName, $indexName, $vectorFieldName); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * @throws DBALException |
| 53 | + */ |
| 54 | + public static function fromDbal(Connection $connection, string $tableName, string $indexName = 'embedding', string $vectorFieldName = 'embedding'): self |
| 55 | + { |
| 56 | + $pdo = $connection->getNativeConnection(); |
| 57 | + |
| 58 | + if (!$pdo instanceof \PDO) { |
| 59 | + throw new InvalidArgumentException('Only DBAL connections using PDO driver are supported.'); |
| 60 | + } |
| 61 | + |
| 62 | + return self::fromPdo($pdo, $tableName, $indexName, $vectorFieldName); |
| 63 | + } |
| 64 | + |
| 65 | + public function add(VectorDocument ...$documents): void |
| 66 | + { |
| 67 | + $statement = $this->connection->prepare( |
| 68 | + \sprintf( |
| 69 | + <<<'SQL' |
| 70 | + INSERT INTO %1$s (id, metadata, %2$s) |
| 71 | + VALUES (:id, :metadata, VEC_FromText(:vector)) |
| 72 | + ON DUPLICATE KEY UPDATE metadata = :metadata, %2$s = VEC_FromText(:vector) |
| 73 | + SQL, |
| 74 | + $this->tableName, |
| 75 | + $this->vectorFieldName, |
| 76 | + ), |
| 77 | + ); |
| 78 | + |
| 79 | + foreach ($documents as $document) { |
| 80 | + $operation = [ |
| 81 | + 'id' => $document->id->toBinary(), |
| 82 | + 'metadata' => json_encode($document->metadata->getArrayCopy()), |
| 83 | + 'vector' => json_encode($document->vector->getData()), |
| 84 | + ]; |
| 85 | + |
| 86 | + $statement->execute($operation); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * @param array{ |
| 92 | + * limit?: positive-int, |
| 93 | + * } $options |
| 94 | + */ |
| 95 | + public function query(Vector $vector, array $options = [], ?float $minScore = null): array |
| 96 | + { |
| 97 | + $statement = $this->connection->prepare( |
| 98 | + \sprintf( |
| 99 | + <<<'SQL' |
| 100 | + SELECT id, VEC_ToText(%1$s) embedding, metadata, VEC_DISTANCE_EUCLIDEAN(%1$s, VEC_FromText(:embedding)) AS score |
| 101 | + FROM %2$s |
| 102 | + %3$s |
| 103 | + ORDER BY score ASC |
| 104 | + LIMIT %4$d |
| 105 | + SQL, |
| 106 | + $this->vectorFieldName, |
| 107 | + $this->tableName, |
| 108 | + null !== $minScore ? 'WHERE VEC_DISTANCE_EUCLIDEAN(%1$s, VEC_FromText(:embedding)) >= :minScore' : '', |
| 109 | + $options['limit'] ?? 5, |
| 110 | + ), |
| 111 | + ); |
| 112 | + |
| 113 | + $params = ['embedding' => json_encode($vector->getData())]; |
| 114 | + |
| 115 | + if (null !== $minScore) { |
| 116 | + $params['minScore'] = $minScore; |
| 117 | + } |
| 118 | + |
| 119 | + $documents = []; |
| 120 | + |
| 121 | + $statement->execute($params); |
| 122 | + |
| 123 | + foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $result) { |
| 124 | + $documents[] = new VectorDocument( |
| 125 | + id: Uuid::fromBinary($result['id']), |
| 126 | + vector: new Vector(json_decode((string) $result['embedding'], true)), |
| 127 | + metadata: new Metadata(json_decode($result['metadata'] ?? '{}', true)), |
| 128 | + score: $result['score'], |
| 129 | + ); |
| 130 | + } |
| 131 | + |
| 132 | + return $documents; |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * @param array{} $options |
| 137 | + */ |
| 138 | + public function initialize(array $options = []): void |
| 139 | + { |
| 140 | + if ([] !== $options) { |
| 141 | + throw new InvalidArgumentException('No supported options'); |
| 142 | + } |
| 143 | + |
| 144 | + $serverVersion = $this->connection->getAttribute(\PDO::ATTR_SERVER_VERSION); |
| 145 | + |
| 146 | + if (!str_contains((string) $serverVersion, 'MariaDB') || version_compare($serverVersion, '11.7.0') < 0) { |
| 147 | + throw new InvalidArgumentException('You need MariaDB >=11.7 to use this feature'); |
| 148 | + } |
| 149 | + |
| 150 | + $this->connection->exec( |
| 151 | + \sprintf( |
| 152 | + <<<'SQL' |
| 153 | + CREATE TABLE IF NOT EXISTS %1$s ( |
| 154 | + id BINARY(16) NOT NULL PRIMARY KEY, |
| 155 | + metadata JSON, |
| 156 | + %2$s VECTOR(1536) NOT NULL, |
| 157 | + VECTOR INDEX %3$s (%2$s) |
| 158 | + ) |
| 159 | + SQL, |
| 160 | + $this->tableName, |
| 161 | + $this->vectorFieldName, |
| 162 | + $this->indexName, |
| 163 | + ), |
| 164 | + ); |
| 165 | + } |
| 166 | +} |
0 commit comments