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

symfony/ai-mongo-db-message-store

MongoDB message store integration for Symfony AI Chat. Persist and retrieve chat conversations using the MongoDB PHP library, with support for creating and managing collections. Useful for durable chat history storage in MongoDB-backed Symfony apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies:
    composer require symfony/ai-chat symfony/ai-mongo-db-message-store mongodb/mongodb
    
  2. Configure MongoDB Connection: Add to config/services.yaml (Symfony) or config/mongodb.php (Laravel):
    # config/packages/ai.yaml (Symfony)
    framework:
        ai:
            message_store: mongodb
            mongodb:
                uri: 'mongodb://user:pass@host:port/db'
                collection: 'ai_chat_messages'
    
  3. Initialize Collection (run once):
    use MongoDB\Client;
    $client = new Client('mongodb://user:pass@host:port/db');
    $client->selectDatabase('db')->createCollection('ai_chat_messages');
    
  4. First Use Case:
    use Symfony\Component\AI\Chat\MessageStore\MongoDbMessageStore;
    use Symfony\Component\AI\Chat\Message;
    
    $store = new MongoDbMessageStore($client->selectDatabase('db'));
    $store->save(new Message('user', 'Hello!'));
    $messages = $store->findByConversationId('conv_123');
    

Where to Look First


Implementation Patterns

Core Workflows

  1. Chat Session Management:
    // Laravel Service Example
    public function handleChatRequest(string $conversationId, string $userInput): array
    {
        $store = app(MongoDbMessageStore::class);
        $messages = $store->findByConversationId($conversationId);
    
        $response = $this->callSymfonyAIChat($userInput, $messages);
        $store->save(new Message('ai', $response));
    
        return ['response' => $response, 'history' => $messages];
    }
    
  2. Conversation Pruning:
    // TTL Index Setup (via MongoDB CLI or PHP)
    $collection->createIndex(['timestamp' => 1], ['expireAfterSeconds' => 2592000]); // 30 days
    
  3. Hybrid Laravel-Symfony Integration:
    • Option A: API Layer
      // Laravel Route
      Route::post('/chat', function (Request $request) {
          $response = Http::post('http://symfony-ai-service/api/chat', $request->all());
          return $response->json();
      });
      
    • Option B: Shared Container
      // Laravel Service Provider
      public function register()
      {
          $this->app->singleton(MongoDbMessageStore::class, function ($app) {
              $client = new Client(config('mongodb.connection'));
              return new MongoDbMessageStore($client->selectDatabase(config('mongodb.database')));
          });
      }
      

Integration Tips

  • Laravel Event Listeners: Bind to Symfony\Component\AI\Chat\Event\MessageSentEvent for post-processing:
    public function handle(MessageSentEvent $event)
    {
        // Log, analyze, or sync to CRM
    }
    
  • Query Optimization: Use MongoDB’s $text search for full-text queries:
    $messages = $store->findBy([
        'conversationId' => 'conv_123',
        'text' => ['$text' => ['$search' => 'urgent']]
    ]);
    
  • Fallback Mechanism: Implement a decorator pattern for resilience:
    class ResilientMongoDbMessageStore implements MessageStoreInterface
    {
        public function __construct(
            private MongoDbMessageStore $primary,
            private ?MessageStoreInterface $fallback = null
        ) {}
    
        public function save(Message $message)
        {
            try {
                $this->primary->save($message);
            } catch (\Exception $e) {
                $this->fallback?->save($message);
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Driver Conflicts:

    • Issue: mongodb/mongodb (v2.0+) vs. jenssegers/mongodb (Laravel’s legacy driver).
    • Fix: Standardize on mongodb/mongodb and update Laravel’s MongoDB config:
      // config/mongodb.php
      'connections' => [
          'default' => [
              'driver' => 'mongodb',
              'host' => env('DB_HOST', '127.0.0.1'),
              'port' => env('DB_PORT', 27017),
              'database' => env('DB_DATABASE', 'forge'),
              'username' => env('DB_USERNAME', 'forge'),
              'password' => env('DB_PASSWORD', ''),
              'options' => [
                  'typeMap' => ['root' => 'array', 'document' => 'array'], // Critical for Symfony serialization
              ],
          ],
      ],
      
  2. Serialization Mismatches:

    • Issue: Symfony’s serializer may conflict with Laravel’s JSON handling.
    • Fix: Configure Symfony’s serializer to avoid overlaps:
      # config/packages/serializer.yaml
      framework:
          serializer:
              mapping:
                  paths: ['%kernel.project_dir%/config/serializer']
              ignore_annotations: true
      
  3. Missing Indexes:

    • Issue: Slow queries on conversationId or timestamp.
    • Fix: Pre-create indexes:
      $collection->createIndex(['conversationId' => 1, 'timestamp' => -1]);
      
  4. No Schema Validation:

    • Issue: MongoDB accepts any document structure, risking inconsistent data.
    • Fix: Use a validator or schema library (e.g., spatie/laravel-mongodb-schema):
      use Spatie\LaravelMongoDbSchema\Schema;
      Schema::create('ai_chat_messages', function (Blueprint $collection) {
          $collection->index('conversationId');
          $collection->index('timestamp');
          $collection->required('userId');
          $collection->required('role'); // 'user' or 'ai'
          $collection->required('content');
      });
      
  5. Symfony-Specific Assumptions:

    • Issue: Assumes Symfony’s Message class; Laravel may need adapters.
    • Fix: Create a Laravel-compatible message class:
      class LaravelMessage implements \Symfony\Component\AI\Chat\MessageInterface
      {
          public function __construct(
              public string $role,
              public string $content,
              public ?string $id = null,
              public ?string $conversationId = null,
              public ?\DateTimeInterface $timestamp = null
          ) {}
      }
      

Debugging Tips

  • Enable MongoDB Logging:
    $client->selectDatabase('db')->manage()->getLogger()->setCallback(function ($level, $message) {
        error_log("[MongoDB] [$level] $message");
    });
    
  • Query Profiling: Use MongoDB’s explain() to analyze slow queries:
    $explanation = $collection->find(['conversationId' => 'conv_123'])->explain();
    
  • Common Errors:
    • InvalidArgumentException: Check typeMap in MongoDB options (must match Symfony’s expectations).
    • ClassNotFoundException: Ensure Symfony\Component\AI\Chat\Message is autoloaded or use the Laravel adapter.

Extension Points

  1. Custom Message Fields: Extend the message store to include metadata:
    class ExtendedMongoDbMessageStore extends MongoDbMessageStore
    {
        public function saveWithMetadata(Message $message, array $metadata)
        {
            $document = $this->convertMessageToDocument($message);
            $document['metadata'] = $metadata;
            $this->collection->insertOne($document);
        }
    }
    
  2. Event Dispatching: Trigger Laravel events on message operations:
    class EventfulMongoDbMessageStore extends MongoDbMessageStore
    {
        public function save(Message $message)
        {
            $result = parent::save($message);
            event(new MessageStored($message, $result->getInsertedId()));
            return $result;
        }
    }
    
  3. Bulk Operations: Optimize batch inserts for high-throughput scenarios:
    public function bulkSave(iterable $messages)
    {
        $documents = array_map([$this, 'convertMessageToDocument'], $messages);
        $this->collection->insertMany($documents);
    }
    

4

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