Skip to content

[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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions examples/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,10 @@ services:
ports:
- '8108:8108'

redis:
image: redis:8.0.3
ports:
- '6379:6379'

volumes:
typesense_data:
73 changes: 73 additions & 0 deletions examples/rag/redis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?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.
*/

use Symfony\AI\Agent\Agent;
use Symfony\AI\Agent\Toolbox\AgentProcessor;
use Symfony\AI\Agent\Toolbox\Tool\SimilaritySearch;
use Symfony\AI\Agent\Toolbox\Toolbox;
use Symfony\AI\Fixtures\Movies;
use Symfony\AI\Platform\Bridge\OpenAi\Embeddings;
use Symfony\AI\Platform\Bridge\OpenAi\Gpt;
use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\AI\Store\Bridge\Redis\Store;
use Symfony\AI\Store\Document\Metadata;
use Symfony\AI\Store\Document\TextDocument;
use Symfony\AI\Store\Document\Vectorizer;
use Symfony\AI\Store\Indexer;
use Symfony\Component\Uid\Uuid;

require_once dirname(__DIR__).'/bootstrap.php';

// initialize the store
$redis = new Redis([
'host' => 'localhost',
'port' => 6379,
]);
$store = new Store(
redis: $redis,
indexName: 'my_index',
);

// create embeddings and documents
$documents = [];
foreach (Movies::all() as $i => $movie) {
$documents[] = new TextDocument(
id: Uuid::v4(),
content: 'Title: '.$movie['title'].\PHP_EOL.'Director: '.$movie['director'].\PHP_EOL.'Description: '.$movie['description'],
metadata: new Metadata($movie),
);
}

// initialize the table
$store->initialize(['vector_size' => 1536]);

// create embeddings for documents
$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client());
$vectorizer = new Vectorizer($platform, $embeddings = new Embeddings());
$indexer = new Indexer($vectorizer, $store, logger());
$indexer->index($documents);

$model = new Gpt(Gpt::GPT_4O_MINI);

$similaritySearch = new SimilaritySearch($platform, $embeddings, $store);
$toolbox = new Toolbox([$similaritySearch], logger: logger());
$processor = new AgentProcessor($toolbox);
$agent = new Agent($platform, $model, [$processor], [$processor], logger());

$messages = new MessageBag(
Message::forSystem('Please answer all user questions only using SimilaritySearch function.'),
Message::ofUser('Which movie fits the theme of technology?')
);
$result = $agent->call($messages);

echo $result->getContent().\PHP_EOL;
28 changes: 28 additions & 0 deletions src/ai-bundle/config/options.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use MongoDB\Client as MongoDbClient;
use Probots\Pinecone\Client as PineconeClient;
use Symfony\AI\Platform\PlatformInterface;
use Symfony\AI\Store\Bridge\Redis\Distance;
use Symfony\AI\Store\StoreInterface;

return static function (DefinitionConfigurator $configurator): void {
Expand Down Expand Up @@ -278,6 +279,33 @@
->end()
->end()
->end()
->arrayNode('redis')
->normalizeKeys(false)
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->variableNode('connection_parameters')
Copy link
Contributor

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

Copy link
Member Author

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

Copy link
Member

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 of Redis. 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).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I update the config to support either

  • An array of parameter that is passed to the Redis constructor
  • A service id that points to an instance of Redis

->info('see https://github.com/phpredis/phpredis?tab=readme-ov-file#example-1')
->cannotBeEmpty()
->end()
->scalarNode('client')
->info('a service id of a Redis client')
->cannotBeEmpty()
->end()
->scalarNode('index_name')->isRequired()->cannotBeEmpty()->end()
->scalarNode('key_prefix')->defaultValue('vector:')->end()
->enumNode('distance')
->info('Distance metric to use for vector similarity search')
->values(Distance::cases())
->defaultValue(Distance::Cosine)
->end()
->end()
->validate()
->ifTrue(static fn ($v) => !isset($v['connection_parameters']) && !isset($v['client']))
->thenInvalid('Either "connection_parameters" or "client" must be configured.')
->end()
->end()
->end()
->arrayNode('surreal_db')
->normalizeKeys(false)
->useAttributeAsKey('name')
Expand Down
29 changes: 28 additions & 1 deletion src/ai-bundle/src/AiBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@
use Symfony\AI\AiBundle\Security\Attribute\IsGrantedTool;
use Symfony\AI\Platform\Bridge\Anthropic\PlatformFactory as AnthropicPlatformFactory;
use Symfony\AI\Platform\Bridge\Azure\OpenAi\PlatformFactory as AzureOpenAiPlatformFactory;
use Symfony\AI\Platform\Bridge\Cerebras\PlatformFactory as CerebrasPlatformFactory;
use Symfony\AI\Platform\Bridge\Gemini\PlatformFactory as GeminiPlatformFactory;
use Symfony\AI\Platform\Bridge\LmStudio\PlatformFactory as LmStudioPlatformFactory;
use Symfony\AI\Platform\Bridge\Mistral\PlatformFactory as MistralPlatformFactory;
use Symfony\AI\Platform\Bridge\Ollama\PlatformFactory as OllamaPlatformFactory;
use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory as OpenAiPlatformFactory;
use Symfony\AI\Platform\Bridge\OpenRouter\PlatformFactory as OpenRouterPlatformFactory;
use Symfony\AI\Platform\Bridge\Cerebras\PlatformFactory as CerebrasPlatformFactory;
use Symfony\AI\Platform\Model;
use Symfony\AI\Platform\ModelClientInterface;
use Symfony\AI\Platform\Platform;
Expand All @@ -47,6 +47,7 @@
use Symfony\AI\Store\Bridge\Neo4j\Store as Neo4jStore;
use Symfony\AI\Store\Bridge\Pinecone\Store as PineconeStore;
use Symfony\AI\Store\Bridge\Qdrant\Store as QdrantStore;
use Symfony\AI\Store\Bridge\Redis\Store as RedisStore;
use Symfony\AI\Store\Bridge\SurrealDb\Store as SurrealDbStore;
use Symfony\AI\Store\Bridge\Typesense\Store as TypesenseStore;
use Symfony\AI\Store\CacheStore;
Expand Down Expand Up @@ -703,6 +704,32 @@ private function processStoreConfig(string $type, array $stores, ContainerBuilde
}
}

if ('redis' === $type) {
foreach ($stores as $name => $store) {
if (isset($store['http_client'])) {
$redisClient = new Reference($store['redis_client']);
} else {
$redisClient = new Definition(\Redis::class);
$redisClient->setArguments([$store['connection_parameters']]);
}

$arguments = [
$redisClient,
$store['index_name'],
$store['key_prefix'],
$store['distance'],
];

$definition = new Definition(RedisStore::class);
$definition
->addTag('ai.store')
->setArguments($arguments)
;

$container->setDefinition('ai.store.'.$type.'.'.$name, $definition);
}
}

if ('surreal_db' === $type) {
foreach ($stores as $name => $store) {
$arguments = [
Expand Down
9 changes: 9 additions & 0 deletions src/ai-bundle/tests/DependencyInjection/AiBundleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,15 @@ private function getFullConfig(): array
'distance' => 'Cosine',
],
],
'redis' => [
'my_redis_store' => [
'connection_parameters' => [
'host' => '1.2.3.4',
'port' => 6379,
],
'index_name' => 'my_vector_index',
],
],
'surreal_db' => [
'my_surreal_db_store' => [
'endpoint' => 'http://127.0.0.1:8000',
Expand Down
1 change: 1 addition & 0 deletions src/store/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ CHANGELOG
- Pinecone
- PostgreSQL with pgvector extension
- Qdrant
- Redis
- SurrealDB
- Typesense
* Add Retrieval Augmented Generation (RAG) support:
Expand Down
1 change: 1 addition & 0 deletions src/store/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"symfony/ai-platform": "@dev",
"symfony/clock": "^6.4 || ^7.1",
"symfony/http-client": "^6.4 || ^7.1",
"symfony/polyfill-php83": "^1.32",
"symfony/uid": "^6.4 || ^7.1"
},
"require-dev": {
Expand Down
31 changes: 31 additions & 0 deletions src/store/src/Bridge/Redis/Distance.php
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;
}
}
Loading