Gemini PHP for Laravel

repository·main·Indexed 20 days ago

https://github.com/google-gemini-php/laravel

A community-maintained Laravel integration for the Gemini AI API. It provides tools to interact with Google's generative models, supporting text, image, and video input, as well as advanced features like structured JSON output, function calling, code execution, Google Search grounding, and speech generation. Compatible with PHP 8.1+ and Laravel 9, 10, 11, or 12.

Tokens
8.6K
Snippets
29
Records
30
Agent score
21%

What's inside google-gemini-php-laravel

  1. Implement Function Calling

    main

    Enable the model to call custom functions by defining them as Tool objects containing FunctionDeclarations.

    1. Define the function's name, description, and parameters using a Schema.
    2. Attach the tool to the model using withTool().
    3. When the model returns a functionCall in a response part, execute your local logic and send the result back to the model using sendMessage() with a Content object containing a FunctionResponse.
    // 1. Define the tool
    $tool = new Tool(functionDeclarations: [
        new FunctionDeclaration(
            name: 'addition',
            description: 'Performs addition',
            parameters: new Schema(
                type: DataType::OBJECT,
                properties: [
                    'number1' => new Schema(type: DataType::NUMBER),
                    'number2' => new Schema(type: DataType::NUMBER),
                ],
                required: ['number1', 'number2']
            )
        )
    ]);
    
    // 2. Start chat with tool
    $chat = Gemini::generativeModel(model: 'gemini-2.0-flash')->withTool($tool)->startChat();
    $response = $chat->sendMessage('What is 4 + 3?');
    
    // 3. Handle the call
    if ($response->parts()[0]->functionCall !== null) {
        $call = $response->parts()[0]->functionCall;
        // ... execute local logic ...
        $functionResponse = new Content(
            parts: [new Part(functionResponse: new FunctionResponse('addition', ['answer' => 7]))],
            role: Role::USER
        );
        $response = $chat->sendMessage($functionResponse);
    }
  2. Manage multi-turn conversations (Chat)

    main

    Build conversational flows using startChat(). You can provide an initial history array of Content objects (using Content::parse()) to set context. Use sendMessage() to send new messages and receive responses. The chat session maintains state automatically.

    use Gemini\Data\Content;
    use Gemini\Enums\Role;
    use Gemini\Laravel\Facades\Gemini;
    
    $chat = Gemini::generativeModel(model: 'gemini-2.0-flash')
        ->startChat(history: [
            Content::parse(part: 'The stories you write about what I have to say should be one line. Is that clear?'),
            Content::parse(part: 'Yes, I understand. The stories I write about your input should be one line long.', role: Role::MODEL)
        ]);
    
    $response = $chat->sendMessage('Create a story set in a quiet village in 1600s France');
    echo $response->text();
  3. Upgrade to Gemini PHP Laravel 2.0

    main

    Version 2.0 is designed to work exclusively with the Gemini v1beta API.

    Breaking Changes

    • \Gemini\Enums\ModelType enum is deprecated.
    • Gemini::geminiPro() and Gemini::geminiFlash() methods have been removed.
    • Recommendation: Use Gemini::generativeModel() and pass the model string directly. Methods that previously accepted ModelType now accept a BackedEnum.

    Upgrade Command

    composer require google-gemini-php/laravel:^2.0
  4. Manage files via the File API

    main

    The File API allows you to upload and manage files (up to 2GB per file, 20GB total per project) for use in prompts. Files are stored for 48 hours.

    • Upload: Use Gemini::files()->upload() with a filename and MIME type. Note that uploads are asynchronous; you must poll metadataGet() until the state is complete().
    • List: Use Gemini::files()->list() to see all files.
    • Metadata: Use Gemini::files()->metadataGet() to retrieve details about a specific file.
    • Delete: Use Gemini::files()->delete() to remove a file.
    use Gemini\Enums\FileState;
    use Gemini\Enums\MimeType;
    use Gemini\Laravel\Facades\Gemini;
    
    // Upload and poll for completion
    $files = Gemini::files();
    $meta = $files->upload(filename: 'video.mp4', mimeType: MimeType::VIDEO_MP4, displayName: 'Video');
    
    do {
        sleep(2);
        $meta = $files->metadataGet($meta->uri);
    } while (!$meta->state->complete());
    
    if ($meta->state == FileState::Failed) {
        // Handle error
    }
  5. Manage cached content

    main

    Context caching reduces costs and latency for large, frequently used inputs.

    • Create: Use Gemini::cachedContents()->create() with a ttl (e.g., '3600s') or an absolute expireTime.
    • List/Retrieve: Use list() or retrieve() to manage existing caches.
    • Update: Use update() to extend the TTL or change the expiration time.
    • Use: Pass the cache name to withCachedContent() when initializing a generative model.
    • Delete: Use delete() to remove a cache.
    use Gemini\Data\Content;
    use Gemini\Laravel\Facades\Gemini;
    
    // Create cache
    $cachedContent = Gemini::cachedContents()->create(
        model: 'gemini-2.0-flash',
        systemInstruction: Content::parse('You are an expert PHP developer.'),
        parts: ['Large codebase content...'],
        ttl: '3600s'
    );
    
    // Use cache
    $response = Gemini::generativeModel(model: 'gemini-2.0-flash')
        ->withCachedContent($cachedContent->name)
        ->generateContent('Explain the main function.');
  6. Install Gemini PHP for Laravel

    main

    Install the Gemini PHP Laravel package using Composer and then run the artisan install command to publish the configuration file.

    Running php artisan gemini:install creates config/gemini.php and appends the GEMINI_API_KEY placeholder to your .env file.

    composer require google-gemini-php/laravel
    php artisan gemini:install
  7. Configure Gemini API environment variables

    main

    After installation, you can configure the Gemini client using the following environment variables in your .env file:

    • GEMINI_API_KEY: Your API key from Google AI Studio.
    • GEMINI_BASE_URL: The base URL for the Gemini API.
    • GEMINI_REQUEST_TIMEOUT: The request timeout value.
    GEMINI_API_KEY=
    GEMINI_BASE_URL=
    GEMINI_REQUEST_TIMEOUT=
  8. Install Gemini for Laravel via Artisan

    main

    Run the gemini:install command to prepare the Gemini client for use in your Laravel application. This command automates the following setup steps:

    1. Publishes Configuration: Creates the config/gemini.php file using the package's service provider.
    2. Updates Environment Variables: Appends the GEMINI_API_KEY placeholder to your .env and .env.example files.

    After running this command, you must manually add your actual Gemini API key to your .env file.

    php artisan gemini:install
  9. Troubleshoot API timeouts

    main

    If you encounter timeouts when sending requests to the Gemini API, you can increase the request timeout duration. This can be configured in the config/gemini.php file using the request_timeout key or via the GEMINI_REQUEST_TIMEOUT environment variable.

    // In config/gemini.php
    return [
        'api_key' => env('GEMINI_API_KEY'),
        'base_url' => env('GEMINI_BASE_URL', 'https://generativelanguage.googleapis.com/v1beta/'),
        'request_timeout' => env('GEMINI_REQUEST_TIMEOUT', 30),
    ];
    # In .env
    GEMINI_REQUEST_TIMEOUT=60
  10. Generate structured JSON output

    main

    Constrain the model to return JSON by configuring GenerationConfig with responseMimeType: ResponseMimeType::APPLICATION_JSON and providing a Schema. This allows you to define the expected structure (types, properties, and required fields). Use $result->json() to retrieve the parsed data.

    use Gemini\Data\GenerationConfig;
    use Gemini\Data\Schema;
    use Gemini\Enums\DataType;
    use Gemini\Enums\ResponseMimeType;
    use Gemini\Laravel\Facades\Gemini;
    
    $result = Gemini::generativeModel(model: 'gemini-2.0-flash')
        ->withGenerationConfig(
            generationConfig: new GenerationConfig(
                responseMimeType: ResponseMimeType::APPLICATION_JSON,
                responseSchema: new Schema(
                    type: DataType::ARRAY,
                    items: new Schema(
                        type: DataType::OBJECT,
                        properties: [
                            'recipe_name' => new Schema(type: DataType::STRING),
                            'cooking_time_in_minutes' => new Schema(type: DataType::INTEGER)
                        ,
                        required: ['recipe_name', 'cooking_time_in_minutes'],
                    )
                )
            )
        )
        ->generateContent('List 5 popular cookie recipes with cooking time');
    
    $data = $result->json();
  11. Test API failures with Throwables

    main

    To test how your application handles API errors, you can provide a Throwable object (such as Gemini\Exceptions\ErrorException) to Gemini::fake(). This will cause the fake client to throw that exception when the request is made.

    use Gemini//Laravel/Facades/Gemini;
    use Gemini//Exceptions/ErrorException;
    
    Gemini::fake([
        new ErrorException([
            'message' => 'The model `gemini-basic` does not exist',
            'status' => 'INVALID_ARGUMENT',
            'code' => 400,
        ]),
    ]);
    
    // This call will now throw the ErrorException defined above
    Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('test');