google-gemini-php/client

⚡️ Gemini PHP is a community-maintained PHP API client that allows you to interact with the Gemini AI API.

What is Gemini PHP?

Gemini PHP is a community-maintained PHP library that lets you talk to Google's Gemini API from your PHP code. It's a client—a set of tools that handles the communication details so you can focus on building your app.

It supports a wide range of Gemini's capabilities, including:

  • Text, image, video, audio, and document input – send prompts with mixed media.
  • Streaming – get responses piece by piece instead of waiting for the whole thing.
  • Chat sessions – keep a conversation history across multiple turns.
  • Structured output – force the model to return JSON or a specific enum value.
  • Function calling – let the model invoke your own PHP functions.
  • Built-in tools – Google Search, Google Maps, URL context, File Search, and code execution.
  • Image and speech generation – create images or spoken audio.
  • Thinking models – models that can reason before answering.
  • File management – upload, list, and delete files.
  • Context caching – reuse context to save cost and latency.
  • File search stores – manage searchable document collections.
  • Embeddings – convert text into numerical vectors.
  • Model listing – see which models your API key can access.
  • A fake client – for testing without hitting the real API.

Prerequisites

  • PHP 8.2 or higher

Installation

Install via Composer:

composer require google-gemini-php/client

You also need a PSR-18 HTTP client (like Guzzle) if your project doesn't already have one:

composer require guzzlehttp/guzzle

Getting an API Key

You need a Gemini API key. Create one in Google AI Studio.

Basic Usage

Create a client with your API key and ask a model a question:

use Gemini;

$yourApiKey = getenv('YOUR_API_KEY');
$client = Gemini::client($yourApiKey);

$result = $client->generativeModel(model: 'gemini-2.5-flash')->generateContent('Hello');
$result->text(); // "Hello! How can I assist you today?"

You can also customize the client's base URL, headers, query parameters, or HTTP client using a factory.

Key Features (with examples from the README)

Text and Image Input

Send a text prompt along with an image (as a base64-encoded blob):

$result = $client->generativeModel(model: 'gemini-2.5-flash')->generateContent([
    'What is this picture?',
    new Blob(mimeType: MimeType::IMAGE_JPEG, data: base64_encode(file_get_contents('scones.jpg')))
]);

Video Input

Use an uploaded video file URI:

$result = $client->generativeModel(model: 'gemini-2.5-flash')->generateContent([
    'What is this video?',
    new UploadedFile(fileUri: $meta->uri, mimeType: MimeType::VIDEO_MP4)
]);

Media Resolution

Control token usage and detail level for images, videos, and documents—either globally or per part.

Image Generation

Generate images with a dedicated image model, setting aspect ratio and size:

$response = $client->generativeModel(model: 'gemini-2.5-flash-image')
    ->withGenerationConfig(new GenerationConfig(imageConfig: new ImageConfig(aspectRatio: '16:9', imageSize: '2K')))
    ->generateContent('Draw a futuristic city');

Chat Sessions

Start a chat with history and send messages:

$chat = $client->generativeModel(model: 'gemini-2.5-flash')->startChat(history: [...]);
$response = $chat->sendMessage('Create a story set in a quiet village in 1600s France');

Streaming

Get partial results as they're generated:

$stream = $client->generativeModel(model: 'gemini-2.5-flash')->streamGenerateContent('Write a long story');
foreach ($stream as $response) {
    echo $response->text();
}

Structured Output

Force JSON output with a schema:

$result = $client->generativeModel(model: 'gemini-2.5-flash')
    ->withGenerationConfig(new GenerationConfig(
        responseMimeType: ResponseMimeType::APPLICATION_JSON,
        responseSchema: new Schema(...)
    ))
    ->generateContent('List 5 popular cookie recipes');
$result->json();

Function Calling

Define functions the model can call, and handle the calls in your code:

$chat = $client->generativeModel(model: 'gemini-2.5-flash')
    ->withTool(new Tool(functionDeclarations: [...]))
    ->startChat();
$response = $chat->sendMessage('What is 4 + 3?');
// handle the function call, then send the response back

Built-in Tools

  • Google Search – ground answers with web search.
  • Google Maps – use location data.
  • URL Context – fetch content from a URL.
  • File Search – search over your uploaded documents.
  • Code Execution – let the model run code.

File Management

Upload, list, get metadata, and delete files.

Cached Content

Create, list, update, and delete cached content to reuse context.

File Search Stores

Create and manage searchable document collections.

Embeddings

Generate vector representations of text.

Models

List all models available to your API key, or get details about a specific one.

Testing

Gemini PHP ships with a fake client so you can test your code without making real API calls.

Upgrade to 2.0

Version 2.0 works only with the Gemini v1beta API and adds features like structured output, system instructions, file uploads, function calling, and more. Some older methods (like geminiPro() and geminiFlash()) are deprecated; use generativeModel() with a model string instead.

Troubleshooting

The README includes sections on error handling, empty responses, and timeouts.


This explanation is based solely on the provided README. For full details, code examples, and the latest updates, refer to the project's repository.

Related

  • Project
  • Project
  • Project
  • Project
  • Project