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

Client Laravel Package

google-gemini-php/client

Community-maintained PHP client for the Google Gemini API. Send text, images, and video; run multi-turn chat with streaming; generate images and speech; structured output, function calling, code execution, grounding/search, token counting, plus file and cached-content management.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require google-gemini-php/client:^2.7.4
    

    Verify the package loads in composer.json under require with the updated version.

  2. First Request Initialize the client with your API key (from Google AI Studio):

    use Google\Gemini\Client;
    
    $client = new Client('YOUR_API_KEY');
    
  3. Basic Usage Send a text generation request:

    $response = $client->generateText('What is Laravel?');
    echo $response->getText();
    
  4. Key Files

    • src/Client.php: Core client logic (updated with new tools support).
    • src/Exceptions/: Error handling classes.
    • src/Tools/: New directory for tool integrations (e.g., FileSearchTool, MapsTool).
    • config/gemini.php (if auto-generated): Updated configuration defaults.

Implementation Patterns

Workflows

  1. Streaming Responses Process large responses incrementally:

    $response = $client->generateText('Explain Laravel', ['stream' => true]);
    foreach ($response->stream() as $chunk) {
        echo $chunk->getText();
    }
    
  2. Multi-Turn Conversations Use sessionId for context:

    $sessionId = $client->startSession();
    $response = $client->generateText('Hello', ['sessionId' => $sessionId]);
    $followup = $client->generateText('Continue', ['sessionId' => $sessionId]);
    
  3. Image + Text Prompts Combine images and text:

    $response = $client->generateText(
        'Describe this image',
        ['imageUri' => 'https://example.com/image.jpg']
    );
    
  4. New: Tool-Based Prompts Leverage Google's new tools (e.g., file search, maps):

    // File Search Tool Example
    $response = $client->generateText(
        'Summarize this document: {fileSearch}',
        ['tools' => ['fileSearch' => new \Google\Gemini\Tools\FileSearchTool('doc.pdf')]]
    );
    
    // Maps Tool Example
    $response = $client->generateText(
        'Find restaurants near {maps}',
        ['tools' => ['maps' => new \Google\Gemini\Tools\MapsTool('New York')]]
    );
    
  5. Optional Thinking Budget Configure thinkingBudget as optional in ThinkingConfig:

    $response = $client->generateText(
        'Complex query',
        ['thinkingConfig' => new \Google\Gemini\ThinkingConfig(['optionalField' => 'value'])]
    );
    

Integration Tips

  • Laravel Service Provider Bind the client in AppServiceProvider:

    $this->app->singleton(Client::class, function ($app) {
        return new Client(config('services.gemini.key'));
    });
    
  • Request Caching Cache responses for repeated queries:

    $response = Cache::remember("gemini:{$prompt}", now()->addHours(1), function () use ($client, $prompt) {
        return $client->generateText($prompt);
    });
    
  • Error Handling Centralize exception handling:

    try {
        $response = $client->generateText('Risky prompt');
    } catch (Google\Gemini\Exception\RateLimitException $e) {
        // Retry logic or notify admin
    }
    
  • Tool-Specific Validation Validate tool inputs before sending:

    $fileTool = new \Google\Gemini\Tools\FileSearchTool('doc.pdf');
    if (!$fileTool->isValid()) {
        throw new \InvalidArgumentException('Invalid file for search tool');
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Never hardcode keys. Use Laravel’s .env:
      GEMINI_API_KEY=your_key_here
      
    • Restrict key permissions in Google Cloud Console.
  2. Rate Limits

    • Default: 60 requests/minute. Monitor usage via:
      $client->getRateLimitStatus();
      
    • Implement exponential backoff for retries.
  3. Session Management

    • sessionId expires after inactivity. Regenerate if stale:
      if (!$client->validateSession($sessionId)) {
          $sessionId = $client->startSession();
      }
      
  4. Payload Size Limits

    • Max 1MB for text/image prompts + tools. Validate input:
      $tools = ['fileSearch' => new \Google\Gemini\Tools\FileSearchTool('large_file.pdf')];
      if ($client->estimatePayloadSize($prompt, $tools) > 1_000_000) {
          throw new \InvalidArgumentException('Payload too large');
      }
      
  5. Tool-Specific Quotas

Debugging

  • Enable Verbose Logging

    $client = new Client('YOUR_KEY', [
        'debug' => true,
        'logger' => new \Monolog\Logger('gemini')
    ]);
    
  • Common Errors

    Error Class Cause Fix
    InvalidArgumentException Malformed prompt/tool Validate input/tool
    Google\Gemini\Exception\AuthError Invalid API key Check .env
    Google\Gemini\Exception\ServerError Gemini API downtime Retry with jitter
    Google\Gemini\Exception\ToolError Invalid tool configuration Validate tool inputs
  • Tool Debugging Use getToolErrors() to inspect tool-specific failures:

    try {
        $response = $client->generateText('Query with tools', ['tools' => $tools]);
    } catch (\Exception $e) {
        if (method_exists($e, 'getToolErrors')) {
            $errors = $e->getToolErrors();
            // Log or handle tool-specific errors
        }
    }
    

Extension Points

  1. Custom Prompt Templates Extend Google\Gemini\Prompt for reusable formats:

    class LaravelPrompt extends \Google\Gemini\Prompt {
        public function __construct(string $query) {
            parent::__construct("Laravel context: " . $query);
        }
    }
    
  2. Middleware for Requests Add preprocessing/validation:

    $client->setRequestMiddleware(function ($request) {
        $request->setHeader('X-Custom-Header', 'value');
    });
    
  3. Async Processing Use queues for long-running tasks:

    dispatch(new GenerateTextJob($prompt, $tools));
    
  4. Custom Tools Implement new tools by extending \Google\Gemini\Tool:

    class WeatherTool extends \Google\Gemini\Tool {
        public function __construct(string $location) {
            $this->setInput(['location' => $location]);
        }
    }
    
  5. Thinking Budget Configuration Customize ThinkingConfig for advanced use cases:

    $config = new \Google\Gemini\ThinkingConfig([
        'optionalField' => 'value', // Now optional
        'maxOutputTokens' => 1000,
    ]);
    
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