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

symfony/ai-pogocache-message-store

Symfony AI Chat integration for Pogocache message storage. Persist and retrieve chat messages via Pogocache’s HTTP API with simple configuration, enabling shared, durable conversation history backed by Pogocache and compatible with its authentication options.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require symfony/ai-pogocache-message-store
    

    Ensure symfony/ai-chat (≥0.9) and symfony/http-client (≥7.3) are installed.

  2. Configure Pogocache: Add credentials to .env:

    POGOCACHE_URL=https://your-pogocache-instance.com/api
    POGOCACHE_TOKEN=your_api_token_here
    
  3. Bind the Message Store: Register the store in config/app.php or a service provider:

    $app->bind(
        \Symfony\Component\Ai\Chat\MessageStoreInterface::class,
        function ($app) {
            return new \Symfony\Ai\PogocacheMessageStore(
                $app->make(\Symfony\Contracts\HttpClient\HttpClientInterface::class),
                $app->make(\Symfony\Component\Serializer\SerializerInterface::class),
                $app['config']['services.pogocache.token']
            );
        }
    );
    
  4. First Use Case: Use Symfony AI Chat’s Chat class to send/retrieve messages:

    use Symfony\Component\Ai\Chat\Chat;
    use Symfony\Component\Ai\Chat\Message;
    
    $chat = new Chat($messageStore);
    $chat->addMessage(new Message('user', 'Hello!'));
    $response = $chat->ask('ai', 'How are you?');
    

Implementation Patterns

Core Workflows

  1. Message Persistence:

    • Save: Automatically triggered via Symfony AI Chat’s Chat class.
    • Retrieve: Fetch messages by ID for conversation history:
      $message = $messageStore->getMessage('chat_id:123');
      
  2. Laravel Integration:

    • Service Provider: Centralize Pogocache configuration:
      public function register(): void {
          $this->app->singleton(\Symfony\Component\Ai\Chat\MessageStoreInterface::class, function ($app) {
              return new \Symfony\Ai\PogocacheMessageStore(
                  $app->make(\Symfony\Contracts\HttpClient\HttpClientInterface::class),
                  new \Symfony\Component\Serializer\Serializer(),
                  config('services.pogocache.token')
              );
          });
      }
      
  3. Event-Driven Patterns:

    • Listen to Symfony AI events and dispatch Laravel events:
      $messageStore->addListener(
          \Symfony\Component\Ai\Chat\Events\MessageStored::class,
          function ($event) {
              event(new \App\Events\ChatMessageStored($event->getMessage()));
          }
      );
      
  4. Queue Integration:

    • Offload message storage to queues for async processing:
      ChatMessage::created(function ($message) {
          StorePogocacheMessage::dispatch($message);
      });
      

Laravel-Specific Patterns

  1. HTTP Client Abstraction:

    • Replace Symfony’s HttpClient with Laravel’s HttpClient:
      use Illuminate\Support\Facades\Http;
      
      class LaravelPogocacheStore {
          public function save(Message $message): void {
              Http::withHeaders([
                  'Authorization' => 'Bearer '.config('services.pogocache.token'),
                  'Content-Type' => 'application/json',
              ])->post(config('services.pogocache.url'), [
                  'json' => $message->toArray(),
              ]);
          }
      }
      
  2. Fallback Mechanism:

    • Cache messages locally during Pogocache outages:
      public function getMessage(string $id): ?Message {
          return cache()->remember("pogocache:fallback:{$id}", now()->addMinutes(10), function () use ($id) {
              return $this->pogocache->fetch($id);
          });
      }
      
  3. Model Binding:

    • Bind Pogocache messages to Laravel Eloquent models:
      class ChatMessage extends Model {
          protected $casts = ['content' => 'array'];
      
          public static function boot(): void {
              static::saved(function ($model) {
                  app(\Symfony\Component\Ai\Chat\MessageStoreInterface::class)->save($model);
              });
          }
      }
      
  4. Testing:

    • Mock Pogocache responses in Laravel tests:
      Http::fake([
          config('services.pogocache.url') => Http::response(['content' => 'test'], 200),
      ]);
      

Gotchas and Tips

Pitfalls

  1. Serialization Mismatches:

    • Issue: Symfony’s Serializer may not handle Laravel’s Carbon instances or custom objects.
    • Fix: Normalize data before serialization:
      $data = [
          'content' => $message->content,
          'created_at' => $message->created_at->toIso8601String(),
      ];
      
  2. HTTP Client Timeouts:

    • Issue: Pogocache requests may hang if not configured with retries.
    • Fix: Use Laravel’s HttpClient with middleware:
      Http::withOptions([
          'timeout' => 5.0,
          'connect_timeout' => 2.0,
      ])->retry(3, 100);
      
  3. Idempotency:

    • Issue: Duplicate messages if Laravel retries jobs or Symfony AI Chat reprocesses events.
    • Fix: Use Pogocache’s HTTP PUT for updates and check for existence:
      if (!$this->exists($message->id)) {
          $this->save($message);
      }
      
  4. Token Management:

    • Issue: Hardcoded tokens in config files.
    • Fix: Use Laravel Vault or environment variables:
      POGOCACHE_TOKEN=${VAULT_SECURE_POGOCACHE_TOKEN}
      
  5. Rate Limiting:

    • Issue: Pogocache may throttle requests during high traffic.
    • Fix: Implement exponential backoff in Laravel:
      use Symfony\Component\HttpClient\Retry\RetryStrategy;
      
      $client = Http::withOptions([
          'retry_strategy' => new RetryStrategy(3, 100, true),
      ]);
      

Debugging Tips

  1. Log HTTP Traffic:

    • Intercept Pogocache requests with Laravel middleware:
      Http::macro('pogocache', function ($callback) {
          $response = Http::withHeaders([
              'Authorization' => 'Bearer '.config('services.pogocache.token'),
          ])->toPogocache($callback);
      
          \Log::debug('Pogocache Request', [
              'url' => $response->originalRequest()->url(),
              'method' => $response->originalRequest()->method(),
              'response' => $response->body(),
          ]);
      
          return $response;
      });
      
  2. Validate Payloads:

    • Use Laravel’s Validator to ensure messages conform to Pogocache’s schema:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make($message->toArray(), [
          'content' => 'required|string|max:10000',
          'created_at' => 'required|date',
      ]);
      
  3. Monitor Performance:

    • Track cache hit/miss ratios with Laravel Telescope:
      \Log::channel('telescope')->info('Pogocache Miss', [
          'message_id' => $message->id,
          'fallback_used' => true,
      ]);
      

Extension Points

  1. Custom Serialization:

    • Override Symfony’s serializer for Laravel-specific types:
      $serializer = new \Symfony\Component\Serializer\Serializer([
          new \Symfony\Component\Serializer\Normalizer\ObjectNormalizer(),
          new \App\Serializer\CarbonNormalizer(), // Custom normalizer
      ]);
      
  2. Message Deduplication:

    • Add a Laravel job to deduplicate messages:
      class DeduplicatePogocacheMessages implements ShouldQueue {
          public function handle(): void {
              $messages = Message::whereNull('pogocache_id')->get();
              foreach ($messages as $message) {
                  $pogocacheId = $this->store->save($message);
                  $message->update(['pogocache_id' => $pogocacheId]);
              }
          }
      }
      
  3. Multi-Region Support:

    • Route messages to regional Pogocache instances based on user location:
      public function getPogocacheUrl(): string {
          $region = request()->ip() === 'eu' ? 'eu' : 'us';
          return "https://pogocache-{$region}.com/api";
      }
      
  4. Analytics Integration:

    • Track message interactions with Laravel Scout or a custom analytics service:
      $messageStore->addListener(
          \Symfony\Component\Ai\Chat\Events\MessageRead::class,
          function ($event) {
              \App\Models\Analytics
      
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