|
| 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\Redis; |
| 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 | + |
| 23 | +/** |
| 24 | + * @author Grégoire Pineau <[email protected]> |
| 25 | + */ |
| 26 | +class Store implements VectorStoreInterface, InitializableStoreInterface |
| 27 | +{ |
| 28 | + public function __construct( |
| 29 | + private readonly \Redis $redis, |
| 30 | + private readonly string $indexName, |
| 31 | + private readonly string $keyPrefix = 'vector:', |
| 32 | + private readonly Distance $distance = Distance::Cosine, |
| 33 | + ) { |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param array{vector_size?: positive-int, index_method?: string, extra_schema?: list<string>} $options |
| 38 | + * |
| 39 | + * - For Mistral: ['vector_size' => 1024] |
| 40 | + * - For OpenAI: ['vector_size' => 1536] |
| 41 | + * - For Gemini: ['vector_size' => 3072] (default) |
| 42 | + * - For other models: adjust vector_size accordingly |
| 43 | + */ |
| 44 | + public function initialize(array $options = []): void |
| 45 | + { |
| 46 | + $vectorSize = $options['vector_size'] ?? 3072; |
| 47 | + $indexMethod = $options['index_method'] ?? 'FLAT'; // Or 'HNSW' for approximate search |
| 48 | + $distanceMetric = $this->distance->getRedisMetric(); |
| 49 | + $extraSchema = $options['extra_schema'] ?? []; |
| 50 | + |
| 51 | + // Create the index with vector field for JSON documents |
| 52 | + try { |
| 53 | + $this->redis->rawCommand( |
| 54 | + 'FT.CREATE', $this->indexName, 'ON', 'JSON', |
| 55 | + 'PREFIX', '1', $this->keyPrefix, |
| 56 | + 'SCHEMA', |
| 57 | + '$.id', 'AS', 'id', 'TEXT', |
| 58 | + // '$.metadata', 'AS', 'metadata', 'TEXT', |
| 59 | + '$.embedding', 'AS', 'embedding', 'VECTOR', $indexMethod, '6', 'TYPE', 'FLOAT32', 'DIM', $vectorSize, 'DISTANCE_METRIC', $distanceMetric, |
| 60 | + ...$extraSchema, |
| 61 | + ); |
| 62 | + } catch (\RedisException $e) { |
| 63 | + // Index might already exist, check if it's a "already exists" error |
| 64 | + if (!str_contains($e->getMessage(), 'Index already exists')) { |
| 65 | + throw new RuntimeException(\sprintf('Failed to create Redis index: "%s".', $e->getMessage()), 0, $e); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + public function add(VectorDocument ...$documents): void |
| 71 | + { |
| 72 | + $pipeline = $this->redis->multi(\Redis::PIPELINE); |
| 73 | + |
| 74 | + foreach ($documents as $document) { |
| 75 | + $key = $this->keyPrefix.$document->id->toRfc4122(); |
| 76 | + $data = [ |
| 77 | + 'id' => $document->id->toRfc4122(), |
| 78 | + 'metadata' => $document->metadata->getArrayCopy(), |
| 79 | + 'embedding' => $document->vector->getData(), |
| 80 | + ]; |
| 81 | + |
| 82 | + $pipeline->rawCommand('JSON.SET', $key, '$', json_encode($data, \JSON_THROW_ON_ERROR)); |
| 83 | + } |
| 84 | + |
| 85 | + $pipeline->exec(); |
| 86 | + } |
| 87 | + |
| 88 | + /** |
| 89 | + * @param array<string, mixed> $options |
| 90 | + * |
| 91 | + * @return VectorDocument[] |
| 92 | + */ |
| 93 | + public function query(Vector $vector, array $options = []): array |
| 94 | + { |
| 95 | + $limit = $options['limit'] ?? 5; |
| 96 | + $maxScore = $options['maxScore'] ?? null; |
| 97 | + $whereFilter = $options['where'] ?? '*'; |
| 98 | + |
| 99 | + $query = "({$whereFilter}) => [KNN {$limit} @embedding \$query_vector AS vector_score]"; |
| 100 | + |
| 101 | + try { |
| 102 | + $results = $this->redis->rawCommand( |
| 103 | + 'FT.SEARCH', |
| 104 | + $this->indexName, |
| 105 | + $query, |
| 106 | + 'PARAMS', 2, 'query_vector', $this->toRedisVector($vector), |
| 107 | + 'RETURN', 4, '$.id', '$.metadata', '$.embedding', 'vector_score', |
| 108 | + 'SORTBY', 'vector_score', 'ASC', |
| 109 | + 'LIMIT', 0, $limit, |
| 110 | + 'DIALECT', 2 |
| 111 | + ); |
| 112 | + } catch (\RedisException $e) { |
| 113 | + throw new RuntimeException(\sprintf('Failed to execute query: "%s".', $e->getMessage()), 0, $e); |
| 114 | + } |
| 115 | + |
| 116 | + if (!\is_array($results) || \count($results) < 2) { |
| 117 | + return []; |
| 118 | + } |
| 119 | + |
| 120 | + $documents = []; |
| 121 | + $numResults = $results[0]; |
| 122 | + |
| 123 | + // Parse results (skip first element which is the count) |
| 124 | + for ($i = 1; $i <= $numResults; $i += 2) { |
| 125 | + // $docKey = $results[$i]; |
| 126 | + $docData = $results[$i + 1]; |
| 127 | + |
| 128 | + // Convert flat array to associative array |
| 129 | + $data = []; |
| 130 | + for ($j = 0; $j < \count($docData); $j += 2) { |
| 131 | + $fieldName = $docData[$j]; |
| 132 | + $fieldValue = $docData[$j + 1] ?? null; |
| 133 | + |
| 134 | + if (\is_string($fieldValue) && json_validate($fieldValue)) { |
| 135 | + $fieldValue = json_decode($fieldValue, true); |
| 136 | + } |
| 137 | + |
| 138 | + $data[$fieldName] = $fieldValue; |
| 139 | + } |
| 140 | + |
| 141 | + if (!isset($data['$.id'], $data['vector_score'])) { |
| 142 | + continue; |
| 143 | + } |
| 144 | + |
| 145 | + $score = (float) $data['vector_score']; |
| 146 | + |
| 147 | + // Apply max score filter if specified |
| 148 | + if (null !== $maxScore && $score > $maxScore) { |
| 149 | + continue; |
| 150 | + } |
| 151 | + |
| 152 | + $documents[] = new VectorDocument( |
| 153 | + id: Uuid::fromString($data['$.id']), |
| 154 | + vector: new Vector($data['$.embedding'] ?? []), |
| 155 | + metadata: new Metadata($data['$.metadata'] ?? []), |
| 156 | + score: $score, |
| 157 | + ); |
| 158 | + } |
| 159 | + |
| 160 | + return $documents; |
| 161 | + } |
| 162 | + |
| 163 | + private function toRedisVector(VectorInterface $vector): string |
| 164 | + { |
| 165 | + $data = $vector->getData(); |
| 166 | + $bytes = ''; |
| 167 | + foreach ($data as $value) { |
| 168 | + $bytes .= pack('f', $value); |
| 169 | + } |
| 170 | + |
| 171 | + return $bytes; |
| 172 | + } |
| 173 | +} |
0 commit comments