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 Redis Message Store Laravel Package

symfony/ai-redis-message-store

Redis-backed message store for Symfony AI Chat. Persists and retrieves chat messages using Redis (phpredis) for fast, durable conversation history and session state. Part of the Symfony AI ecosystem; issues and PRs handled in the main symfony/ai repo.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies Add the package and required Symfony components to your Laravel project:

    composer require symfony/ai-redis-message-store symfony/serializer symfony/messenger
    
  2. Configure Redis Ensure your config/redis.php is properly set up for your Redis server. Example:

    'default' => [
        'url' => env('REDIS_URL'),
        'client' => 'phpredis',
    ],
    
  3. Basic Integration Create a service provider to bind the Redis message store to Laravel’s container:

    // app/Providers/SymfonyAIServiceProvider.php
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Symfony\Component\AI\Chat\RedisMessageStore;
    use Symfony\Component\AI\Chat\MessageStoreInterface;
    
    class SymfonyAIServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton(MessageStoreInterface::class, function ($app) {
                $redis = $app['redis']->connection();
                return new RedisMessageStore($redis);
            });
        }
    }
    

    Register the provider in config/app.php under providers.

  4. First Use Case Use the message store in a Laravel service or controller:

    use Symfony\Component\AI\Chat\MessageStoreInterface;
    
    class ChatService
    {
        protected $messageStore;
    
        public function __construct(MessageStoreInterface $messageStore)
        {
            $this->messageStore = $messageStore;
        }
    
        public function saveMessage(string $conversationId, array $message)
        {
            $this->messageStore->save($conversationId, $message);
        }
    
        public function loadMessages(string $conversationId): array
        {
            return $this->messageStore->findAll($conversationId);
        }
    }
    

Implementation Patterns

Usage Patterns

  1. Dependency Injection Leverage Laravel’s service container to inject MessageStoreInterface into your services. Example:

    class ChatController extends Controller
    {
        public function __construct(private MessageStoreInterface $messageStore) {}
    
        public function store(Request $request)
        {
            $this->messageStore->save($request->conversation_id, $request->message);
            return response()->json(['status' => 'saved']);
        }
    }
    
  2. Key Naming Convention Define a consistent key naming strategy to avoid collisions. Example:

    $key = "chat:{$userId}:{$conversationId}";
    $this->messageStore->save($key, $message);
    
  3. Error Handling and Retries Implement retry logic for Redis operations using Laravel’s retry helper:

    use Illuminate\Support\Facades\Redis;
    
    $this->messageStore->save($conversationId, $message);
    retry(5, function () use ($conversationId, $message) {
        $redis = Redis::connection();
        $redis->set($this->getKey($conversationId), json_encode($message));
    }, function () {
        return Redis::connection()->ping() !== 'PONG';
    });
    
  4. Integration with Laravel Events Dispatch Laravel events when messages are saved or loaded:

    use Illuminate\Support\Facades\Event;
    
    $this->messageStore->save($conversationId, $message);
    Event::dispatch(new MessageSaved($conversationId, $message));
    

Workflows

  1. Real-Time Chat Application

    • Use the Redis message store for storing chat messages in real-time.
    • Combine with Laravel Echo and Pusher for live updates.
  2. AI Agent Collaboration

    • Store conversation history in Redis for AI agents to reference.
    • Use Redis pub/sub for broadcasting messages between agents.
  3. Multi-Tenant Chat System

    • Prefix keys with tenant identifiers:
      $key = "tenant:{$tenantId}:chat:{$conversationId}";
      

Integration Tips

  1. Symfony Messenger Integration If using Symfony Messenger, configure it to use the Redis message store for transport:

    # config/packages/messenger.yaml
    framework:
        messenger:
            transports:
                redis_chat:
                    dsn: '%env(REDIS_DSN)%'
                    options:
                        queue_name: 'chat_messages'
                    retry_strategy:
                        max_retries: 3
                        delay: 1000
                        multiplier: 2
    
  2. Caching Layer Cache frequently accessed conversations in Laravel’s cache:

    $cacheKey = "chat:conversation:{$conversationId}";
    if (!cache()->has($cacheKey)) {
        $messages = $this->messageStore->findAll($conversationId);
        cache()->put($cacheKey, $messages, now()->addMinutes(5));
    }
    
  3. Monitoring and Metrics Track Redis operations using Laravel Telescope or Prometheus:

    use Illuminate\Support\Facades\Redis;
    
    $start = microtime(true);
    $this->messageStore->save($conversationId, $message);
    $latency = microtime(true) - $start;
    \Log::info("Redis save latency: {$latency}s");
    

Gotchas and Tips

Pitfalls

  1. Key Collisions

    • Without a consistent naming convention, keys may collide with other Redis users in a shared environment.
    • Solution: Use a unique prefix for your application, e.g., appname:chat:{$conversationId}.
  2. Memory Management

    • Redis stores messages in memory, which can lead to high memory usage if not managed.
    • Solution: Set TTL (Time-To-Live) for keys to automatically expire old messages:
      $redis = Redis::connection();
      $redis->setex($key, 86400, json_encode($message)); // Expire in 24 hours
      
  3. Serialization Issues

    • The package relies on Symfony’s Serializer for converting messages to/from JSON.
    • Solution: Ensure your message objects are serializable or use arrays for simplicity.
  4. Lack of Advanced Redis Features

    • The package only uses basic Redis commands (SET, GET). Advanced features like streams or hashes are not supported.
    • Solution: Extend the RedisMessageStore class to add custom Redis commands as needed.
  5. Dependency Conflicts

    • Symfony’s autowiring and configuration may conflict with Laravel’s conventions.
    • Solution: Isolate Symfony dependencies in a separate module or namespace.

Debugging

  1. Redis Connection Issues

    • If Redis operations fail, verify the connection settings in config/redis.php.
    • Debugging Tip: Use Redis::connection()->ping() to check connectivity.
  2. Serialization Errors

    • If messages fail to save or load, check if they are properly serialized.
    • Debugging Tip: Log the serialized message before saving:
      $serialized = json_encode($message);
      \Log::debug("Serialized message: {$serialized}");
      
  3. Key Not Found Errors

    • Ensure the key naming convention matches between save and load operations.
    • Debugging Tip: Log the constructed key:
      $key = "chat:{$conversationId}";
      \Log::debug("Using key: {$key}");
      

Config Quirks

  1. Redis Client Configuration

    • The package expects a Redis client compatible with phpredis. If using predis, ensure it’s properly configured.
    • Solution: Configure the Redis client in config/redis.php:
      'client' => env('REDIS_CLIENT', 'phpredis'),
      
  2. Symfony Container Initialization

    • Symfony’s dependency injection container must be properly initialized for the message store to work.
    • Solution: Ensure the SymfonyAIServiceProvider is registered and loaded before use.

Extension Points

  1. Custom Message Store

    • Extend RedisMessageStore to add custom functionality:
      use Symfony\Component\AI\Chat\RedisMessageStore as BaseRedisMessageStore;
      
      class CustomRedisMessageStore extends BaseRedisMessageStore
      {
          public function saveWithTTL(string $conversationId, array $message, int $ttl)
          {
              $key = $this->getKey($conversationId);
              $this->redis->setex($key, $ttl, json_encode($message));
          }
      }
      
  2. Event Listeners

    • Add event listeners for message store operations:
      $messageStore->addListener(function ($event) {
          \Log::info("Message event: " . $event->getType());
      });
      
  3. Fallback Mechanism

    • Implement a fallback to a different message store if Redis is unavailable:
      use Symfony\Component\AI\Chat\MessageStoreInterface;
      
      class FallbackMessageStore implements MessageStoreInterface
      {
          public function save(string $conversationId, array $message): void
          {
              // Fallback logic
      
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