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

google-gemini-php/laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require google-gemini-php/laravel
    php artisan vendor:publish --provider="GoogleGemini\Laravel\GeminiServiceProvider" --tag="config"
    
    • Publishes the config file at config/gemini.php.
  2. Configure API Key Add your Google Gemini API key to .env:

    GEMINI_API_KEY=your_api_key_here
    
    • Verify the key is loaded in config/gemini.php under api_key.
  3. First Use Case: Text Generation

    use GoogleGemini\Laravel\Facades\Gemini;
    
    $response = Gemini::chat()->text('What is Laravel?')->send();
    dd($response->content);
    
    • Outputs the AI-generated response for the prompt.

Where to Look First

  • Config File: config/gemini.php (API key, endpoint, and default settings).
  • Facade: GoogleGemini\Laravel\Facades\Gemini (primary entry point).
  • Usage Examples: README Usage Section (covers chat, image generation, and streaming).

Implementation Patterns

Core Workflows

  1. Basic Chat Requests

    $response = Gemini::chat()
        ->model('gemini-1.5-pro') // Optional: Specify model
        ->temperature(0.7)       // Optional: Adjust creativity
        ->send('Explain Laravel Eloquent ORM');
    
    • Chain methods for fine-tuning responses.
  2. Multi-Turn Conversations

    $chat = Gemini::chat()->start('Hello, I need help with Laravel.');
    $response = $chat->send('How do I use relationships?');
    $chat->addMessage($response); // Persist context
    
    • Useful for chatbots or interactive tools.
  3. Image Generation

    $response = Gemini::generate()
        ->prompt('A futuristic cityscape')
        ->size('1024x1024')
        ->send();
    
    • Returns a URL to the generated image.
  4. Streaming Responses

    Gemini::chat()->stream('Explain Laravel queues')
        ->onResponse(function ($chunk) {
            echo $chunk->text;
        });
    
    • Process responses incrementally (e.g., for real-time UIs).

Integration Tips

  • Service Layer: Wrap Gemini calls in a service class to abstract logic:
    class GeminiService {
        public function summarizeText(string $text): string {
            return Gemini::chat()->send("Summarize this: $text")->content;
        }
    }
    
  • Queue Jobs: Offload long-running requests (e.g., image generation) to queues:
    Gemini::generate()->prompt('Complex image')->dispatch();
    
  • Caching: Cache frequent responses (e.g., FAQs) using Laravel’s cache:
    $response = Cache::remember("gemini_faq_{$question}", now()->addHours(1), fn() =>
        Gemini::chat()->send($question)->content
    );
    

Gotchas and Tips

Pitfalls

  1. API Key Management

    • Never hardcode keys. Use Laravel’s .env and validate the key exists in config/gemini.php:
      if (empty(config('gemini.api_key'))) {
          throw new \RuntimeException('Gemini API key not configured.');
      }
      
    • Rotate keys periodically and update .env.
  2. Rate Limits

    • Gemini enforces usage limits. Handle 429 Too Many Requests:
      try {
          $response = Gemini::chat()->send('...');
      } catch (\GoogleGemini\Exceptions\RateLimitException $e) {
          retry()->times(3)->later(5)->try(fn() => $response);
      }
      
  3. Model Availability

    • Not all models are available in all regions. Verify supported models in the Gemini docs.
    • Defaults to gemini-pro; explicitly set if needed:
      Gemini::chat()->model('gemini-1.5-pro-latest');
      
  4. Streaming Quirks

    • Streaming may drop chunks if the connection is unstable. Implement retry logic for critical use cases.
    • Avoid long-running streams in CLI commands (use queues instead).

Debugging

  • Enable Debugging Set debug: true in config/gemini.php to log raw API responses:
    'debug' => env('GEMINI_DEBUG', false),
    
  • Validate Inputs Sanitize prompts to avoid malformed requests:
    $prompt = htmlspecialchars($userInput, ENT_QUOTES);
    
  • Error Handling Catch specific exceptions:
    try {
        $response = Gemini::chat()->send($prompt);
    } catch (\GoogleGemini\Exceptions\InvalidRequestException $e) {
        Log::error("Invalid prompt: {$e->getMessage()}");
    }
    

Extension Points

  1. Custom Responses Extend the GeminiResponse class to add domain-specific methods:

    class CustomGeminiResponse extends \GoogleGemini\Laravel\Responses\GeminiResponse {
        public function extractEntities(): array {
            // Custom logic to parse response for entities
        }
    }
    
    • Bind the custom class in the service provider.
  2. Middleware Add middleware to modify requests/responses globally:

    Gemini::extend(function ($gemini) {
        $gemini->macro('logRequest', function ($prompt) {
            Log::info("Gemini Prompt: {$prompt}");
            return $this;
        });
    });
    
    • Use in chains: Gemini::chat()->logRequest($prompt)->send().
  3. Testing Mock Gemini responses in tests using Laravel’s HTTP testing:

    $response = Gemini::fake()->chat()->thenReturn(
        new \GoogleGemini\Laravel\Responses\GeminiResponse(['content' => 'Mocked response'])
    );
    
    • Install google-gemini-php/laravel-testing for helpers.
  4. Webhooks For async operations (e.g., image generation), use Laravel’s queue:work with webhook callbacks:

    Gemini::generate()->prompt('...')->queue(function ($job, $response) {
        event(new GeminiImageGenerated($response->url));
    });
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui