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.
Install the Package Add the package via Composer in your Laravel project:
composer require symfony/ai-mistral-platform
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();
},
],
Configure Mistral API Key
Store your Mistral API key in Laravel’s .env:
MISTRAL_API_KEY=your_api_key_here
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();
}
}
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);
}
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]);
}
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;
}
}
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());
}
}
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();
}
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);
}
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',
],
],
Real-Time Chatbot Integration
ChatCompletion for interactive chat interfaces.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();
}
});
}
Batch Embedding Generation
public function generateBatchEmbeddings(array $texts)
{
foreach ($texts as $text) {
GenerateEmbeddingJob::dispatch($text);
}
}
Hybrid Search with Embeddings
public function searchDocuments(string $query)
{
$queryEmbedding = $this->generateEmbedding($query);
return $this->searchEngine->search($queryEmbedding, limit: 5);
}
Fallback Logic for Multi-Provider
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);
}
}
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!');
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;
}
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();
});
}
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));
}
Testing with Mocks
Mock the MistralClient in tests to avoid hitting the API:
use Symfony\Ai\Mistral\MistralClient;
use Symfony\Ai\M
How can I help you explore Laravel packages today?