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