Skip to content

[AIBundle] Cache store configuration improved #293

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
4 changes: 3 additions & 1 deletion src/ai-bundle/config/options.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@
->arrayPrototype()
->children()
->scalarNode('service')->cannotBeEmpty()->defaultValue('cache.app')->end()
->scalarNode('cache_key')->end()
->scalarNode('strategy')->end()
->end()
->end()
->end()
Expand Down Expand Up @@ -215,7 +217,7 @@
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->scalarNode('distance')->cannotBeEmpty()->end()
->scalarNode('strategy')->cannotBeEmpty()->end()
->end()
->end()
->end()
Expand Down
8 changes: 8 additions & 0 deletions src/ai-bundle/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,14 @@ Configuration
# multiple collections possible per type
default:
collection: 'my_collection'
cache:
research:
service: 'cache.app'
cache_key: 'research'
strategy: 'chebyshev'
memory:
ollama:
strategy: 'manhattan'
indexer:
default:
# platform: 'ai.platform.mistral'
Expand Down
35 changes: 31 additions & 4 deletions 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 @@ -50,6 +50,8 @@
use Symfony\AI\Store\Bridge\SurrealDb\Store as SurrealDbStore;
use Symfony\AI\Store\Bridge\Typesense\Store as TypesenseStore;
use Symfony\AI\Store\CacheStore;
use Symfony\AI\Store\DistanceCalculator;
use Symfony\AI\Store\DistanceStrategy;
use Symfony\AI\Store\Document\Vectorizer;
use Symfony\AI\Store\Indexer;
use Symfony\AI\Store\InMemoryStore;
Expand Down Expand Up @@ -494,8 +496,24 @@ private function processStoreConfig(string $type, array $stores, ContainerBuilde
foreach ($stores as $name => $store) {
$arguments = [
new Reference($store['service']),
new Definition(DistanceCalculator::class),
];

if (\array_key_exists('cache_key', $store) && null !== $store['cache_key']) {
$arguments[2] = $store['cache_key'];
}

if (\array_key_exists('strategy', $store) && null !== $store['strategy']) {
if (!$container->hasDefinition('ai.store.distance_calculator.'.$name)) {
$distanceCalculatorDefinition = new Definition(DistanceCalculator::class);
$distanceCalculatorDefinition->setArgument(0, DistanceStrategy::from($store['strategy']));

$container->setDefinition('ai.store.distance_calculator.'.$name, $distanceCalculatorDefinition);
}

$arguments[1] = new Reference('ai.store.distance_calculator.'.$name);
}

$definition = new Definition(CacheStore::class);
$definition
->addTag('ai.store')
Expand Down Expand Up @@ -577,9 +595,18 @@ private function processStoreConfig(string $type, array $stores, ContainerBuilde

if ('memory' === $type) {
foreach ($stores as $name => $store) {
$arguments = [
$store['distance'],
];
$arguments = [];

if (\array_key_exists('strategy', $store) && null !== $store['strategy']) {
if (!$container->hasDefinition('ai.store.distance_calculator.'.$name)) {
$distanceCalculatorDefinition = new Definition(DistanceCalculator::class);
$distanceCalculatorDefinition->setArgument(0, DistanceStrategy::from($store['strategy']));

$container->setDefinition('ai.store.distance_calculator.'.$name, $distanceCalculatorDefinition);
}

$arguments[0] = new Reference('ai.store.distance_calculator.'.$name);
}

$definition = new Definition(InMemoryStore::class);
$definition
Expand Down
143 changes: 142 additions & 1 deletion src/ai-bundle/tests/DependencyInjection/AiBundleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@
use Symfony\AI\AiBundle\AiBundle;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

#[CoversClass(AiBundle::class)]
#[UsesClass(ContainerBuilder::class)]
#[UsesClass(Definition::class)]
#[UsesClass(Reference::class)]
class AiBundleTest extends TestCase
{
#[DoesNotPerformAssertions]
Expand Down Expand Up @@ -105,6 +109,130 @@ public function testAgentsAsToolsCannotDefineService()
]);
}

public function testCacheStoreWithCustomKeyCanBeConfigured()
{
$container = $this->buildContainer([
'ai' => [
'store' => [
'cache' => [
'my_cache_store_with_custom_strategy' => [
'service' => 'cache.system',
'cache_key' => 'random',
],
],
],
],
]);

$this->assertTrue($container->hasDefinition('ai.store.cache.my_cache_store_with_custom_strategy'));
$this->assertFalse($container->hasDefinition('ai.store.distance_calculator.my_cache_store_with_custom_strategy'));

$definition = $container->getDefinition('ai.store.cache.my_cache_store_with_custom_strategy');

$this->assertCount(3, $definition->getArguments());
$this->assertInstanceOf(Reference::class, $definition->getArgument(0));
$this->assertSame('cache.system', (string) $definition->getArgument(0));
$this->assertSame('random', $definition->getArgument(2));
}

public function testCacheStoreWithCustomStrategyCanBeConfigured()
{
$container = $this->buildContainer([
'ai' => [
'store' => [
'cache' => [
'my_cache_store_with_custom_strategy' => [
'service' => 'cache.system',
'strategy' => 'chebyshev',
],
],
],
],
]);

$this->assertTrue($container->hasDefinition('ai.store.cache.my_cache_store_with_custom_strategy'));
$this->assertTrue($container->hasDefinition('ai.store.distance_calculator.my_cache_store_with_custom_strategy'));

$definition = $container->getDefinition('ai.store.cache.my_cache_store_with_custom_strategy');

$this->assertCount(2, $definition->getArguments());
$this->assertInstanceOf(Reference::class, $definition->getArgument(0));
$this->assertSame('cache.system', (string) $definition->getArgument(0));
$this->assertInstanceOf(Reference::class, $definition->getArgument(1));
$this->assertSame('ai.store.distance_calculator.my_cache_store_with_custom_strategy', (string) $definition->getArgument(1));
}

public function testCacheStoreWithCustomStrategyAndKeyCanBeConfigured()
{
$container = $this->buildContainer([
'ai' => [
'store' => [
'cache' => [
'my_cache_store_with_custom_strategy' => [
'service' => 'cache.system',
'cache_key' => 'random',
'strategy' => 'chebyshev',
],
],
],
],
]);

$this->assertTrue($container->hasDefinition('ai.store.cache.my_cache_store_with_custom_strategy'));
$this->assertTrue($container->hasDefinition('ai.store.distance_calculator.my_cache_store_with_custom_strategy'));

$definition = $container->getDefinition('ai.store.cache.my_cache_store_with_custom_strategy');

$this->assertCount(3, $definition->getArguments());
$this->assertInstanceOf(Reference::class, $definition->getArgument(0));
$this->assertSame('cache.system', (string) $definition->getArgument(0));
$this->assertSame('random', $definition->getArgument(2));
$this->assertInstanceOf(Reference::class, $definition->getArgument(1));
$this->assertSame('ai.store.distance_calculator.my_cache_store_with_custom_strategy', (string) $definition->getArgument(1));
}

public function testInMemoryStoreWithoutCustomStrategyCanBeConfigured()
{
$container = $this->buildContainer([
'ai' => [
'store' => [
'memory' => [
'my_memory_store_with_custom_strategy' => [],
],
],
],
]);

$this->assertTrue($container->hasDefinition('ai.store.memory.my_memory_store_with_custom_strategy'));

$definition = $container->getDefinition('ai.store.memory.my_memory_store_with_custom_strategy');
$this->assertCount(0, $definition->getArguments());
}

public function testInMemoryStoreWithCustomStrategyCanBeConfigured()
{
$container = $this->buildContainer([
'ai' => [
'store' => [
'memory' => [
'my_memory_store_with_custom_strategy' => [
'strategy' => 'chebyshev',
],
],
],
],
]);

$this->assertTrue($container->hasDefinition('ai.store.memory.my_memory_store_with_custom_strategy'));
$this->assertTrue($container->hasDefinition('ai.store.distance_calculator.my_memory_store_with_custom_strategy'));

$definition = $container->getDefinition('ai.store.memory.my_memory_store_with_custom_strategy');

$this->assertCount(1, $definition->getArguments());
$this->assertInstanceOf(Reference::class, $definition->getArgument(0));
$this->assertSame('ai.store.distance_calculator.my_memory_store_with_custom_strategy', (string) $definition->getArgument(0));
}

private function buildContainer(array $configuration): ContainerBuilder
{
$container = new ContainerBuilder();
Expand Down Expand Up @@ -205,6 +333,19 @@ private function getFullConfig(): array
'my_cache_store' => [
'service' => 'cache.system',
],
'my_cache_store_with_custom_key' => [
'service' => 'cache.system',
'cache_key' => 'bar',
],
'my_cache_store_with_custom_strategy' => [
'service' => 'cache.system',
'strategy' => 'chebyshev',
],
'my_cache_store_with_custom_strategy_and_custom_key' => [
'service' => 'cache.system',
'cache_key' => 'bar',
'strategy' => 'chebyshev',
],
],
'chroma_db' => [
'my_chroma_store' => [
Expand All @@ -230,7 +371,7 @@ private function getFullConfig(): array
],
'memory' => [
'my_memory_store' => [
'distance' => 'cosine',
'strategy' => 'cosine',
],
],
'mongodb' => [
Expand Down
8 changes: 4 additions & 4 deletions src/store/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ You can find more advanced usage in combination with an Agent using the store fo
* `Similarity Search with MongoDB (RAG)`_
* `Similarity Search with Neo4j (RAG)`_
* `Similarity Search with Pinecone (RAG)`_
* `Similarity Search with PSR-6 Cache (RAG)`_
* `Similarity Search with Qdrant (RAG)`_
* `Similarity Search with SurrealDB (RAG)`_
* `Similarity Search with Symfony Cache (RAG)`_
* `Similarity Search with Typesense (RAG)`_

.. note::
Expand All @@ -66,9 +66,9 @@ Supported Stores
* `Neo4j`_
* `Pinecone`_ (requires `probots-io/pinecone-php` as additional dependency)
* `Postgres`_ (requires `ext-pdo`)
* `PSR-6 Cache`_
* `Qdrant`_
* `SurrealDB`_
* `Symfony Cache`_
* `Typesense`_

.. note::
Expand Down Expand Up @@ -109,7 +109,7 @@ This leads to a store implementing two methods::
.. _`Similarity Search with memory storage (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/in-memory.php
.. _`Similarity Search with Neo4j (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/neo4j.php
.. _`Similarity Search with Pinecone (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/pinecone.php
.. _`Similarity Search with PSR-6 Cache (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/cache.php
.. _`Similarity Search with Symfony Cache (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/cache.php
.. _`Similarity Search with Qdrant (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/qdrant.php
.. _`Similarity Search with SurrealDB (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/surrealdb.php
.. _`Similarity Search with Typesense (RAG)`: https://github.com/symfony/ai/blob/main/examples/rag/typesense.php
Expand All @@ -126,4 +126,4 @@ This leads to a store implementing two methods::
.. _`Neo4j`: https://neo4j.com/
.. _`Typesense`: https://typesense.org/
.. _`GitHub`: https://github.com/symfony/ai/issues/16
.. _`PSR-6 Cache`: https://www.php-fig.org/psr/psr-6/
.. _`Symfony Cache`: https://symfony.com/doc/current/components/cache.html
6 changes: 3 additions & 3 deletions src/store/src/CacheStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ public function __construct(
private DistanceCalculator $distanceCalculator = new DistanceCalculator(),
private string $cacheKey = '_vectors',
) {
if (!interface_exists(CacheItemPoolInterface::class)) {
throw new RuntimeException('For using the CacheStore as vector store, a PSR-6 cache implementation is required. Try running "composer require symfony/cache" or another PSR-6 compatible cache.');
if (!interface_exists(CacheInterface::class)) {
throw new RuntimeException('For using the CacheStore as vector store, a symfony/contracts cache implementation is required. Try running "composer require symfony/cache" or another symfony/contracts compatible cache.');
}
}

Expand Down Expand Up @@ -61,7 +61,7 @@ public function add(VectorDocument ...$documents): void
*/
public function query(Vector $vector, array $options = []): array
{
$documents = $this->cache->getItem($this->cacheKey)->get() ?? [];
$documents = $this->cache->get($this->cacheKey, static fn (): array => []);

$vectorDocuments = array_map(static fn (array $document): VectorDocument => new VectorDocument(
id: Uuid::fromString($document['id']),
Expand Down