|
| 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\SurrealDB; |
| 13 | + |
| 14 | +use Symfony\AI\Platform\Vector\NullVector; |
| 15 | +use Symfony\AI\Platform\Vector\Vector; |
| 16 | +use Symfony\AI\Store\Document\Metadata; |
| 17 | +use Symfony\AI\Store\Document\VectorDocument; |
| 18 | +use Symfony\AI\Store\Exception\InvalidArgumentException; |
| 19 | +use Symfony\AI\Store\Exception\RuntimeException; |
| 20 | +use Symfony\AI\Store\InitializableStoreInterface; |
| 21 | +use Symfony\AI\Store\VectorStoreInterface; |
| 22 | +use Symfony\Component\Uid\Uuid; |
| 23 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 24 | + |
| 25 | +/** |
| 26 | + * @author Guillaume Loulier <[email protected]> |
| 27 | + */ |
| 28 | +final class Store implements InitializableStoreInterface, VectorStoreInterface |
| 29 | +{ |
| 30 | + private string $authenticationToken = ''; |
| 31 | + |
| 32 | + public function __construct( |
| 33 | + private readonly HttpClientInterface $httpClient, |
| 34 | + private readonly string $endpointUrl, |
| 35 | + #[\SensitiveParameter] private readonly string $user, |
| 36 | + #[\SensitiveParameter] private readonly string $password, |
| 37 | + #[\SensitiveParameter] private readonly string $namespace, |
| 38 | + #[\SensitiveParameter] private readonly string $database, |
| 39 | + private readonly string $table = 'vectors', |
| 40 | + private readonly string $vectorFieldName = '_vectors', |
| 41 | + private readonly string $strategy = 'cosine', |
| 42 | + private readonly int $embeddingsDimension = 1536, |
| 43 | + private readonly bool $isNamespacedUser = false, |
| 44 | + ) { |
| 45 | + } |
| 46 | + |
| 47 | + public function add(VectorDocument ...$documents): void |
| 48 | + { |
| 49 | + foreach ($documents as $document) { |
| 50 | + $this->request('POST', \sprintf('key/%s', $this->table), $this->convertToIndexableArray($document)); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public function query(Vector $vector, array $options = [], ?float $minScore = null): array |
| 55 | + { |
| 56 | + $vectors = json_encode($vector->getData()); |
| 57 | + |
| 58 | + $results = $this->request('POST', 'sql', \sprintf( |
| 59 | + 'SELECT id, %s, _metadata, vector::similarity::%s(%s, %s) AS distance FROM %s WHERE %s <|2|> %s;', |
| 60 | + $this->vectorFieldName, $this->strategy, $this->vectorFieldName, $vectors, $this->table, $this->vectorFieldName, $vectors, |
| 61 | + )); |
| 62 | + |
| 63 | + return array_map($this->convertToVectorDocument(...), $results[0]['result']); |
| 64 | + } |
| 65 | + |
| 66 | + public function initialize(array $options = []): void |
| 67 | + { |
| 68 | + $this->authenticate(); |
| 69 | + |
| 70 | + $this->request('POST', 'sql', \sprintf( |
| 71 | + 'DEFINE INDEX %s_vectors ON %s FIELDS %s MTREE DIMENSION %d DIST %s TYPE F32', |
| 72 | + $this->table, $this->table, $this->vectorFieldName, $this->embeddingsDimension, $this->strategy |
| 73 | + )); |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * @param array<string, mixed>|string $payload |
| 78 | + * |
| 79 | + * @return array<string|int, mixed> |
| 80 | + */ |
| 81 | + private function request(string $method, string $endpoint, array|string $payload): array |
| 82 | + { |
| 83 | + $url = \sprintf('%s/%s', $this->endpointUrl, $endpoint); |
| 84 | + |
| 85 | + $finalPayload = [ |
| 86 | + 'json' => $payload, |
| 87 | + ]; |
| 88 | + |
| 89 | + if (\is_string($payload)) { |
| 90 | + $finalPayload = [ |
| 91 | + 'body' => $payload, |
| 92 | + ]; |
| 93 | + } |
| 94 | + |
| 95 | + $response = $this->httpClient->request($method, $url, array_merge($finalPayload, [ |
| 96 | + 'headers' => [ |
| 97 | + 'Accept' => 'application/json', |
| 98 | + 'Content-Type' => 'application/json', |
| 99 | + 'Surreal-NS' => $this->namespace, |
| 100 | + 'Surreal-DB' => $this->database, |
| 101 | + 'Authorization' => \sprintf('Bearer %s', $this->authenticationToken), |
| 102 | + ], |
| 103 | + ])); |
| 104 | + |
| 105 | + return $response->toArray(); |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * @return array<string, mixed> |
| 110 | + */ |
| 111 | + private function convertToIndexableArray(VectorDocument $document): array |
| 112 | + { |
| 113 | + return [ |
| 114 | + 'id' => $document->id->toRfc4122(), |
| 115 | + $this->vectorFieldName => $document->vector->getData(), |
| 116 | + '_metadata' => array_merge($document->metadata->getArrayCopy(), [ |
| 117 | + '_id' => $document->id->toRfc4122(), |
| 118 | + ]), |
| 119 | + ]; |
| 120 | + } |
| 121 | + |
| 122 | + /** |
| 123 | + * @param array<string, mixed> $data |
| 124 | + */ |
| 125 | + private function convertToVectorDocument(array $data): VectorDocument |
| 126 | + { |
| 127 | + $id = $data['_metadata']['_id'] ?? throw new InvalidArgumentException('Missing "id" field in the document data'); |
| 128 | + |
| 129 | + $vector = !\array_key_exists($this->vectorFieldName, $data) || null === $data[$this->vectorFieldName] |
| 130 | + ? new NullVector() |
| 131 | + : new Vector($data[$this->vectorFieldName]); |
| 132 | + |
| 133 | + unset($data['_metadata']['_id']); |
| 134 | + |
| 135 | + return new VectorDocument( |
| 136 | + id: Uuid::fromString($id), |
| 137 | + vector: $vector, |
| 138 | + metadata: new Metadata($data['_metadata']), |
| 139 | + ); |
| 140 | + } |
| 141 | + |
| 142 | + private function authenticate(): void |
| 143 | + { |
| 144 | + if ('' !== $this->authenticationToken) { |
| 145 | + return; |
| 146 | + } |
| 147 | + |
| 148 | + $authenticationPayload = [ |
| 149 | + 'user' => $this->user, |
| 150 | + 'pass' => $this->password, |
| 151 | + ]; |
| 152 | + |
| 153 | + if ($this->isNamespacedUser) { |
| 154 | + $authenticationPayload['ns'] = $this->namespace; |
| 155 | + $authenticationPayload['db'] = $this->database; |
| 156 | + } |
| 157 | + |
| 158 | + $authenticationResponse = $this->httpClient->request('POST', \sprintf('%s/signin', $this->endpointUrl), [ |
| 159 | + 'headers' => [ |
| 160 | + 'Accept' => 'application/json', |
| 161 | + ], |
| 162 | + 'json' => $authenticationPayload, |
| 163 | + ]); |
| 164 | + |
| 165 | + $payload = $authenticationResponse->toArray(); |
| 166 | + |
| 167 | + if (!\array_key_exists('token', $payload)) { |
| 168 | + throw new RuntimeException('The SurrealDB authentication response does not contain a token.'); |
| 169 | + } |
| 170 | + |
| 171 | + $this->authenticationToken = $payload['token']; |
| 172 | + } |
| 173 | +} |
0 commit comments