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

symfony/ai-gemini-platform

Symfony AI bridge for Google’s Gemini platform. Integrates Gemini generateContent (incl. streaming) and embeddings APIs, linking to official docs and API reference. Includes licensed media fixtures for tests and points to the main Symfony AI repo for issues/PRs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require symfony/ai-gemini-platform
    

    Ensure your composer.json includes Symfony’s HTTP client and Messenger components if not already present.

  2. Configure the Client Add to config/services.php:

    'gemini' => [
        'api_key' => env('GEMINI_API_KEY'),
        'endpoint' => env('GEMINI_ENDPOINT', 'https://generativelanguage.googleapis.com/v1'),
        'default_model' => env('GEMINI_MODEL', 'gemini-3.1-pro-preview'),
    ],
    
  3. Bind the Client in Laravel In App\Providers\AppServiceProvider:

    use Symfony\Component\AI\Gemini\Client\GeminiClient;
    use Symfony\Component\AI\Gemini\Client\ModelClient;
    
    public function register()
    {
        $this->app->singleton(GeminiClient::class, function ($app) {
            return new GeminiClient(
                $app['config']['services.gemini.api_key'],
                $app['config']['services.gemini.endpoint']
            );
        });
    }
    
  4. First Use Case: Text Generation

    use Symfony\Component\AI\Gemini\Client\ModelClient;
    
    public function generateText()
    {
        $client = app(ModelClient::class);
        $response = $client->generateContent(
            'gemini-3.1-pro-preview',
            'Explain Laravel dependency injection in simple terms.'
        );
        return $response->getContent();
    }
    
  5. Environment Variables Add to .env:

    GEMINI_API_KEY=your_api_key_here
    GEMINI_MODEL=gemini-3.1-pro-preview
    

Implementation Patterns

Core Workflows

1. Text Generation (Synchronous)

$client = app(ModelClient::class);
$response = $client->generateContent(
    'gemini-3.1-pro-preview',
    'Write a blog post about Laravel AI integrations.'
);
$content = $response->getContent(); // Full response

2. Streaming Responses

Useful for real-time UIs (e.g., chatbots):

$response = $client->generateContent(
    'gemini-3.1-pro-preview',
    'Explain Laravel queues.',
    ['stream' => true]
);

foreach ($response->getDeltas() as $delta) {
    echo $delta->getContent(); // Process chunk-by-chunk
}

3. Multimodal Inputs (Images, PDFs, Audio)

use Symfony\Component\AI\Content\MultiPartContent;

$content = new MultiPartContent();
$content->addText('Summarize this document:');
$content->addFile('path/to/document.pdf');

$response = $client->generateContent(
    'gemini-3.1-pro-preview',
    $content
);

4. Embeddings for Vector Search

$embeddings = $client->batchEmbedContents(
    'models/embedding-001',
    ['text1', 'text2', 'text3']
);
// Store embeddings in PostgreSQL pgvector or Pinecone

5. Tool Use (Google Maps or Custom Tools)

$tools = [
    new ServerTool(
        'get_weather',
        'Fetch weather data for a location',
        ['parameters' => ['location' => 'string']],
        'http://your-api/weather'
    )
];

$response = $client->generateContent(
    'gemini-3.1-pro-preview',
    'What is the weather in Paris?',
    ['tools' => $tools]
);

6. Dynamic Model Routing (Provider Abstraction)

Configure in config/services.php:

'gemini' => [
    'providers' => [
        'default' => 'gemini-3.1-pro-preview',
        'flash' => 'gemini-3-flash-preview',
    ],
],

Use in code:

$client->generateContent('flash', 'Quick response needed.');

Integration Tips

Laravel-Specific Patterns

  1. Queue Background Jobs Wrap long-running Gemini calls (e.g., batch embeddings) in Laravel queues:

    use Illuminate\Support\Facades\Bus;
    
    Bus::dispatch(new GenerateEmbeddingsJob($texts));
    
  2. Laravel Events for Responses Trigger events after Gemini responses:

    event(new GeminiResponseGenerated($response));
    
  3. API Rate Limiting Use Laravel’s throttle middleware or Symfony’s RetryMiddleware:

    $client->withOptions([
        'middleware' => [
            new RetryMiddleware(),
            new ThrottleMiddleware(10), // 10 requests/minute
        ],
    ]);
    
  4. File Uploads Handle file uploads from Laravel requests:

    $file = $request->file('document');
    $content = new MultiPartContent();
    $content->addFile($file->path());
    
  5. Caching Responses Cache frequent Gemini responses using Laravel’s cache:

    $cacheKey = 'gemini:summary:' . md5($content);
    $response = Cache::remember($cacheKey, now()->addHours(1), function () use ($client, $content) {
        return $client->generateContent('gemini-3.1-pro-preview', $content);
    });
    

Gotchas and Tips

Pitfalls

  1. Streaming Chunk Handling

    • Issue: Streaming responses require manual iteration over DeltaInterface chunks. Laravel’s synchronous request handling may block.
    • Fix: Use Laravel’s queue or event system to process chunks asynchronously:
      $response->getDeltas()->map(function ($delta) {
          event(new GeminiChunkReceived($delta));
      });
      
  2. Multipart Content Size Limits

    • Issue: Large files (e.g., PDFs > 10MB) may fail with Gemini’s API limits.
    • Fix: Preprocess files (e.g., compress PDFs) or split into chunks:
      $content->addFile($file->path(), ['mime_type' => 'application/pdf', 'chunk_size' => 5_000_000]);
      
  3. Tool Use Errors

    • Issue: Tools may fail silently or return unclear errors.
    • Fix: Enable debug mode and handle ToolException:
      try {
          $response = $client->generateContent(..., ['tools' => $tools]);
      } catch (ToolException $e) {
          Log::error('Tool failed:', ['error' => $e->getToolErrors()]);
      }
      
  4. Preview Model Instability

    • Issue: Preview models (e.g., gemini-3.1-pro-preview) may change or deprecate.
    • Fix: Use a fallback mechanism:
      $models = ['gemini-3.1-pro-preview', 'gemini-3-flash-preview'];
      foreach ($models as $model) {
          try {
              return $client->generateContent($model, $prompt);
          } catch (ModelNotAvailableException) {
              continue;
          }
      }
      
  5. Binary Data Handling

    • Issue: Binary media (images/audio) may not serialize correctly.
    • Fix: Use base64 encoding for small files or stream directly:
      $content->addFile(base64_encode(file_get_contents($file)));
      

Debugging Tips

  1. Enable Symfony Debug Mode Add to config/app.php:

    'debug' => env('APP_DEBUG', true),
    

    This provides detailed error messages for Gemini API failures.

  2. Log Raw API Responses Wrap the client with a custom middleware to log requests/responses:

    $client->withOptions([
        'middleware' => [
            new LoggingMiddleware(),
        ],
    ]);
    
  3. Validate API Keys Ensure your GEMINI_API_KEY is correct and has permissions for the models you’re using.

  4. Check Rate Limits Gemini enforces rate limits. Monitor usage via:

    $client->getLastResponse()->getHeaders()['x-ratelimit-remaining'];
    

Extension Points

  1. Custom Providers Extend the Provider abstraction to add logic (e.g., cost-based model selection):
    class CostAwareProvider implements ProviderInterface
    {
        public function getModel(string $name, array $options): string
        {
            if ($options['cost_efficient'] ?? false) {
                return 'gemini-3-flash-preview';
            }
            return 'gemini-3.1-pro-preview';
        }
    }
    
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