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

Laravel Gemini Laravel Package

hosseinhezami/laravel-gemini

Laravel package for integrating Google Gemini into your app. Send prompts, manage chats and responses, and work with text generation via a clean, developer-friendly API. Ideal for quickly adding AI features to Laravel projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require hosseinhezami/laravel-gemini
    php artisan vendor:publish --tag=gemini-config
    

    Add GEMINI_API_KEY to .env.

  2. First Use Case: Text Generation

    use HosseinHezami\LaravelGemini\Facades\Gemini;
    
    $response = Gemini::text()
        ->prompt('Hello Gemini!')
        ->generate();
    
    echo $response->content();
    
  3. Key Files to Review

    • config/gemini.php (default models, API settings)
    • app/Providers/GeminiServiceProvider.php (service binding)
    • vendor/hosseinhezami/laravel-gemini/src/ (core logic)

Implementation Patterns

Core Workflows

  1. Builder Pattern for API Calls Chain methods for clarity and reusability:

    Gemini::text()
        ->model('gemini-2.5-flash')
        ->system('You are a helpful assistant.')
        ->prompt('Explain Laravel Eloquent.')
        ->temperature(0.5)
        ->generate();
    
  2. Multimodal Requests Combine text + files (e.g., document analysis):

    Gemini::text()
        ->upload('document', storage_path('docs/report.pdf'))
        ->prompt('Summarize this document.')
        ->generate();
    
  3. Streaming Responses For real-time UI updates:

    return response()->stream(function () {
        Gemini::text()
            ->prompt('Tell a story about AI.')
            ->stream(function ($chunk) {
                echo "data: " . json_encode($chunk) . "\n\n";
            });
    }, 200, ['Content-Type' => 'text/event-stream']);
    
  4. Caching Strategy Cache frequent queries to reduce API calls:

    // Cache a prompt configuration
    $cacheName = Gemini::text()
        ->prompt('Frequent question.')
        ->cache(ttl: '3600s');
    
    // Reuse cached config
    $response = Gemini::text()
        ->cachedContent($cacheName)
        ->generate();
    
  5. Dynamic API Key Management Switch keys per request (e.g., for multi-tenancy):

    Gemini::setApiKey('tenant-specific-key');
    $response = Gemini::text()->prompt('...')->generate();
    

Integration Tips

  • Queue Long-Running Tasks (e.g., video generation):
    Gemini::video()
        ->prompt('Generate a 10-second clip.')
        ->generate(); // Returns a job ID; poll later
    
  • Error Handling: Wrap calls in try-catch for HosseinHezami\LaravelGemini\Exceptions\GeminiException.
  • Rate Limiting: Use Laravel’s throttle middleware for API key protection.
  • Testing: Mock the Gemini facade in unit tests:
    $this->mock(Gemini::class)->shouldReceive('text')->andReturnSelf();
    

Gotchas and Tips

Pitfalls

  1. API Key Priority:

    • Runtime setApiKey() overrides .env/config. Verify keys dynamically if using multi-tenancy.
    • Fix: Log key sources during debugging:
      \Log::debug('API Key Source:', [
          'env' => config('gemini.api_key'),
          'runtime' => Gemini::getApiKey(),
      ]);
      
  2. File Upload Limits:

    • Gemini enforces file size/mime-type restrictions. Validate locally before upload:
      $allowedTypes = ['image/png', 'application/pdf'];
      if (!in_array($mime, $allowedTypes)) {
          throw new \InvalidArgumentException('Unsupported file type.');
      }
      
  3. Streaming Quirks:

    • Chunk size (config/gemini.stream.chunk_size) affects latency/performance. Test with 1024 (default) and adjust.
    • Debug: Use Gemini::text()->stream(function($chunk) { \Log::debug($chunk); }) to inspect chunks.
  4. Caching Caveats:

    • Cache names are auto-generated from builder params. Override with displayName for consistency:
      $cacheName = Gemini::text()->prompt('...')->cache(displayName: 'user_guide_summary');
      
    • Warning: Cached content expires per TTL. Clear stale caches manually if needed:
      Gemini::caches()->delete($cacheName);
      
  5. Model Compatibility:

    • Not all models support all features (e.g., gemini-2.5-flash lacks video generation). Check Gemini docs for model capabilities.
    • Tip: Use Gemini::text()->model('gemini-2.5-flash-lite') for cost-sensitive operations.

Debugging

  1. Enable Logging: Set logging: true in config/gemini.php to log requests/responses to storage/logs/gemini.log.

  2. Request Validation: Validate payloads before sending:

    $builder = Gemini::text()->prompt('...');
    \Log::debug('Request Payload:', $builder->getPayload());
    
  3. Rate Limit Headers: Check response->headers() for X-RateLimit-* headers to diagnose throttling.

  4. File Upload Debugging: Verify file URIs with:

    $fileId = Gemini::files()->upload('document', $path);
    \Log::debug('Uploaded File:', Gemini::files()->get($fileId));
    

Extension Points

  1. Custom Providers: Extend the HosseinHezami\LaravelGemini\Contracts\Provider interface to support non-Gemini APIs:

    class CustomProvider implements Provider {
        public function generateContent(array $payload) { ... }
    }
    

    Register in config/gemini.php:

    'providers' => [
        'custom' => [
            'class' => \App\Providers\CustomProvider::class,
        ],
    ],
    
  2. Response Transformers: Override response handling in a service provider:

    Gemini::extend(function ($app) {
        $app->singleton('gemini.response', function () {
            return new \App\Services\CustomResponseTransformer();
        });
    });
    
  3. Middleware for API Keys: Add middleware to validate keys per request:

    namespace App\Http\Middleware;
    use Closure;
    use HosseinHezami\LaravelGemini\Facades\Gemini;
    
    class ValidateGeminiKey {
        public function handle($request, Closure $next) {
            if (!$request->hasValidGeminiKey()) {
                Gemini::setApiKey($request->validated('api_key'));
            }
            return $next($request);
        }
    }
    
  4. Event Listeners: Listen for gemini.generated events to process responses:

    event(new \HosseinHezami\LaravelGemini\Events\ContentGenerated($response));
    
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.
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
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata