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 Platform Laravel Package

symfony/ai-cache-platform

Symfony AI Cache Platform bridge that integrates Cache Platform as a caching backend for Symfony AI. Enables storing and retrieving AI-related cache entries via Cache Platform, improving performance and reuse across requests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require symfony/ai-cache-platform
    

    Ensure symfony/ai is also installed (composer require symfony/ai).

  2. Configure Cache Platform: Add a service provider to config/app.php:

    'providers' => [
        // ...
        Symfony\Component\Cache\Bridge\Laravel\CachePlatformServiceProvider::class,
    ],
    
  3. First Use Case: Cache an AI-generated response (e.g., LLM output) in a controller:

    use Symfony\Component\Cache\Adapter\AdapterInterface;
    use Symfony\Component\AI\Client\ClientInterface;
    
    public function generateSummary(ClientInterface $aiClient, AdapterInterface $cache)
    {
        $cacheKey = 'ai_summary:user_' . auth()->id();
        $summary = $cache->get($cacheKey, function () use ($aiClient) {
            return $aiClient->generate('Summarize this article...');
        });
        return response()->json($summary);
    }
    

Where to Look First

  • Symfony AI Cache Docs: Symfony AI Documentation for cache platform usage.
  • Laravel Cache Integration: Check vendor/symfony/cache/src/Bridge/Laravel for bridge classes.
  • Example Projects: Look for Symfony AI + Laravel implementations (e.g., Symfony AI Demos).

Implementation Patterns

Core Workflows

  1. Caching AI Responses: Use the cache adapter to store AI-generated data (e.g., embeddings, LLM outputs) with configurable TTLs:

    $cache = app(\Symfony\Component\Cache\Adapter\AdapterInterface::class);
    $data = $cache->get('ai_embedding:user_123', function () {
        return $aiClient->createEmbedding('Sample text');
    }, 3600); // Cache for 1 hour
    
  2. Tag-Based Invalidation: Invalidate caches by tags (e.g., for user-specific AI data):

    $cache->invalidateTags(['user_ai_data']);
    
  3. Multi-Backend Caching: Leverage Symfony’s CachePool to distribute AI caches across Redis and file systems:

    $pool = app(\Symfony\Component\Cache\PoolInterface::class);
    $pool->getItem('global_ai_cache')->set('data');
    

Integration Tips

  • Laravel Service Binding: Bind Symfony’s cache platform to Laravel’s container in a service provider:

    public function register()
    {
        $this->app->singleton(\Symfony\Component\Cache\Adapter\AdapterInterface::class, function ($app) {
            return \Symfony\Component\Cache\Adapter\RedisAdapter::createConnection(
                'redis://localhost'
            )->get('ai_cache', 3600);
        });
    }
    
  • AI Client Integration: Wrap Symfony AI clients to auto-cache responses:

    class CachedAIClient
    {
        public function __construct(
            private ClientInterface $aiClient,
            private AdapterInterface $cache
        ) {}
    
        public function generate(string $prompt): string
        {
            $key = 'ai_prompt:' . md5($prompt);
            return $this->cache->get($key, fn() => $this->aiClient->generate($prompt), 300);
        }
    }
    
  • Queue-Based Invalidation: Use Laravel queues to invalidate caches asynchronously:

    CacheInvalidationJob::dispatch('user_ai_data_tag');
    

Common Patterns

Pattern Example Use Case Implementation
Key Prefixing Isolate AI caches by feature (e.g., recommendations:) $cache->get('recommendations:user_1')
Dynamic TTLs Short TTLs for volatile data (e.g., 5 mins) $cache->get($key, $callback, 300)
Fallback Logic Serve stale data if cache fails $cache->get($key, $callback, 0, null, true)
Batch Fetching Cache multiple AI responses at once Use CachePool::getItems()

Gotchas and Tips

Pitfalls

  1. Cache Key Collisions:

    • Issue: Poorly designed keys (e.g., ai_data) may cause conflicts.
    • Fix: Use namespaced keys (e.g., feature_recommendations:user_123).
  2. Stale Data:

    • Issue: Long TTLs may serve outdated AI responses (e.g., stale recommendations).
    • Fix: Implement tag-based invalidation or short TTLs (e.g., 300s).
  3. Redis Connection Issues:

    • Issue: Cache failures if Redis is down.
    • Fix: Use Laravel’s cache fallback:
      $cache = Cache::store('redis')->rememberForever(...);
      
  4. Symfony vs. Laravel DI Conflicts:

    • Issue: Symfony’s Cache may clash with Laravel’s Cache facade.
    • Fix: Explicitly bind Symfony’s cache:
      $this->app->bind(\Symfony\Component\Cache\CacheInterface::class, function ($app) {
          return new \Symfony\Component\Cache\Adapter\RedisAdapter(...);
      });
      
  5. Missing Cache Invalidation:

    • Issue: Caches not cleared after AI model updates.
    • Fix: Use event listeners or queues:
      event(new AiModelUpdated($modelId));
      // In listener: Cache::tags(['ai_model_' . $modelId])->flush();
      

Debugging Tips

  • Check Cache Hit/Miss Ratios: Use Laravel Telescope or Symfony’s CacheItemPoolInterface stats:

    $pool->getStats(); // Symfony 6.4+
    
  • Log Cache Keys: Debug cache keys in logs:

    \Log::debug('Cache key:', ['key' => $cacheKey]);
    
  • Test Locally with File Cache: Simplify debugging by switching to file cache:

    $cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
    

Extension Points

  1. Custom Cache Providers: Extend Symfony’s CachePool for AI-specific logic:

    class AiCachePool extends \Symfony\Component\Cache\Pool\PoolInterface
    {
        public function getItem($id): CacheItemInterface
        {
            // Add AI-specific logic (e.g., auto-invalidate on model updates)
        }
    }
    
  2. Cache Warmers: Pre-load AI caches during low-traffic periods:

    Cache::tags(['ai_warmup'])->put('popular_queries', $data, now()->addHours(1));
    
  3. Monitoring Metrics: Track cache performance with Prometheus:

    $metrics = new \Symfony\Component\Cache\Metrics\MetricsCollector();
    $pool->collect($metrics);
    

Configuration Quirks

  • TTL Granularity: Symfony’s cache uses seconds, not minutes (e.g., 3600 = 1 hour).
  • Pool vs. Adapter: Use CachePool for advanced features (e.g., tags), Adapter for simple key-value.
  • Laravel Cache Facade: Avoid mixing Cache::remember() with Symfony’s cache—stick to one adapter per feature.

Pro Tips

  • Use Redis Pub/Sub for Invalidation: Trigger cache invalidation across instances:
    Redis::publish('ai_cache_invalidate', 'user_123');
    
  • Cache AI Embeddings Separately: Embeddings are often reused; cache them with longer TTLs:
    $cache->get('embedding:text_456', fn() => $aiClient->createEmbedding('text'), 86400);
    
  • Leverage Laravel’s Cache Tags: Combine Symfony’s tags with Laravel’s:
    Cache::tags(['ai', 'user_123'])->put('data', $value);
    
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