Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ai Cache Store Laravel Package

symfony/ai-cache-store

Symfony AI Cache Store integrates a cache-backed vector store with Symfony AI Store, enabling lightweight storage and retrieval of embeddings using Symfony Cache. Ideal for development, testing, and small deployments where simplicity matters.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install Dependencies:

    composer require symfony/ai symfony/ai-cache-store predis/predis
    

    (Use fruitcake/laravel-cache if not using Redis.)

  2. Configure Cache Driver in .env:

    CACHE_DRIVER=redis
    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=null
    REDIS_PORT=6379
    
  3. Bind the CacheStore in AppServiceProvider:

    use Symfony\AI\Store\CacheStore;
    use Symfony\Component\Cache\Adapter\RedisAdapter;
    
    public function register()
    {
        $this->app->singleton(CacheStore::class, function ($app) {
            $cache = new RedisAdapter();
            return new CacheStore($cache);
        });
    }
    
  4. First Usage Example (in a controller or command):

    use Symfony\AI\Store\CacheStore;
    
    $store = app(CacheStore::class);
    
    // Insert a vector
    $store->insert('user_123', [0.1, 0.2, 0.3]);
    
    // Query vectors (exact match)
    $results = $store->query([0.15, 0.25, 0.35]);
    
    // Filtered query (requires v0.4.0+)
    $results = $store->query([0.1, 0.2, 0.3], ['metadata' => ['user_id' => '123']]);
    
  5. Verify with Tinker:

    php artisan tinker
    
    $store = app(CacheStore::class);
    $store->insert('test_key', [0.5, 0.5, 0.5]);
    $store->query([0.5, 0.5, 0.5]); // Should return the inserted vector
    

Where to Look First


Implementation Patterns

Core Workflows

1. Vector Storage and Retrieval

  • Insert/Update Vectors:
    $store->insert('document_456', [0.7, 0.8, 0.9], [
        'metadata' => ['author' => 'John Doe', 'tags' => ['ai', 'ml']]
    ]);
    
  • Query by Vector (Exact Match):
    $results = $store->query([0.6, 0.7, 0.8]);
    // Returns an array of keys matching the vector (if using exact-match logic).
    
  • Query with Filters:
    $results = $store->query([0.1, 0.2, 0.3], [
        'metadata' => ['tags' => ['ai']]
    ]);
    

2. Bulk Operations

  • Bulk Insert:
    $store->insertMany([
        'doc_1' => [0.1, 0.2, 0.3],
        'doc_2' => [0.4, 0.5, 0.6],
    ]);
    
  • Bulk Remove:
    $store->remove(['doc_1', 'doc_2']);
    

3. Hybrid AI Workflow Example

use Symfony\AI\Embedding\EmbeddingInterface;

// Assume $embeddingService generates embeddings
$embedding = $embeddingService->createFromText("Hello world");

// Store the embedding
$store->insert('text_hello_world', $embedding->getEmbedding());

// Later, retrieve and use in a query
$similarEmbeddings = $store->query($embedding->getEmbedding());

Integration Tips

Laravel-Specific Patterns

  1. Facade for Cleaner Usage:

    // app/Facades/VectorStore.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class VectorStore extends Facade {
        protected static function getFacadeAccessor() {
            return 'ai.cache_store';
        }
    }
    

    Bind in AppServiceProvider:

    $this->app->bind('ai.cache_store', function ($app) {
        $cache = $app['cache']->driver();
        return new \Symfony\AI\Store\CacheStore($cache);
    });
    

    Now use:

    use App\Facades\VectorStore;
    
    VectorStore::insert('key', [0.1, 0.2, 0.3]);
    
  2. Queue Jobs for Async Operations:

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Symfony\AI\Store\CacheStore;
    
    class StoreEmbeddingJob implements ShouldQueue {
        use Queueable;
    
        public function handle(CacheStore $store) {
            $store->insert('job_key', $this->embedding);
        }
    }
    
  3. Cache Tagging for Invalidation:

    // Insert with tags
    $store->insert('key', [0.1, 0.2, 0.3], ['tags' => ['user_123']]);
    
    // Clear by tag (requires custom implementation)
    $cache = $store->getCache();
    $cache->deleteItemsMatchingTag('user_123');
    

Performance Optimization

  1. TTL Management:

    $store->insert('key', [0.1, 0.2, 0.3], [], 3600); // 1-hour TTL
    
    • Use shorter TTLs for volatile data (e.g., real-time embeddings).
    • Use longer TTLs for static data (e.g., product catalogs).
  2. Batch Processing:

    $batch = [];
    foreach ($documents as $doc) {
        $batch['doc_' . $doc->id] = $doc->embedding;
    }
    $store->insertMany($batch);
    
  3. Cache Driver Selection:

    • Redis: Best for low-latency, persistent storage (recommended for production).
    • APCu: Best for in-memory, single-server use cases (dev/staging).
    • File/Database: Avoid for production due to high latency and lack of persistence.

Testing Patterns

  1. Unit Testing:

    use Symfony\AI\Store\CacheStore;
    use Symfony\Component\Cache\Adapter\ArrayAdapter;
    
    public function testInsertAndQuery() {
        $cache = new ArrayAdapter();
        $store = new CacheStore($cache);
    
        $store->insert('test_key', [0.1, 0.2, 0.3]);
        $results = $store->query([0.1, 0.2, 0.3]);
    
        $this->assertContains('test_key', $results);
    }
    
  2. Integration Testing with Redis:

    use Illuminate\Foundation\Testing\RefreshDatabase;
    
    public function testRedisIntegration() {
        $store = app(CacheStore::class);
    
        $store->insert('redis_key', [0.4, 0.5, 0.6]);
        $results = $store->query([0.4, 0.5, 0.6]);
    
        $this->assertCount(1, $results);
    }
    

Gotchas and Tips

Pitfalls

  1. Serialization Issues:

    • Problem: Vectors must be serializable. Non-serializable objects (e.g., custom classes) will fail.
    • Fix: Ensure vectors are arrays or use json_encode()/json_decode():
      $serialized = json_encode([0.1, 0.2, 0.3]);
      $store->insert('key', $serialized);
      
  2. Cache Eviction:

    • Problem: Using file cache or database cache may lead to data loss on eviction.
    • Fix: Use Redis with persistence or configure TTLs explicitly:
      CACHE_DRIVER=redis
      REDIS_PERSISTENCE=appendonly
      
  3. Exact-Match Queries Only:

    • Problem: The package does not support approximate nearest neighbor (ANN) search. Queries are exact matches or filtered by metadata.
    • Workaround: Pre-filter vectors
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky