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 Mistral Platform Laravel Package

symfony/ai-mistral-platform

Symfony AI bridge for the Mistral platform. Integrates Mistral’s API (including chat completions) into Symfony AI, enabling easy use of Mistral models in Symfony applications with standard client abstractions and tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package Add the package via Composer in your Laravel project:

    composer require symfony/ai-mistral-platform
    
  2. Set Up HTTP Client Bind the Symfony HTTP client to Laravel’s container (if not already configured):

    // config/app.php
    'providers' => [
        // ...
        Symfony\Contracts\HttpClient\HttpClientInterface::class => function ($app) {
            return \Symfony\Contracts\HttpClient\HttpClient::create();
        },
    ],
    
  3. Configure Mistral API Key Store your Mistral API key in Laravel’s .env:

    MISTRAL_API_KEY=your_api_key_here
    
  4. First Use Case: Chat Completion Create a simple service to interact with Mistral’s chat endpoint:

    use Symfony\Ai\Mistral\MistralClient;
    use Symfony\Ai\Mistral\ChatCompletion;
    
    class MistralChatService
    {
        public function __construct(private MistralClient $client)
        {
        }
    
        public function ask(string $question): string
        {
            $response = $this->client->chatCompletion(
                new ChatCompletion('mistral-tiny', $question)
            );
            return $response->getContent();
        }
    }
    
  5. Register the Service Bind the MistralClient and MistralChatService in a Laravel service provider:

    use Symfony\Ai\Mistral\MistralClient;
    
    public function register()
    {
        $this->app->bind(MistralClient::class, function ($app) {
            return new MistralClient(
                $app->make(\Symfony\Contracts\HttpClient\HttpClientInterface::class),
                $app['config']['services.mistral.api_key']
            );
        });
    
        $this->app->bind(MistralChatService::class);
    }
    
  6. Use in a Controller Inject the service into a controller and call it:

    use MistralChatService;
    
    public function askQuestion(Request $request, MistralChatService $chatService)
    {
        $response = $chatService->ask($request->input('question'));
        return response()->json(['answer' => $response]);
    }
    

Implementation Patterns

Usage Patterns

  1. Provider Abstraction for Multi-Provider Support Leverage the Provider abstraction to route requests dynamically between Mistral and other AI providers (e.g., OpenAI):

    use Symfony\Ai\Provider\ProviderInterface;
    use Symfony\Ai\Provider\MistralProvider;
    
    class AiProviderRouter
    {
        public function __construct(
            private ProviderInterface $mistralProvider,
            private ProviderInterface $openAiProvider
        ) {}
    
        public function getProviderForModel(string $model): ProviderInterface
        {
            return str_starts_with($model, 'mistral-')
                ? $this->mistralProvider
                : $this->openAiProvider;
        }
    }
    
  2. Streaming Responses with Laravel Queues Process streaming responses (DeltaInterface) asynchronously using Laravel Queues:

    use Symfony\Ai\Mistral\MistralClient;
    use Symfony\Ai\Mistral\ChatCompletion;
    use Symfony\Component\Ai\Streaming\StreamingResponse;
    
    public function streamChatResponse(MistralClient $client, string $question)
    {
        $response = $client->chatCompletion(
            new ChatCompletion('mistral-tiny', $question)
        );
    
        foreach ($response->getStream() as $delta) {
            // Dispatch a job to process each delta
            ProcessStreamDelta::dispatch($delta->getContent());
        }
    }
    
  3. Embeddings for Semantic Search Use Mistral’s embeddings for document similarity or search:

    use Symfony\Ai\Mistral\EmbeddingClient;
    
    public function generateEmbedding(EmbeddingClient $client, string $text): array
    {
        $embedding = $client->embed($text);
        return $embedding->getEmbedding();
    }
    
  4. Error Handling with Uniform Exceptions Catch Mistral-specific errors uniformly using Symfony AI’s shared trait:

    use Symfony\Component\Ai\Exception\AiException;
    
    try {
        $response = $client->chatCompletion($completion);
    } catch (AiException $e) {
        // Handle errors consistently across providers
        report($e);
        return response()->json(['error' => $e->getMessage()], 500);
    }
    
  5. Configuration Management Centralize Mistral configuration in Laravel’s config/services.php:

    'mistral' => [
        'api_key' => env('MISTRAL_API_KEY'),
        'base_uri' => env('MISTRAL_API_BASE_URI', 'https://api.mistral.ai/v1'),
        'timeout' => 30.0,
        'models' => [
            'chat' => 'mistral-tiny',
            'embedding' => 'mistral-embed',
        ],
    ],
    

Workflows

  1. Real-Time Chatbot Integration

    • Use ChatCompletion for interactive chat interfaces.
    • Stream responses to update UI dynamically (e.g., with Laravel Echo or Livewire).
    • Example:
      public function chat(Request $request)
      {
          $response = $this->client->chatCompletion(
              new ChatCompletion('mistral-tiny', $request->input('prompt'))
          );
      
          return response()->stream(function () use ($response) {
              foreach ($response->getStream() as $delta) {
                  echo $delta->getContent();
                  flush();
              }
          });
      }
      
  2. Batch Embedding Generation

    • Generate embeddings for large datasets using Laravel’s queue system:
      public function generateBatchEmbeddings(array $texts)
      {
          foreach ($texts as $text) {
              GenerateEmbeddingJob::dispatch($text);
          }
      }
      
  3. Hybrid Search with Embeddings

    • Combine Mistral embeddings with Laravel Scout or a custom search engine:
      public function searchDocuments(string $query)
      {
          $queryEmbedding = $this->generateEmbedding($query);
          return $this->searchEngine->search($queryEmbedding, limit: 5);
      }
      
  4. Fallback Logic for Multi-Provider

    • Implement a fallback mechanism when Mistral is unavailable:
      public function getCompletionWithFallback(string $model, string $prompt)
      {
          try {
              return $this->mistralProvider->complete($model, $prompt);
          } catch (AiException) {
              return $this->openAiProvider->complete('gpt-3.5-turbo', $prompt);
          }
      }
      

Integration Tips

  1. Laravel Facade for Cleaner Syntax Create a facade to simplify Mistral interactions:

    // app/Facades/Mistral.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class Mistral extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return 'mistral.client';
        }
    }
    

    Usage:

    use App\Facades\Mistral;
    
    $response = Mistral::chatCompletion('mistral-tiny', 'Hello, world!');
    
  2. Laravel Events for Observability Dispatch Laravel events for Mistral API calls to log or monitor usage:

    use Symfony\Component\Ai\Event\AiEventDispatcher;
    use App\Events\MistralApiCalled;
    
    public function __construct(private AiEventDispatcher $dispatcher)
    {}
    
    public function chatCompletion(string $model, string $prompt)
    {
        $response = $this->client->chatCompletion(new ChatCompletion($model, $prompt));
        $this->dispatcher->dispatch(new MistralApiCalled($response));
        return $response;
    }
    
  3. Caching Embeddings Cache embeddings to avoid redundant API calls:

    use Illuminate\Support\Facades\Cache;
    
    public function getEmbedding(string $text): array
    {
        return Cache::remember("embedding_{$text}", now()->addHours(1), function () {
            return $this->client->embed($text)->getEmbedding();
        });
    }
    
  4. Rate Limiting and Retries Use Laravel’s Illuminate\Cache\RateLimiter to manage API rate limits:

    use Illuminate\Cache\RateLimiter;
    
    public function __construct(private RateLimiter $limiter)
    {}
    
    public function safeChatCompletion(string $model, string $prompt)
    {
        $this->limiter->hit('mistral-chat', now()->addMinutes(1));
        return $this->client->chatCompletion(new ChatCompletion($model, $prompt));
    }
    
  5. Testing with Mocks Mock the MistralClient in tests to avoid hitting the API:

    use Symfony\Ai\Mistral\MistralClient;
    use Symfony\Ai\M
    
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