|
| 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\Postgres; |
| 13 | + |
| 14 | +use Doctrine\DBAL\Connection; |
| 15 | +use Symfony\AI\Platform\Vector\Vector; |
| 16 | +use Symfony\AI\Platform\Vector\VectorInterface; |
| 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 PostgreSQL with pgvector extension. |
| 26 | + * |
| 27 | + * @author Simon André <[email protected]> |
| 28 | + * |
| 29 | + * @see https://github.com/pgvector/pgvector |
| 30 | + */ |
| 31 | +final readonly class Store implements VectorStoreInterface, InitializableStoreInterface |
| 32 | +{ |
| 33 | + public function __construct( |
| 34 | + private \PDO $connection, |
| 35 | + private string $tableName, |
| 36 | + private string $vectorFieldName = 'embedding', |
| 37 | + ) { |
| 38 | + } |
| 39 | + |
| 40 | + public static function fromPdo(\PDO $connection, string $tableName, string $vectorFieldName = 'embedding'): self |
| 41 | + { |
| 42 | + return new self($connection, $tableName, $vectorFieldName); |
| 43 | + } |
| 44 | + |
| 45 | + public static function fromDbal(Connection $connection, string $tableName, string $vectorFieldName = 'embedding'): self |
| 46 | + { |
| 47 | + $pdo = $connection->getNativeConnection(); |
| 48 | + |
| 49 | + if (!$pdo instanceof \PDO) { |
| 50 | + throw new InvalidArgumentException('Only DBAL connections using PDO driver are supported.'); |
| 51 | + } |
| 52 | + |
| 53 | + return self::fromPdo($pdo, $tableName, $vectorFieldName); |
| 54 | + } |
| 55 | + |
| 56 | + public function add(VectorDocument ...$documents): void |
| 57 | + { |
| 58 | + $statement = $this->connection->prepare( |
| 59 | + \sprintf( |
| 60 | + 'INSERT INTO %1$s (id, metadata, %2$s) |
| 61 | + VALUES (:id, :metadata, :vector) |
| 62 | + ON CONFLICT (id) DO UPDATE SET metadata = EXCLUDED.metadata, %2$s = EXCLUDED.%2$s', |
| 63 | + $this->tableName, |
| 64 | + $this->vectorFieldName, |
| 65 | + ), |
| 66 | + ); |
| 67 | + |
| 68 | + foreach ($documents as $document) { |
| 69 | + $operation = [ |
| 70 | + 'id' => $document->id->toRfc4122(), |
| 71 | + 'metadata' => json_encode($document->metadata->getArrayCopy(), \JSON_THROW_ON_ERROR), |
| 72 | + 'vector' => $this->toPgvector($document->vector), |
| 73 | + ]; |
| 74 | + |
| 75 | + $statement->execute($operation); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * @param array<string, mixed> $options |
| 81 | + * @param float|null $minScore Minimum score to filter results (optional) |
| 82 | + * |
| 83 | + * @return VectorDocument[] |
| 84 | + */ |
| 85 | + public function query(Vector $vector, array $options = [], ?float $minScore = null): array |
| 86 | + { |
| 87 | + $sql = \sprintf( |
| 88 | + 'SELECT id, %s AS embedding, metadata, (%s <-> :embedding) AS score |
| 89 | + FROM %s |
| 90 | + %s |
| 91 | + ORDER BY score ASC |
| 92 | + LIMIT %d', |
| 93 | + $this->vectorFieldName, |
| 94 | + $this->vectorFieldName, |
| 95 | + $this->tableName, |
| 96 | + null !== $minScore ? "WHERE ({$this->vectorFieldName} <-> :embedding) >= :minScore" : '', |
| 97 | + $options['limit'] ?? 5, |
| 98 | + ); |
| 99 | + $statement = $this->connection->prepare($sql); |
| 100 | + |
| 101 | + $params = [ |
| 102 | + 'embedding' => $this->toPgvector($vector), |
| 103 | + ]; |
| 104 | + if (null !== $minScore) { |
| 105 | + $params['minScore'] = $minScore; |
| 106 | + } |
| 107 | + |
| 108 | + $statement->execute($params); |
| 109 | + |
| 110 | + $documents = []; |
| 111 | + foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $result) { |
| 112 | + $documents[] = new VectorDocument( |
| 113 | + id: Uuid::fromString($result['id']), |
| 114 | + vector: new Vector($this->fromPgvector($result['embedding'])), |
| 115 | + metadata: new Metadata(json_decode($result['metadata'] ?? '{}', true, 512, \JSON_THROW_ON_ERROR)), |
| 116 | + score: $result['score'], |
| 117 | + ); |
| 118 | + } |
| 119 | + |
| 120 | + return $documents; |
| 121 | + } |
| 122 | + |
| 123 | + public function initialize(array $options = []): void |
| 124 | + { |
| 125 | + if ([] !== $options) { |
| 126 | + throw new InvalidArgumentException('No supported options'); |
| 127 | + } |
| 128 | + |
| 129 | + $this->connection->exec('CREATE EXTENSION IF NOT EXISTS vector'); |
| 130 | + |
| 131 | + $this->connection->exec( |
| 132 | + \sprintf( |
| 133 | + 'CREATE TABLE IF NOT EXISTS %s ( |
| 134 | + id UUID PRIMARY KEY, |
| 135 | + metadata JSONB, |
| 136 | + %s vector(1536) NOT NULL |
| 137 | + )', |
| 138 | + $this->tableName, |
| 139 | + $this->vectorFieldName, |
| 140 | + ), |
| 141 | + ); |
| 142 | + $this->connection->exec( |
| 143 | + \sprintf( |
| 144 | + 'CREATE INDEX IF NOT EXISTS %s_%s_idx ON %s USING ivfflat (%s vector_cosine_ops)', |
| 145 | + $this->tableName, |
| 146 | + $this->vectorFieldName, |
| 147 | + $this->tableName, |
| 148 | + $this->vectorFieldName, |
| 149 | + ), |
| 150 | + ); |
| 151 | + } |
| 152 | + |
| 153 | + private function toPgvector(VectorInterface $vector): string |
| 154 | + { |
| 155 | + return '['.implode(',', $vector->getData()).']'; |
| 156 | + } |
| 157 | + |
| 158 | + private function fromPgvector(string $vector): array |
| 159 | + { |
| 160 | + return json_decode($vector, true, 512, \JSON_THROW_ON_ERROR); |
| 161 | + } |
| 162 | +} |
0 commit comments