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

symfony/ai-doctrine-message-store

Doctrine DBAL message store integration for Symfony AI Chat. Persist and retrieve chat messages in a relational database using Doctrine DBAL, enabling durable conversation history and easy storage configuration within Symfony applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies

    composer require symfony/ai symfony/ai-doctrine-message-store doctrine/dbal
    
    • Laravel users: Use doctrine/dbal (v3.x+) for DBAL support.
  2. Configure DBAL Connection Ensure your config/database.php includes a DBAL-compatible connection (e.g., pgsql, mysql). Example:

    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            'schema' => 'public',
        ],
    ],
    
  3. Set Up Schema Run the package’s schema migration (adapt for Laravel):

    # Symfony CLI (if using Symfony)
    php bin/console doctrine:schema:update --force
    
    # Laravel Alternative: Create a migration
    php artisan make:migration create_ai_messages_table
    

    Schema (simplified for Laravel):

    Schema::create('ai_messages', function (Blueprint $table) {
        $table->id();
        $table->string('conversation_id');
        $table->text('content');
        $table->json('metadata')->nullable();
        $table->timestamps();
        $table->index(['conversation_id', 'created_at']);
    });
    
  4. First Use Case: Store a Chat Message

    use Symfony\Component\AI\MessageStoreInterface;
    use Symfony\AI\DoctrineMessageStore\DoctrineDBALMessageStore;
    
    // Laravel Service Provider (e.g., AppServiceProvider)
    public function register()
    {
        $this->app->singleton(MessageStoreInterface::class, function ($app) {
            return new DoctrineDBALMessageStore(
                $app['db']->connection('pgsql')->getDoctrineConnection()
            );
        });
    }
    
    // Usage in a Controller/Service
    $messageStore = app(MessageStoreInterface::class);
    $messageStore->save(
        new \Symfony\Component\AI\Message(
            'user-123',
            'What is Laravel?',
            'Laravel is a PHP framework...'
        )
    );
    

Implementation Patterns

Core Workflows

  1. Message CRUD Operations

    • Save: Persist user/LLM exchanges.
      $message = new \Symfony\Component\AI\Message(
          'conv-abc',
          'user', 'Hello!',
          'ai', 'Hi there!'
      );
      $messageStore->save($message);
      
    • Load: Retrieve by conversation_id or timestamp.
      $messages = $messageStore->findByConversation('conv-abc');
      
    • Delete: Purge old conversations (e.g., via TTL).
      $messageStore->deleteByConversation('conv-abc');
      
  2. Conversation History

    • Use findByConversation() to fetch multi-turn dialogues.
    • Laravel Tip: Add a scopeConversation() to Eloquent if hybrid storage is needed.
  3. Metadata Handling

    • Store structured data (e.g., user_id, ai_model) in the metadata JSON field.
      $message->setMetadata([
          'user_id' => 1,
          'model' => 'gpt-4',
          'tokens' => 1200,
      ]);
      

Integration Tips

  • Symfony AI Chat Compatibility

    • Wire the store into Symfony AI’s Chat component:
      use Symfony\Component\AI\Chat\Chat;
      use Symfony\Component\AI\Chat\Message;
      
      $chat = new Chat($messageStore);
      $chat->addUserMessage('Hello!');
      $response = $chat->ask('ai-model');
      $chat->addAIMessage($response);
      
  • Laravel Event Listeners

    • Trigger actions on message storage (e.g., analytics):
      // app/Providers/EventServiceProvider
      public function boot()
      {
          \Symfony\Component\AI\Message::saved(function ($message) {
              \Log::info("AI Message stored: {$message->getContent()}");
          });
      }
      
  • Batch Operations

    • Use DBAL’s executeStatement() for bulk inserts (e.g., importing historical chats):
      $conn = $messageStore->getConnection();
      $stmt = $conn->prepare("INSERT INTO ai_messages (...) VALUES (...)");
      $stmt->executeStatement([/* batch data */]);
      
  • Hybrid Storage

    • Combine with Redis for high-throughput scenarios:
      // Cache recent messages in Redis, fall back to DBAL
      $redis = Redis::connection();
      $cacheKey = "ai:conv:{$conversationId}";
      if (!$redis->exists($cacheKey)) {
          $messages = $messageStore->findByConversation($conversationId);
          $redis->set($cacheKey, json_encode($messages), 'EX', 3600);
      }
      

Gotchas and Tips

Pitfalls

  1. Schema Conflicts

    • Issue: The package assumes a specific schema. Laravel migrations may clash with existing tables.
    • Fix: Use Schema::table() for updates or generate a custom migration:
      Schema::table('ai_messages', function (Blueprint $table) {
          $table->json('metadata')->nullable()->after('content');
      });
      
  2. PSR-15 Overhead

    • Issue: Laravel lacks native PSR-15 support. Direct DBAL usage may be simpler.
    • Fix: Bypass the store interface and use raw DBAL:
      $conn = $messageStore->getConnection();
      $conn->insert('ai_messages', [
          'conversation_id' => 'conv-abc',
          'content' => 'Hello!',
          'created_at' => now(),
      ]);
      
  3. Performance Bottlenecks

    • Issue: DBAL queries can slow down high-frequency AI interactions.
    • Fix:
      • Add indexes to conversation_id and created_at.
      • Use Laravel’s query caching:
        $messages = Cache::remember("ai:conv:{$id}", now()->addHours(1), function () use ($id) {
            return $messageStore->findByConversation($id);
        });
        
  4. Symfony Dependency Bloat

    • Issue: Pulling in symfony/ai for a single store may add unnecessary components.
    • Fix: Use only the store class and mock Symfony AI interfaces:
      // Mock Symfony AI's Message class
      class LaravelAIMessage implements \Symfony\Component\AI\MessageInterface {
          // Implement required methods
      }
      
  5. Transaction Handling

    • Issue: DBAL transactions may not align with Laravel’s.
    • Fix: Wrap operations in Laravel’s transaction:
      DB::transaction(function () use ($messageStore) {
          $messageStore->save($message);
          // Other DB operations
      });
      

Debugging Tips

  • Query Logging Enable DBAL logging to inspect slow queries:

    $conn->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    
  • Schema Validation Verify the table structure matches the package’s expectations:

    php artisan schema:dump
    

    Compare with the Symfony AI schema.

  • Connection Issues

    • Ensure the DBAL connection matches Laravel’s configuration:
      $connection = $app['db']->connection('pgsql')->getDoctrineConnection();
      

Extension Points

  1. Custom Metadata Extend the metadata field to store app-specific data:

    $message->setMetadata([
        'user_id' => auth()->id(),
        'session_id' => session()->getId(),
    ]);
    
  2. Soft Deletes Add a deleted_at column and implement soft deletes:

    Schema::table('ai_messages', function (Blueprint $table) {
        $table->softDeletes();
    });
    

    Override deleteByConversation() to use soft deletes.

  3. Search Functionality Add full-text search with PostgreSQL/MySQL:

    Schema::table('ai_messages', function (Blueprint $table) {
        $table->fullText('content');
    });
    

    Query with:

    $conn->executeQuery("
        SELECT * FROM ai_messages
        WHERE to_tsvector('english', content) @@ to_tsquery('english', ?)
    ", ['laravel']);
    
  4. Event Dispatching Trigger Laravel events on message operations:

    // In DoctrineDBALMessageStore
    event(new \App\Events\AIMessageStored($message));
    
  5. Rate Limiting Use Laravel’s rate limiting middleware for API endpoints that store messages:

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony