|
| 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\ClickHouse; |
| 13 | + |
| 14 | +use Symfony\AI\Platform\Vector\Vector; |
| 15 | +use Symfony\AI\Platform\Vector\VectorInterface; |
| 16 | +use Symfony\AI\Store\Document\Metadata; |
| 17 | +use Symfony\AI\Store\Document\VectorDocument; |
| 18 | +use Symfony\AI\Store\Exception\RuntimeException; |
| 19 | +use Symfony\AI\Store\InitializableStoreInterface; |
| 20 | +use Symfony\AI\Store\VectorStoreInterface; |
| 21 | +use Symfony\Component\Uid\Uuid; |
| 22 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 23 | +use Symfony\Contracts\HttpClient\ResponseInterface; |
| 24 | + |
| 25 | +/** |
| 26 | + * @author Grégoire Pineau <[email protected]> |
| 27 | + */ |
| 28 | +class Store implements VectorStoreInterface, InitializableStoreInterface |
| 29 | +{ |
| 30 | + public function __construct( |
| 31 | + private readonly HttpClientInterface $httpClient, |
| 32 | + private readonly string $databaseName = 'default', |
| 33 | + private readonly string $tableName = 'embedding', |
| 34 | + ) { |
| 35 | + } |
| 36 | + |
| 37 | + public function initialize(array $options = []): void |
| 38 | + { |
| 39 | + $sql = <<<'SQL' |
| 40 | + CREATE TABLE IF NOT EXISTS {{ table }} ( |
| 41 | + id UUID, |
| 42 | + metadata String, |
| 43 | + embedding Array(Float32), |
| 44 | + ) ENGINE = MergeTree() |
| 45 | + ORDER BY id |
| 46 | + SQL; |
| 47 | + |
| 48 | + $this->execute('POST', $sql); |
| 49 | + } |
| 50 | + |
| 51 | + public function add(VectorDocument ...$documents): void |
| 52 | + { |
| 53 | + $rows = []; |
| 54 | + |
| 55 | + foreach ($documents as $document) { |
| 56 | + $rows[] = $this->formatVectorDocument($document); |
| 57 | + } |
| 58 | + |
| 59 | + $this->insertBatch($rows); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @return array<string, mixed> |
| 64 | + */ |
| 65 | + protected function formatVectorDocument(VectorDocument $document): array |
| 66 | + { |
| 67 | + return [ |
| 68 | + 'id' => $document->id->toRfc4122(), |
| 69 | + 'metadata' => json_encode($document->metadata->getArrayCopy(), \JSON_THROW_ON_ERROR), |
| 70 | + 'embedding' => $document->vector->getData(), |
| 71 | + ]; |
| 72 | + } |
| 73 | + |
| 74 | + public function query(Vector $vector, array $options = [], ?float $minScore = null): array |
| 75 | + { |
| 76 | + $sql = <<<'SQL' |
| 77 | + SELECT |
| 78 | + id, |
| 79 | + embedding, |
| 80 | + metadata, |
| 81 | + cosineDistance(embedding, {query_vector:Array(Float32)}) as score |
| 82 | + FROM {{ table }} |
| 83 | + WHERE length(embedding) = length({query_vector:Array(Float32)}) {{ where }} |
| 84 | + ORDER BY score ASC |
| 85 | + LIMIT {limit:UInt32} |
| 86 | + SQL; |
| 87 | + |
| 88 | + if (isset($options['where'])) { |
| 89 | + $sql = str_replace('{{ where }}', 'AND '.$options['where'], $sql); |
| 90 | + } else { |
| 91 | + $sql = str_replace('{{ where }}', '', $sql); |
| 92 | + } |
| 93 | + |
| 94 | + $results = $this |
| 95 | + ->execute('GET', $sql, [ |
| 96 | + 'query_vector' => $this->toClickHouseVector($vector), |
| 97 | + 'limit' => $options['limit'] ?? 5, |
| 98 | + ...$options['params'] ?? [], |
| 99 | + ]) |
| 100 | + ->toArray()['data'] |
| 101 | + ; |
| 102 | + |
| 103 | + $documents = []; |
| 104 | + foreach ($results as $result) { |
| 105 | + $documents[] = new VectorDocument( |
| 106 | + id: Uuid::fromString($result['id']), |
| 107 | + vector: new Vector($result['embedding']), |
| 108 | + metadata: new Metadata(json_decode($result['metadata'] ?? '{}', true, 512, \JSON_THROW_ON_ERROR)), |
| 109 | + score: $result['score'], |
| 110 | + ); |
| 111 | + } |
| 112 | + |
| 113 | + return $documents; |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * @param array<string, mixed> $params |
| 118 | + */ |
| 119 | + protected function execute(string $method, string $sql, array $params = []): ResponseInterface |
| 120 | + { |
| 121 | + $sql = str_replace('{{ table }}', $this->tableName, $sql); |
| 122 | + |
| 123 | + $options = [ |
| 124 | + 'query' => [ |
| 125 | + 'query' => $sql, |
| 126 | + 'database' => $this->databaseName, |
| 127 | + 'default_format' => 'JSON', |
| 128 | + ], |
| 129 | + ]; |
| 130 | + |
| 131 | + foreach ($params as $key => $value) { |
| 132 | + $options['query']['param_'.$key] = $value; |
| 133 | + } |
| 134 | + |
| 135 | + return $this->httpClient->request($method, '/', $options); |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * @param array<array<string, mixed>> $rows |
| 140 | + */ |
| 141 | + private function insertBatch(array $rows): void |
| 142 | + { |
| 143 | + if (!$rows) { |
| 144 | + return; |
| 145 | + } |
| 146 | + |
| 147 | + $sql = 'INSERT INTO {{ table }} FORMAT JSONEachRow'; |
| 148 | + $sql = str_replace('{{ table }}', $this->tableName, $sql); |
| 149 | + |
| 150 | + $jsonData = ''; |
| 151 | + foreach ($rows as $row) { |
| 152 | + $jsonData .= json_encode($row)."\n"; |
| 153 | + } |
| 154 | + |
| 155 | + $options = [ |
| 156 | + 'query' => [ |
| 157 | + 'query' => $sql, |
| 158 | + 'database' => $this->databaseName, |
| 159 | + ], |
| 160 | + 'body' => $jsonData, |
| 161 | + 'headers' => [ |
| 162 | + 'Content-Type' => 'application/json', |
| 163 | + ], |
| 164 | + ]; |
| 165 | + |
| 166 | + $response = $this->httpClient->request('POST', '/', $options); |
| 167 | + |
| 168 | + if (200 !== $response->getStatusCode()) { |
| 169 | + $content = $response->getContent(false); |
| 170 | + |
| 171 | + throw new RuntimeException("Could not insert data into ClickHouse. Http status code: {$response->getStatusCode()}. Response: {$content}."); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + private function toClickHouseVector(VectorInterface $vector): string |
| 176 | + { |
| 177 | + return '['.implode(',', $vector->getData()).']'; |
| 178 | + } |
| 179 | +} |
0 commit comments