PHP code example of xbnz / google-gemini-api

1. Go to this page and download the library: Download xbnz/google-gemini-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xbnz / google-gemini-api example snippets


// Laravel example

namespace App\Providers;

clsss AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(GoogleOAuth2Interface::class, function (Application $app) {
            return new GoogleOAuth2Service(
                logger: $app->make(LoggerInterface::class)
            );
        });

        $this->app->bind(GoogleAIPlatformInterface::class, function (Application $app) {
            return new GoogleAIPlatformService(
                (new GoogleAIPlatformConnector(
                    $app->make('config')->get('services.google_ai_platform.project_id'),
                    $app->make('config')->get('services.google_ai_platform.region'),
                ))->authenticate(
                    new TokenAuthenticator(
                        $app->make(GoogleOAuth2Interface::class)->token(
                            new TokenRequestDTO(
                                googleServiceAccount: new GoogleServiceAccount(
                                    $app->make('config')->get('services.google_ai_platform.client_email'),
                                    $app->make('config')->get('services.google_ai_platform.private_key'),
                                ),
                                scope: 'https://www.googleapis.com/auth/cloud-platform',
                                issuedAt: CarbonImmutable::now(),
                                expiration: CarbonImmutable::now()->addHour()
                            )
                        )->accessToken
                    )
                ),
                $app->make('log')
            );
        });
    }
}

namespace App\Console\Commands;

class SomeCommand
{
    public function __construct(
        private readonly AIPlatformInterface $aiPlatformService
    ) {}

    public function handle(): void
    {
        $response = $this->aiPlatformService->generateContent(
            new GenerateContentRequestDTO(
                'publishers/google/models/gemini-experimental',
                Collection::make([
                    new ContentDTO(
                        Role::User,
                        Collection::make([
                            new TextPart('Explain what is happening in the image'),
                            new BlobPart(
                                'image/jpeg',
                                'base64 image...',
                            )
                        ])
                    ),
                    new ContentDTO(
                        Role::Model,
                        Collection::make([
                            new TextPart('Sure! This is an image of a cat.'),
                        ]),
                    ),
                    new ContentDTO(
                        Role::User,
                        Collection::make([
                            new TextPart('What color is the cat?'),
                        ]),
                    ),
                    // and so on...
                ])
                Collection::make([
                    new SafetySettings(HarmCategory::HarmCategoryHarassment, SafetyThreshold::BlockOnlyHigh),
                    new SafetySettings(HarmCategory::HarmCategoryHateSpeech, SafetyThreshold::BlockOnlyHigh),
                    new SafetySettings(HarmCategory::HarmCategorySexuallyExplicit, SafetyThreshold::BlockOnlyHigh),
                    new SafetySettings(HarmCategory::HarmCategoryDangerousContent, SafetyThreshold::BlockOnlyHigh),
                ]),
                systemInstructions: Collection::make([
                    new TextPart('Your instructions here...'),
                ]),
                generationConfig: new GenerationConfig(...) // Optional
            )
        );
        
        if ($response->finishReason->consideredSuccessful() === false) {
            // Handle the model not being able to generate content (probably due to unsafe content)
        }
        
        // Do something with the healthy response
        $response->usage->promptTokenCount;
        $modelResponse = $response
            ->content
            ->parts
            ->sole(fn(PartContract $part) => $part instanceof TextPart) // There should only be one TextPart::class in a model response (for now)
            ->text;
    }
}

namespace App\Providers;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(GoogleAIPlatformInterface::class, function (Application $app) {
            return new GoogleAIPlatformService(
                (new GoogleAIPlatformConnector(...))->authenticate(new MyCustomAuthenticator),
            );
        });
    }
}

namespace App\Providers;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
          $this->app->bind(GoogleAIPlatformInterface::class, function (Application $app) {
            return new GoogleAIPlatformService(
                (new GoogleAIPlatformConnector(...))->authenticate(
                    new TokenAuthenticator(
                        $app->make('cache')->remember(
                            'google_api_platform_token',
                            CarbonImmutable::now()->addMinutes(60),
                            function () use ($app) {
                                return $app->make(GoogleOAuth2Interface::class)->token(
                                    new TokenRequestDTO(
                                        googleServiceAccount: new GoogleServiceAccount(
                                            $app->make('config')->get('services.google_ai_platform.client_email'),
                                            $app->make('config')->get('services.google_ai_platform.private_key'),
                                        ),
                                        scope: 'https://www.googleapis.com/auth/cloud-platform',
                                        issuedAt: CarbonImmutable::now(),
                                        expiration: CarbonImmutable::now()->addHour()
                                    )
                                )->accessToken;
                            }
                        ),
                    )
                ),
                $app->make('log')
            );
        });
    }
}

namespace App\Console\Commands;

class SomeCommand
{
    public function handle(): void
    {
        $service = new GoogleAIPlatformService(
            new GoogleAIPlatformConnector(...),
            new MyCustomLogger
        );
        
        try {
            $response = $service->generateContent(...);
        } catch (GoogleAIPlatformException $e) {
            // Handle the exception
        }
        
        // At this point, the logger will have logged the exception
    }
}

namespace App\Console\Commands;

class SomeCommand
{
    public function __construct(
        private readonly GoogleAIPlatformInterface $aiPlatform
    ) {}

    public function handle(): void
    {
        $this->aiPlatform->generateContent(
            requestDto: ...,
            beforeRequest: function (Request $request) {
                $request->headers()->merge([
                    'X-Custom-Header' => 'Value'
                ]);
                
                return $request;
            },
            afterResponse: function (Response $response) {
                // Return your own DTO or do something with the response
                
                return $response;
            }
        )
    }
}

namespace App\Providers;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(GoogleAIPlatformInterface::class, function (Application $app) {
            $connector = new GoogleAIPlatformConnector(...);
            $connector->authenticate(...)
            $connector->sender()->getHandlerStack()->push(
                GuzzleRetryMiddleware::factory([
                    'max_retry_attempts' => 5,
                    'retry_on_status' => [429],
                ])
            )
        
            return new GoogleAIPlatformService(
                $connector
            );
        });
    }
}


namespace App\Console\Commands;

use XbNz\Gemini\OAuth2\GoogleOAuth2Interface;

class SomeCommand
{
    public function __construct(
        private readonly GoogleOAuth2Interface $googleOAuth2Service
    ) {}

    public function handle(): void
    {
        $response = $this->googleOAuth2Service->token(...);
    }
}

namespace Tests\Feature;

use Tests\TestCase;
use XbNz\Gemini\OAuth2\DataTransferObjects\Requests\TokenRequestDTO;
use XbNz\Gemini\OAuth2\GoogleOAuth2ServiceFake;

class SomeCommandTest extends TestCase
{
    public function test_it_works(): void
    {
        // Swapping the real service with the fake one in the Laravel container
        $this->app->swap(GoogleOAuth2Interface::class, $fake = new GoogleOAuth2ServiceFake);
        
        // Basic testing helpers
        $fake->alwaysReturnToken(...);
        $fake->assertTokenRequestCount(...);
        
        // Asserting against requests
        $fake->assertTokenRequest(function (TokenRequestDTO) {
            return $dto->grantType === 'urn:ietf:params:oauth:grant-type:jwt-bearer';
        });
    }
}