symfony/ai-albert-platform
Symfony AI bridge for the French government’s Albert Platform (OpenGateLLM). Connect Symfony apps to Albert’s OpenAI-compatible chat and embeddings endpoints, with links to the API reference, supported models, and upstream sources.
// services.php
$app->bind(\Symfony\Component\AI\Provider\AiProviderInterface::class, \Symfony\Component\AI\Provider\AlbertProvider::class);
``` |
| **HTTP Client** | Use Laravel’s **Guzzle client** or Symfony’s `HttpClient` (injected via the package). No additional setup required if using `symfony/ai`. |
| **Queues** | Offload AI calls to **Laravel queues** (e.g., `bus:dispatch`) for async processing. Example: |
| | ```php |
| | use Symfony\Component\AI\Client;
| | use Illuminate\Bus\Queueable;
|
| | class GenerateEmbedding implements ShouldQueue {
| | use Queueable;
|
| | public function handle(Client $aiClient) {
| | $embeddings = $aiClient->embeddings(['text' => 'sample']);
| | // Save to DB or cache
| | }
| | }
| | ``` |
| **Caching** | Cache embeddings or frequent API responses using Laravel’s cache (e.g., Redis). Example: |
| | ```php |
| | $embeddings = Cache::remember('embeddings:sample', now()->addHours(1), function () use ($aiClient) {
| | return $aiClient->embeddings(['text' => 'sample']);
| | });
| | ``` |
| **Routing** | Use Laravel’s **middleware** or **service providers** to route requests based on business logic (e.g., cost vs. quality). Example: |
| | ```php |
| | // app/Providers/AiServiceProvider.php
| | public function register() {
| | $this->app->bind(AiProviderInterface::class, function ($app) {
| | if ($app['config']['ai.provider'] === 'albert') {
| | return new AlbertProvider($app['config']['ai.albert_api_key']);
| | }
| | return new OpenAiProvider($app['config']['ai.openai_api_key']);
| | });
| | }
| | ``` |
| **Validation** | Validate AI inputs/outputs using Laravel’s **Form Requests** or **Pipes**. Example: |
| | ```php |
| | use Symfony\Component\AI\Exception\InvalidArgumentException;
|
| | public function rules() {
| | return [
| | 'prompt' => 'required|string|max:2000',
| | ];
| | }
|
| | public function withValidator($validator) {
| | $validator->after(function ($validator) {
| | if ($validator->errors()->any()) {
| | throw new InvalidArgumentException('Invalid AI request');
| | }
| | });
| | }
| | ``` |
| **Events** | Dispatch events for AI responses (e.g., `AiResponseGenerated`) to trigger side effects (e.g., logging, analytics). Example: |
| | ```php |
| | use Symfony\Component\AI\Event\AiResponseEvent;
| | use Illuminate\Support\Facades\Event;
|
| | $response = $aiClient->complete(['prompt' => 'sample']);
| | Event::dispatch(new AiResponseEvent($response));
| | ``` |
| **Testing** | Mock the `AiProviderInterface` in tests using Laravel’s **Mockery** or **PHPUnit**. Example: |
| | ```php |
| | $this->mock(AiProviderInterface::class, function ($mock) {
| | $mock->shouldReceive('complete')
| | ->once()
| | ->andReturn(['choices' => [['text' => 'mocked response']]]);
| | });
| | ``` |
| **Monitoring** | Log AI calls using Laravel’s **logging** or **Sentry**. Example: |
| | ```php |
| | use Illuminate\Support\Facades\Log;
|
| | try {
| | $response = $aiClient->complete(['prompt' => 'sample']);
| | Log::info('AI Response', ['response' => $response, 'model' => 'mistral-7b']);
| | } catch (\Exception $e) {
| | Log::error('AI Error', ['error' => $e->getMessage()]);
| | }
| | ``` |
Assess Compatibility
symfony/ai (e.g., PHP 8.1+).symfony/* packages.Install Dependencies
composer require symfony/ai symfony/ai-albert-platform
Configure the Provider
.env:
ALBERT_API_KEY=your_api_key_here
config/ai.php:
'providers' => [
'default' => \Symfony\Component\AI\Provider\AlbertProvider::class,
'fallback' => \Symfony\Component\AI\Provider\OpenAiProvider::class,
],
'albert' => [
'api_key' => env('ALBERT_API_KEY'),
'endpoint' => 'https://albert.api.etalab.gouv.fr',
],
Implement Provider Abstraction
AiProviderInterface to support dynamic routing:
use Symfony\Component\AI\Provider\AiProviderInterface;
class CustomAiProvider implements AiProviderInterface {
private $providers;
public function __construct(array $providers) {
$this->providers = $providers;
}
public function complete(array $options) {
foreach ($this->providers as $provider) {
try {
return $provider->complete($options);
} catch (\Exception $e) {
continue; // Fallback to next provider
}
}
throw new \RuntimeException('All AI providers failed');
}
}
Integrate with Laravel Services
$this->app->bind(AiProviderInterface::class, function ($app) {
return new CustomAiProvider([
new AlbertProvider($app['config']['ai.albert']),
new OpenAiProvider($app['config']['ai.openai']),
]);
});
Build Use Case-Specific Features
use Symfony\Component\AI\Client;
public function handleChatRequest(string $prompt) {
$ai = app(Client::class);
$response = $ai->complete(['prompt' => $prompt, 'model' => 'mistral-7b']);
return $response['choices'][0]['text'];
}
public function generateEmbedding(string $text) {
$ai = app(Client::class);
$embedding = $ai->embeddings(['text' => $text, 'model' => 'all-minilm']);
return $embedding['data'][0]['embedding'];
}
Add Error Handling and Retries
Spatie/Fluent for retries or custom middleware:
use Symfony\Component\AI\Exception\AiException;
use Illuminate\Http\Request;
use Illuminate\Routing\Middleware;
public function handle(Request $request, Closure $next) {
try {
return $next($request);
} catch (AiException $e) {
// Fallback logic or return cached response
return response()->json(['error' => 'AI service unavailable'], 503);
}
}
Test and Benchmark
benchmark() helper:
$time = benchmark(function () {
$ai->complete(['prompt' => 'benchmark']);
});
Deploy and Monitor
## Risks and Mitigations
| **Risk** | **Impact** | **Mitigation** |
|-----------------------------------|-------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Limited Model Variety** | Fewer models than OpenAI/HF. | Use **model routing** to prioritize available models (e.g., `mistral-7b` for cost, `llama-2` for quality)
How can I help you explore Laravel packages today?