-
-
Notifications
You must be signed in to change notification settings - Fork 50
[Store] Add support for Redis #269
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lyrixx
wants to merge
1
commit into
symfony:main
Choose a base branch
from
lyrixx:store-redis
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+780
−1
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\AI\Store\Bridge\Redis; | ||
|
||
use OskarStark\Enum\Trait\Comparable; | ||
|
||
/** | ||
* @author Grégoire Pineau <[email protected]> | ||
*/ | ||
enum Distance: string | ||
{ | ||
use Comparable; | ||
|
||
case Cosine = 'COSINE'; | ||
case L2 = 'L2'; | ||
case Ip = 'IP'; | ||
|
||
public function getRedisMetric(): string | ||
{ | ||
return $this->value; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\AI\Store\Bridge\Redis; | ||
|
||
use Symfony\AI\Platform\Vector\Vector; | ||
use Symfony\AI\Platform\Vector\VectorInterface; | ||
use Symfony\AI\Store\Document\Metadata; | ||
use Symfony\AI\Store\Document\VectorDocument; | ||
use Symfony\AI\Store\Exception\RuntimeException; | ||
use Symfony\AI\Store\InitializableStoreInterface; | ||
use Symfony\AI\Store\VectorStoreInterface; | ||
use Symfony\Component\Uid\Uuid; | ||
|
||
/** | ||
* @author Grégoire Pineau <[email protected]> | ||
*/ | ||
class Store implements VectorStoreInterface, InitializableStoreInterface | ||
{ | ||
public function __construct( | ||
private readonly \Redis $redis, | ||
private readonly string $indexName, | ||
private readonly string $keyPrefix = 'vector:', | ||
private readonly Distance $distance = Distance::Cosine, | ||
) { | ||
} | ||
|
||
/** | ||
* @param array{vector_size?: positive-int, index_method?: string, extra_schema?: list<string>} $options | ||
* | ||
* - For Mistral: ['vector_size' => 1024] | ||
* - For OpenAI: ['vector_size' => 1536] | ||
* - For Gemini: ['vector_size' => 3072] (default) | ||
* - For other models: adjust vector_size accordingly | ||
*/ | ||
public function initialize(array $options = []): void | ||
{ | ||
$vectorSize = $options['vector_size'] ?? 3072; | ||
$indexMethod = $options['index_method'] ?? 'FLAT'; // Or 'HNSW' for approximate search | ||
$distanceMetric = $this->distance->getRedisMetric(); | ||
$extraSchema = $options['extra_schema'] ?? []; | ||
|
||
// Create the index with vector field for JSON documents | ||
try { | ||
$this->redis->rawCommand( | ||
'FT.CREATE', $this->indexName, 'ON', 'JSON', | ||
'PREFIX', '1', $this->keyPrefix, | ||
'SCHEMA', | ||
'$.id', 'AS', 'id', 'TEXT', | ||
// '$.metadata', 'AS', 'metadata', 'TEXT', | ||
'$.embedding', 'AS', 'embedding', 'VECTOR', $indexMethod, '6', 'TYPE', 'FLOAT32', 'DIM', $vectorSize, 'DISTANCE_METRIC', $distanceMetric, | ||
...$extraSchema, | ||
); | ||
} catch (\RedisException $e) { | ||
// Index might already exist, check if it's a "already exists" error | ||
if (!str_contains($e->getMessage(), 'Index already exists')) { | ||
throw new RuntimeException(\sprintf('Failed to create Redis index: "%s".', $e->getMessage()), 0, $e); | ||
} | ||
} | ||
} | ||
|
||
public function add(VectorDocument ...$documents): void | ||
{ | ||
$pipeline = $this->redis->multi(\Redis::PIPELINE); | ||
|
||
foreach ($documents as $document) { | ||
$key = $this->keyPrefix.$document->id->toRfc4122(); | ||
$data = [ | ||
'id' => $document->id->toRfc4122(), | ||
'metadata' => $document->metadata->getArrayCopy(), | ||
'embedding' => $document->vector->getData(), | ||
]; | ||
|
||
$pipeline->rawCommand('JSON.SET', $key, '$', json_encode($data, \JSON_THROW_ON_ERROR)); | ||
} | ||
|
||
$pipeline->exec(); | ||
} | ||
|
||
/** | ||
* @param array<string, mixed> $options | ||
* | ||
* @return VectorDocument[] | ||
*/ | ||
public function query(Vector $vector, array $options = []): array | ||
{ | ||
$limit = $options['limit'] ?? 5; | ||
$maxScore = $options['maxScore'] ?? null; | ||
$whereFilter = $options['where'] ?? '*'; | ||
|
||
$query = "({$whereFilter}) => [KNN {$limit} @embedding \$query_vector AS vector_score]"; | ||
|
||
try { | ||
$results = $this->redis->rawCommand( | ||
'FT.SEARCH', | ||
$this->indexName, | ||
$query, | ||
'PARAMS', 2, 'query_vector', $this->toRedisVector($vector), | ||
'RETURN', 4, '$.id', '$.metadata', '$.embedding', 'vector_score', | ||
'SORTBY', 'vector_score', 'ASC', | ||
'LIMIT', 0, $limit, | ||
'DIALECT', 2 | ||
); | ||
} catch (\RedisException $e) { | ||
throw new RuntimeException(\sprintf('Failed to execute query: "%s".', $e->getMessage()), 0, $e); | ||
} | ||
|
||
if (!\is_array($results) || \count($results) < 2) { | ||
return []; | ||
} | ||
|
||
$documents = []; | ||
$numResults = $results[0]; | ||
|
||
// Parse results (skip first element which is the count) | ||
for ($i = 1; $i <= $numResults; $i += 2) { | ||
// $docKey = $results[$i]; | ||
$docData = $results[$i + 1]; | ||
|
||
// Convert flat array to associative array | ||
$data = []; | ||
for ($j = 0; $j < \count($docData); $j += 2) { | ||
$fieldName = $docData[$j]; | ||
$fieldValue = $docData[$j + 1] ?? null; | ||
|
||
if (\is_string($fieldValue) && json_validate($fieldValue)) { | ||
$fieldValue = json_decode($fieldValue, true); | ||
} | ||
|
||
$data[$fieldName] = $fieldValue; | ||
} | ||
|
||
if (!isset($data['$.id'], $data['vector_score'])) { | ||
continue; | ||
} | ||
|
||
$score = (float) $data['vector_score']; | ||
|
||
// Apply max score filter if specified | ||
if (null !== $maxScore && $score > $maxScore) { | ||
continue; | ||
} | ||
|
||
$documents[] = new VectorDocument( | ||
id: Uuid::fromString($data['$.id']), | ||
vector: new Vector($data['$.embedding'] ?? []), | ||
metadata: new Metadata($data['$.metadata'] ?? []), | ||
score: $score, | ||
); | ||
} | ||
|
||
return $documents; | ||
} | ||
|
||
private function toRedisVector(VectorInterface $vector): string | ||
{ | ||
$data = $vector->getData(); | ||
$bytes = ''; | ||
foreach ($data as $value) { | ||
$bytes .= pack('f', $value); | ||
} | ||
|
||
return $bytes; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what about going with a DSN here instead? For Symfony cache we use REDIS_URL etc. this way we can just reuse an existing Redis connection
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would be nice indeed.
But Symfony cache has a huge amount of code to parse the the DSN.
I don't want to bloat the the store for now
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's good that the
RedisStore
only takes an instance ofRedis
. It is not its responsibility to instantiate the Redis client.The bundle configuration should accept a redis service name, which could be created directly in the application or with SncRedisBundle (which accepts dsn in config).