Gemini PHP

repository·main·Indexed 19 days ago

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

A community-maintained PHP client for the Google Gemini AI API. Supports multimodal input, function calling, grounding with Google Search, structured JSON output, code execution, and context caching. Requires PHP 8.1+ and a PSR-18 compliant HTTP client. Version 2.0 is designed for the Gemini v1beta API.

Tokens
11.3K
Snippets
39
Records
44
Agent score
65%

What's inside google-gemini-php-client

  1. How Code Execution works

    main

    By enabling the CodeExecution tool, Gemini can generate and run code (like Python) to solve complex tasks. You can inspect the response parts to access the executableCode (the code generated) and the codeExecutionResult (the output of the execution).

    use Gemini\Data\CodeExecution;
    use Gemini\Data\Tool;
    
    $response = $client
        ->generativeModel(model: 'gemini-2.0-flash')
        ->withTool(new Tool(codeExecution: CodeExecution::from()))
        ->generateContent('What is the sum of the first 50 prime numbers?');
    
    foreach ($response->parts() as $part) {
        if ($part->executableCode !== null) {
            echo "Code: " . $part->executableCode->code . "\n";
        }
        if ($part->codeExecutionResult !== null) {
            echo "Output: " . $part->codeExecutionResult->output . "\n";
        }
    }
  2. How Function Calling works

    main

    Function calling allows the model to request the execution of custom functions. You define these using FunctionDeclaration within a Tool. When the model returns a FunctionCall, you execute your local logic and send the FunctionResponse back to the model via sendMessage() to complete the turn.

    // 1. Define the tool
    $chat = $client
        ->generativeModel(model: 'gemini-2.0-flash')
        ->withTool(new Tool(
            functionDeclarations: [
                new FunctionDeclaration(
                    name: 'addition',
                    description: 'Performs addition',
                    parameters: new Schema(
                        type: DataType::OBJECT,
                        properties: [
                            'number1' => new Schema(type: DataType::NUMBER, description: 'First number'),
                            'number2' => new Schema(type: DataType::NUMBER, description: 'Second number'),
                        ],
                        required: ['number1', 'number2']
                    )
                )
            ]
        ))
        ->startChat();
    
    // 2. Send message and handle call
    $response = $chat->sendMessage('What is 4 + 3?');
    if ($response->parts()[0]->functionCall !== null) {
        $functionResponse = handleFunctionCall($response->parts()[0]->functionCall);
        $response = $chat->sendMessage($functionResponse);
    }
    
    echo $response->text();
  3. How System Instructions work

    main

    System instructions allow you to define the persona, behavior, and constraints of the model before the conversation starts. This is done using withSystemInstruction(). You can combine these with other configurations like GenerationConfig to create specialized agents (e.g., a JSON API agent).

    use Gemini\Data\Content;
    
    $response = $client
        ->generativeModel(model: 'gemini-2.0-flash')
        ->withSystemInstruction(
            Content::parse('You are a helpful assistant that always responds in the style of a pirate.')
        )
        ->generateContent('Tell me about PHP programming');
    
    echo $response->text();
  4. How multi-turn conversations (Chat) work

    main

    To build a conversational interface, use startChat(). You can initialize the chat with a history of Gemini\Data\Content objects. Subsequent messages are sent using sendMessage(). For streaming responses, use streamSendMessage().

    use Gemini\Data\Content;
    use Gemini\Enums\Role;
    
    $chat = $client
        ->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();
  5. How Thinking Mode works

    main

    For models like Gemini 2.0 that support thinking mode, you can enable it via ThinkingConfig in the GenerationConfig. This allows you to see the model's reasoning process. You can check if a part contains the reasoning by inspecting $part->thought === true.

    use Gemini\Data\GenerationConfig;
    use Gemini\Data\ThinkingConfig;
    
    $response = $client
        ->generativeModel(model: 'gemini-2.0-flash-thinking-exp')
        ->withGenerationConfig(
            new GenerationConfig(
                thinkingConfig: new ThinkingConfig(
                    includeThoughts: true,
                    thinkingBudget: 1024
                )
            )
        )
        ->generateContent('Solve this logic puzzle...');
    
    foreach ($response->candidates[0]->content->parts as $part) {
        if ($part->thought === true) {
            echo "Model's thinking: " . $part->text . "\n";
        } else if ($part->text !== null) {
            echo "Final answer: " . $part->text . "\n";
        }
    }
  6. Install Gemini PHP via Composer

    main

    Install the Gemini PHP client using Composer. Ensure your environment meets the prerequisite of PHP 8.1+.

    If your project does not already have a PSR-18 compliant HTTP client integrated, you must also install a client like Guzzle to allow the library to make requests.

    composer require google-gemini-php/client
    # If you don't have a PSR-18 client installed:
    composer require guzzlehttp/guzzle
  7. 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. Key operations include:

    • upload(): Upload a file and wait for its state to become complete().
    • list(): List uploaded files.
    • metadataGet(): Retrieve metadata for a specific file.
    • delete(): Remove a file.
    use Gemini\Enums\FileState;
    use Gemini\Enums\MimeType;
    
    $files = $client->files();
    $meta = $files->upload(
        filename: 'video.mp4',
        mimeType: MimeType::VIDEO_MP4,
        displayName: 'Video'
    );
    
    // Wait for processing
    do {
        sleep(2);
        $meta = $files->metadataGet($meta->uri);
    } while (!$meta->state->complete());
    
    if ($meta->state == FileState::Failed) {
        die("Upload failed");
    }
  8. Basic Usage of the Gemini Client

    main

    To interact with the Gemini API, initialize a client using Gemini::client($apiKey). You can then access generative models to generate content from text prompts.

    use Gemini;
    
    $yourApiKey = getenv('YOUR_API_KEY');
    $client = Gemini::client($yourApiKey);
    
    $result = $client->generativeModel(model: 'gemini-2.0-flash')->generateContent('Hello');
    $result->text(); // Hello! How can I assist you today?
  9. Use Context Caching

    main

    Context caching reduces costs and latency for requests with large amounts of shared context. You can create a cache using cachedContents()->create(), specifying a ttl (Time To Live) or an absolute expireTime. You can then use this cache in a model request via withCachedContent().

    use Gemini\Data\Content;
    
    // Create cache
    $cachedContent = $client->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 = $client
        ->generativeModel(model: 'gemini-2.0-flash')
        ->withCachedContent($cachedContent->name)
        ->generateContent('Explain the main function');
  10. Upgrade to Gemini PHP 2.0

    main

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

    Breaking Changes

    • Model Selection: The \Gemini\Enums\ModelType enum, as well as the helper methods $client->geminiPro() and $client->geminiFlash(), are deprecated. You should instead use the $client->generativeModel() method and pass the model string directly.
    • Enum Support: Methods that previously accepted ModelType now accept any BackedEnum.

    New Features in 2.0

    • Structured output
    • System instructions
    • File uploads
    • Function calling
    • Code execution
    • Grounding (Google Search, Google Maps, File Search)
    • Cached content
    • Thinking and Speech model configurations
    • URL context retrieval
    composer require google-gemini-php/client:^2.0
  11. Configure a custom Gemini Client

    main

    If you need to customize the client (e.g., changing the base URL, adding custom HTTP headers, or using a specific PSR-18 HTTP client), use the Gemini::factory() builder pattern.

    ```php
    use Gemini;
    
    $yourApiKey = getenv('YOUR_API_KEY');
    
    $client = Gemini::factory()
        ->withApiKey($yourApiKey)
        ->withBaseUrl('https://generativelanguage.example.com/v1beta')
        ->withHttpHeader('X-My-Header', 'foo')
        ->withQueryParam('my-param', 'bar')
        ->withHttpClient($guzzleClient = new \\