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

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.

View on GitHub
Deep Wiki
Context7
// 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()]);
|                             | }
|                             | ```                                                                                                                                                                                                                   |

Step-by-Step Implementation Plan

  1. Assess Compatibility

    • Verify Laravel’s PHP version supports symfony/ai (e.g., PHP 8.1+).
    • Check for conflicts with existing symfony/* packages.
  2. Install Dependencies

    composer require symfony/ai symfony/ai-albert-platform
    
  3. Configure the Provider

    • Add Albert’s API key to .env:
      ALBERT_API_KEY=your_api_key_here
      
    • Configure the provider in 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',
      ],
      
  4. Implement Provider Abstraction

    • Extend the 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');
          }
      }
      
  5. Integrate with Laravel Services

    • Bind the provider in a service provider:
      $this->app->bind(AiProviderInterface::class, function ($app) {
          return new CustomAiProvider([
              new AlbertProvider($app['config']['ai.albert']),
              new OpenAiProvider($app['config']['ai.openai']),
          ]);
      });
      
  6. Build Use Case-Specific Features

    • Chatbot:
      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'];
      }
      
    • Semantic Search:
      public function generateEmbedding(string $text) {
          $ai = app(Client::class);
          $embedding = $ai->embeddings(['text' => $text, 'model' => 'all-minilm']);
          return $embedding['data'][0]['embedding'];
      }
      
  7. Add Error Handling and Retries

    • Use Laravel’s 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);
          }
      }
      
  8. Test and Benchmark

    • Write unit/integration tests for provider abstraction.
    • Benchmark latency/cost against OpenAI using Laravel’s benchmark() helper:
      $time = benchmark(function () {
          $ai->complete(['prompt' => 'benchmark']);
      });
      
  9. Deploy and Monitor

    • Roll out in stages (e.g., non-critical features first).
    • Monitor latency, cost, and error rates via Laravel’s logging or third-party tools (e.g., Datadog).

## 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)
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/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
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