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

symfony/ai-session-message-store

Symfony AI Session Message Store integrates Symfony Session as a message store for Symfony AI Chat, letting you persist and retrieve chat conversation messages across requests using standard Symfony session handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies:
    composer require symfony/ai-session-message-store symfony/ai-chat symfony/http-foundation
    
  2. Configure Laravel Session Driver: Ensure your .env uses a supported driver (Redis recommended for production):
    SESSION_DRIVER=redis
    
  3. Create a Basic Adapter: Add this to app/Providers/AppServiceProvider.php:
    use Symfony\Component\Ai\Chat\MessageStoreInterface;
    use Illuminate\Support\Facades\Session;
    
    public function register()
    {
        $this->app->singleton(MessageStoreInterface::class, function () {
            return new class implements MessageStoreInterface {
                public function load(string $sessionId): array
                {
                    Session::setId($sessionId);
                    return Session::get('ai_messages', []);
                }
    
                public function save(string $sessionId, array $messages): void
                {
                    Session::setId($sessionId);
                    Session::put('ai_messages', $messages);
                }
            };
        });
    }
    
  4. First Use Case: Create a simple AI chat route in routes/web.php:
    use Symfony\Component\Ai\Chat\AiChat;
    use Symfony\Component\Ai\Chat\MessageStoreInterface;
    
    Route::post('/ai/chat', function () {
        $aiChat = new AiChat(app(MessageStoreInterface::class));
        $response = $aiChat->chat('Hello!');
        return response()->json(['response' => $response]);
    });
    

Where to Look First


Implementation Patterns

Core Workflows

  1. Session-Backed AI Chat:
    // Store messages in session
    $store->save($request->session()->getId(), $messages);
    
    // Load messages for continuation
    $messages = $store->load($request->session()->getId());
    
  2. Hybrid Storage Pattern: Combine session (for active chats) with database (for archives):
    public function load(string $sessionId): array
    {
        $sessionMessages = parent::load($sessionId);
        $archivedMessages = DB::table('ai_messages')->where('session_id', $sessionId)->get();
        return array_merge($sessionMessages, $archivedMessages->toArray());
    }
    
  3. Flash Message Integration: Use Symfony’s FlashBag for AI notifications:
    $this->session->getFlashBag()->add('ai_notification', 'Your chat is saved!');
    

Integration Tips

  • Service Container Binding: Bind the message store in Laravel’s container for dependency injection:
    $this->app->bind(MessageStoreInterface::class, function ($app) {
        return new LaravelSessionMessageStore($app->make('session'));
    });
    
  • Middleware for Session Initialization: Ensure sessions start before AI routes:
    Route::middleware(['web', 'share_session_data'])->group(function () {
        Route::post('/ai/chat', [AiController::class, 'handle']);
    });
    
  • Testing Strategy: Mock the message store in tests:
    $store = Mockery::mock(MessageStoreInterface::class);
    $store->shouldReceive('load')->andReturn([...]);
    $store->shouldReceive('save')->once();
    

Advanced Patterns

  1. Session TTL Management: Automatically clean up old AI messages:
    use Illuminate\Support\Facades\Cache;
    
    public function save(string $sessionId, array $messages): void
    {
        Cache::remember("ai_messages_{$sessionId}", now()->addHours(1), function () use ($messages) {
            return $messages;
        });
    }
    
  2. Multi-Tenant Isolation: Use Redis namespaces or database prefixes:
    public function load(string $sessionId): array
    {
        return Session::namespace("tenant_{$tenantId}")->get('ai_messages', []);
    }
    
  3. Event-Driven Extensions: Dispatch events for message store actions:
    event(new AiMessagesSaved($sessionId, $messages));
    

Gotchas and Tips

Common Pitfalls

  1. Session ID Mismatches:
    • Issue: Laravel’s session ID may differ from Symfony’s expectations.
    • Fix: Explicitly set the session ID before loading/saving:
      $request->session()->setId($sessionId); // Ensure consistency
      
  2. Flash Message Conflicts:
    • Issue: Symfony’s FlashBag may not align with Laravel’s flash().
    • Fix: Normalize flash messages in the adapter:
      public function getFlash(string $key): array
      {
          return $this->session->getFlashBag()->get($key, []);
      }
      
  3. Session Driver Limitations:
    • Issue: File sessions fail under load; database sessions may bloat.
    • Fix: Use Redis with a dedicated namespace:
      SESSION_DRIVER=redis
      SESSION_REDIS_PREFIX=ai_chat_
      
  4. Message Size Limits:
    • Issue: Large message histories may exceed session storage limits.
    • Fix: Implement pagination or archiving:
      public function load(string $sessionId, int $limit = 100): array
      {
          return array_slice(parent::load($sessionId), -$limit);
      }
      

Debugging Tips

  1. Log Session Data: Add debug logs to inspect stored messages:
    \Log::debug('AI Messages:', ['session_id' => $sessionId, 'messages' => $messages]);
    
  2. Validate Session Backend: Check if messages persist across requests:
    dd($store->load($request->session()->getId()));
    
  3. Symfony-Laravel API Mismatches: Use dd() to compare method signatures:
    dd(method_exists($store, 'load')); // Verify interface compliance
    

Extension Points

  1. Custom Message Serialization: Override serialization for complex message objects:
    public function save(string $sessionId, array $messages): void
    {
        $serialized = json_encode($messages);
        $this->session->put('ai_messages', $serialized);
    }
    
  2. Rate Limiting: Add request throttling for AI endpoints:
    use Illuminate\Cache\RateLimiting\Limit;
    
    Route::middleware(['throttle:10,1'])->group(function () {
        Route::post('/ai/chat', [AiController::class, 'handle']);
    });
    
  3. Analytics Integration: Track AI interactions via Laravel’s logging:
    \Log::channel('ai')->info('Chat interaction', [
        'session_id' => $sessionId,
        'user_id' => auth()->id(),
        'timestamp' => now(),
    ]);
    

Configuration Quirks

  1. Redis Configuration: Ensure Redis is properly configured in config/database.php:
    'redis' => [
        'client' => 'predis',
        'options' => [
            'prefix' => 'laravel_ai_',
        ],
    ],
    
  2. Session Timeout: Adjust SESSION_LIFETIME in .env to match AI chat needs:
    SESSION_LIFETIME=1440 # 24 hours
    
  3. CORS for AI Endpoints: If using API routes, configure CORS in config/cors.php:
    'paths' => ['api/ai/*', 'sanctum/csrf-cookie'],
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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