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.
Install the Package:
composer require symfony/ai-cache-platform
Ensure symfony/ai is also installed (composer require symfony/ai).
Configure Cache Platform:
Add a service provider to config/app.php:
'providers' => [
// ...
Symfony\Component\Cache\Bridge\Laravel\CachePlatformServiceProvider::class,
],
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);
}
vendor/symfony/cache/src/Bridge/Laravel for bridge classes.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
Tag-Based Invalidation: Invalidate caches by tags (e.g., for user-specific AI data):
$cache->invalidateTags(['user_ai_data']);
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');
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');
| 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() |
Cache Key Collisions:
ai_data) may cause conflicts.feature_recommendations:user_123).Stale Data:
Redis Connection Issues:
$cache = Cache::store('redis')->rememberForever(...);
Symfony vs. Laravel DI Conflicts:
Cache may clash with Laravel’s Cache facade.$this->app->bind(\Symfony\Component\Cache\CacheInterface::class, function ($app) {
return new \Symfony\Component\Cache\Adapter\RedisAdapter(...);
});
Missing Cache Invalidation:
event(new AiModelUpdated($modelId));
// In listener: Cache::tags(['ai_model_' . $modelId])->flush();
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();
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)
}
}
Cache Warmers: Pre-load AI caches during low-traffic periods:
Cache::tags(['ai_warmup'])->put('popular_queries', $data, now()->addHours(1));
Monitoring Metrics: Track cache performance with Prometheus:
$metrics = new \Symfony\Component\Cache\Metrics\MetricsCollector();
$pool->collect($metrics);
3600 = 1 hour).CachePool for advanced features (e.g., tags), Adapter for simple key-value.Cache::remember() with Symfony’s cache—stick to one adapter per feature.Redis::publish('ai_cache_invalidate', 'user_123');
$cache->get('embedding:text_456', fn() => $aiClient->createEmbedding('text'), 86400);
Cache::tags(['ai', 'user_123'])->put('data', $value);
How can I help you explore Laravel packages today?