PHPackages                             google-gemini-api-php/client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. google-gemini-api-php/client

ActiveLibrary[API Development](/categories/api)

google-gemini-api-php/client
============================

PHP API client for Google's Gemini API

1.0.2(1y ago)2205MITPHPPHP ^8.1

Since Sep 9Pushed 1y ago1 watchersCompare

[ Source](https://github.com/UsmanIlamdin/google-gemini-api-php)[ Packagist](https://packagist.org/packages/google-gemini-api-php/client)[ RSS](/packages/google-gemini-api-php-client/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (11)Versions (6)Used By (0)

 [![Gemini API PHP Client - Example](https://raw.githubusercontent.com/gemini-api-php/client/main/assets/example.png)](https://raw.githubusercontent.com/gemini-api-php/client/main/assets/example.png)

 [![Total Downloads](https://camo.githubusercontent.com/85e6c7b8b0678612b4d3b04d2d4acb2d25048df9a1cf3587c93001f0c387dc83/68747470733a2f2f7061636b61676973742e6f72672f7061636b616765732f676f6f676c652d67656d696e692d6170692d7068702f636c69656e742f7374617473)](https://packagist.org/packages/google-gemini-api-php/client) [![Latest Version](https://camo.githubusercontent.com/b01a554484cffaac3faa462b618f8e43e11375477396865b0fa15bff8d3ca2f5/68747470733a2f2f7061636b61676973742e6f72672f7061636b616765732f676f6f676c652d67656d696e692d6170692d7068702f636c69656e7423312e302e30)](https://packagist.org/packages/google-gemini-api-php/client) [![License](https://github.com/UsmanIlamdin/google-gemini-api-php/raw/master/LICENSE)](https://packagist.org/packages/google-gemini-api-php/client)

Gemini API PHP Gemini
=====================

[](#gemini-api-php-gemini)

Gemini API PHP Client allows you to use the Google's generative AI models, like Gemini Pro and Gemini Pro Vision.

*This library is not developed or endorsed by Google.*

- Usman IlamDin - **[github.com/usmanilamdin](https://github.com/usmanilamdin)**

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [How to use](#how-to-use)
    - [Basic text generation](#basic-text-generation)
    - [Text generation using cached content and file uploaded](#text-generation-using-cached-content-and-file-uploaded)
    - [Multimodal input](#multimodal-input)
    - [Chat Session (Multi-Turn Conversations)](#chat-session-multi-turn-conversations)
    - [Chat Session with history](#chat-session-with-history)
    - [Streaming responses](#streaming-responses)
    - [Streaming Chat Session](#streaming-chat-session)
    - [Tokens counting](#tokens-counting)
    - [Cached Content Resource](#cached-content-resource)
        - [create](#create)
        - [delete](#delete)
        - [get](#get)
        - [list](#list)
        - [patch](#patch)
    - [File Resource](#file-resource)
        - [delete](#delete-5)
        - [get](#get-5)
        - [list](#list-5)
    - [Media Resource](#media-resource)
        - [upload](#upload)
    - [Listing models](#listing-models)
    - [Advanced Usages](#advanced-usages)
        - [Safety Settings and Generation Configuration](#safety-settings-and-generation-configuration)
        - [Using your own HTTP client](#using-your-own-http-client)
        - [Using your own HTTP client for streaming responses](#using-your-own-http-client-for-streaming-responses)

Installation
------------

[](#installation)

> You need an API key to gain access to Google's Gemini API. Visit [Google AI Studio](https://makersuite.google.com/) to get an API key.

First step is to install the Gemini API PHP client with Composer.

```
composer require gemini-api-php/client
```

Gemini API PHP client does not come with an HTTP client. If you are just testing or do not have an HTTP client library in your project, you need to allow `php-http/discovery` composer plugin or install a PSR-18 compatible client library.

How to use
----------

[](#how-to-use)

### Basic text generation

[](#basic-text-generation)

```
use GeminiAPI\Gemini;
use GeminiAPI\Resources\Parts\TextPart;

$gemini = new Gemini('GEMINI_API_KEY');
$response = $gemini->geminiPro()->generateContent(
    new TextPart('PHP in less than 100 chars'),
);

print $response->text();
// PHP: A server-side scripting language used to create dynamic web applications.
// Easy to learn, widely used, and open-source.
```

### Text generation using cached content and file uploaded

[](#text-generation-using-cached-content-and-file-uploaded)

```
use GeminiAPI\Gemini;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\Resources\Parts\FilePart;

$gemini = new Gemini('GEMINI_API_KEY');
$response = $gemini->geminiPro15Flash001()->generateContentWithCache(
    ["cachedContent" => "cachedContents/n9l42h1iszbd"],
    new TextPart("Give me the summary of the file uploaded")
);

print $response->text();
// PHP: This will give the summary of the file uploaded
```

### Multimodal input

[](#multimodal-input)

> Image input modality is only enabled for Gemini Pro Vision model

```
use GeminiAPI\Gemini;
use GeminiAPI\Enums\MimeType;
use GeminiAPI\Resources\Parts\ImagePart;
use GeminiAPI\Resources\Parts\TextPart;

$gemini = new Gemini('GEMINI_API_KEY');
$response = $gemini->geminiProVision()->generateContent(
    new TextPart('Explain what is in the image'),
    new ImagePart(
        MimeType::IMAGE_JPEG,
        base64_encode(file_get_contents('elephpant.jpg')),
    ),
);

print $response->text();
// The image shows an elephant standing on the Earth.
// The elephant is made of metal and has a glowing symbol on its forehead.
// The Earth is surrounded by a network of glowing lines.
// The image is set against a starry background.
```

### Chat Session (Multi-Turn Conversations)

[](#chat-session-multi-turn-conversations)

```
use GeminiAPI\Gemini;
use GeminiAPI\Resources\Parts\TextPart;

$gemini = new Gemini('GEMINI_API_KEY');
$chat = $gemini->geminiPro()->startChat();

$response = $chat->sendMessage(new TextPart('Hello World in PHP'));
print $response->text();

$response = $chat->sendMessage(new TextPart('in Go'));
print $response->text();
```

```

This code will print "Hello World!" to the standard output.

```

```
package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}

This code will print "Hello World!" to the standard output.

```

### Chat Session with history

[](#chat-session-with-history)

```
use GeminiAPI\Gemini;
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\Parts\TextPart;

$history = [
    Content::text('Hello World in PHP', Role::User),
    Content::text(

        This code will print "Hello World!" to the standard output.
        TEXT,
        Role::Model,
    ),
];

$gemini = new Gemini('GEMINI_API_KEY');
$chat = $gemini->geminiPro()
    ->startChat()
    ->withHistory($history);

$response = $chat->sendMessage(new TextPart('in Go'));
print $response->text();
```

```
package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}

This code will print "Hello World!" to the standard output.

```

### Streaming responses

[](#streaming-responses)

> Requires `curl` extension to be enabled

In the streaming response, the callback function will be called whenever a response is returned from the server.

Long responses may be broken into separate responses, and you can start receiving responses faster using a content stream.

```
use GeminiAPI\Gemini;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\Responses\GenerateContentResponse;

$callback = function (GenerateContentResponse $response): void {
    static $count = 0;

    print "\nResponse #{$count}\n";
    print $response->text();
    $count++;
};

$gemini = new Gemini('GEMINI_API_KEY');
$gemini->geminiPro()->generateContentStream(
    $callback,
    [new TextPart('PHP in less than 100 chars')],
);
// Response #0
// PHP: a versatile, general-purpose scripting language for web development, popular for
// Response #1
//  its simple syntax and rich library of functions.
```

### Streaming Chat Session

[](#streaming-chat-session)

> Requires `curl` extension to be enabled

```
use GeminiAPI\Gemini;
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\Responses\GenerateContentResponse;

$history = [
    Content::text('Hello World in PHP', Role::User),
    Content::text(

        This code will print "Hello World!" to the standard output.
        TEXT,
        Role::Model,
    ),
];

$callback = function (GenerateContentResponse $response): void {
    static $count = 0;

    print "\nResponse #{$count}\n";
    print $response->text();
    $count++;
};

$gemini = new Gemini('GEMINI_API_KEY');
$chat = $gemini->geminiPro()
    ->startChat()
    ->withHistory($history);

$chat->sendMessageStream($callback, new TextPart('in Go'));
```

```
Response #0
package main

import "fmt"

func main() {

Response #1
    fmt.Println("Hello World!")
}

This code will print "Hello World!" to the standard output.

```

### Embed Content

[](#embed-content)

```
use GeminiAPI\Gemini;
use GeminiAPI\Enums\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$gemini = new Gemini('GEMINI_API_KEY');
$response = $gemini->embeddingModel(ModelName::Embedding)
    ->embedContent(
        new TextPart('PHP in less than 100 chars'),
    );

print_r($response->embedding->values);
// [
//    [0] => 0.041395925
//    [1] => -0.017692696
//    ...
// ]
```

Cached Content Resource
-----------------------

[](#cached-content-resource)

### create

[](#create)

Creates CachedContent resource.

This example uses the *Sherlock Jr. movie* video used in documentation. File was first uploaded with [media upload](#upload)

```
use GeminiAPI\Data\CachedContent;
use GeminiAPI\Data\Content;

$file = 'https://generativelanguage.googleapis.com/v1beta/files/7j0qhgcmeeqh';

$response = $gemini->cachedContents()->create(
    new CachedContent(
        model: 'models/gemini-1.5-flash-001',
        displayName: 'sherlock jr movie',
        systemInstruction: Content::createTextContent("You are an expert video analyzer, and your job is to answer the user\'s query based on the video file you have access to."),
        contents: [
            Content::createFileContent($file, 'video/mp4', 'user'),
        ],
        ttl: '3600s',
    ),
);

$response->model; // models/gemini-1.5-flash-001
$response->name; // cachedContents/lg5adbi62ykx
$response->displayName; // sherlock jr movie
$response->createTime->format('Y-m-d H:i:s'); // 2024-07-04 23:15:53
$response->updateTime->format('Y-m-d H:i:s'); // 2024-07-04 23:15:53
$response->usageMetadata->totalTokenCount; //
$response->expireTime->format('Y-m-d H:i:s'); // 2024-07-05 00:15:53

$response->toArray(); // ['model' => 'models/gemini-1.5-flash-001', ...]
```

Generate Content with a Cached ContentThe timeout for `generateContent` is set to 60s, request timeout to 120s. If your request is still exceeding these limits you may propose an increase.

```
use GeminiAPI\Data\Content;

$response = $gemini->geminiPro15Flash001()->generateContentWithCache(
            ["cachedContent" => "cachedContents/n9l42h1iszbd"],
            new TextPart("Give me the summary of the file uploaded")
        );

echo $response->text();
```

### delete

[](#delete)

Deletes CachedContent resource.

```
$response = $gemini->cachedContents()->delete('cachedContents/2wojeqz7srpu');

if ($response === true) {
    echo 'Successfully deleted the cached Content';
}
```

### get

[](#get)

Reads CachedContent resource.

```
$response = $gemini->cachedContents()->get('cachedContents/2wojeqz7srpu');

$response->model; // models/gemini-1.5-flash-001
$response->name; // cachedContents/2wojeqz7srpu
$response->displayName; // Repository Specialist
$response->createTime->format('Y-m-d H:i:s'); // 2024-07-04 23:15:53
$response->updateTime->format('Y-m-d H:i:s'); // 2024-07-04 23:15:53
$response->usageMetadata->totalTokenCount; // 259246
$response->expireTime->format('Y-m-d H:i:s'); // 2024-08-04 23:15:53

$response->toArray(); // ['model' => 'models/gemini-1.5-flash-001', ...]
```

### list

[](#list)

Lists CachedContents.

```
$response = $gemini->cachedContents()->list();

$response->nextPageToken; //

foreach ($response->cachedContents as $cachedContent) {
    $cachedContent->model; // models/gemini-1.5-flash-001
    $cachedContent->name; // cachedContents/2wojeqz7srpu
    $cachedContent->displayName; // Repository Specialist
    $cachedContent->createTime->format('Y-m-d H:i:s'); // 2024-07-04 23:15:53
    $cachedContent->updateTime->format('Y-m-d H:i:s'); // 2024-07-04 23:15:53
    $cachedContent->usageMetadata->totalTokenCount; // 259246
    $cachedContent->expireTime->format('Y-m-d H:i:s'); // 2024-10-28 17:02:31
}

$response->toArray(); // ['cachedContents' => [...], ...]
```

### patch

[](#patch)

Updates CachedContent resource (only expiration is updatable).

```
$response = $gemini->cachedContents()->patch([
    'name' => 'cachedContents/2wojeqz7srpu',
    'updateMask' => 'ttl',
    'cachedContent' => new CachedContent(
        ttl: '3600s'
    ),
]);

$response->model; // models/gemini-1.5-flash-001
$response->name; // cachedContents/2wojeqz7srpu
$response->displayName; // Repository Specialist
$response->createTime->format('Y-m-d H:i:s'); // 2024-07-04 23:15:53
$response->updateTime->format('Y-m-d H:i:s'); // 2024-07-05 07:02:21
$response->usageMetadata->totalTokenCount; // 259246
$response->expireTime->format('Y-m-d H:i:s'); // 2024-07-05 08:02:21

$response->toArray(); // ['model' => 'models/gemini-1.5-flash-001', ...]
```

File Resource
-------------

[](#file-resource)

### delete

[](#delete-1)

Deletes the `File`.

```
$response = $gemini->files()->delete('files/qrbxtbaehccw');
if ($response === true) {
    echo 'File deleted successfully';
}
```

### get

[](#get-1)

Gets the metadata for the given `File`.

```
$response = $gemini->files()->get('files/m8uuuytf6niz');

$response->name; // files/m8uuuytf6niz
$response->displayName; // Sample File 2
$response->mimeType; // image/jpeg
$response->sizeBytes; // 44485
$response->createTime->format('Y-m-d H:i:s'); // 2024-07-08 20:51:46
$response->updateTime->format('Y-m-d H:i:s'); // 2024-07-08 20:51:46
$response->expirationTime->format('Y-m-d H:i:s'); // 2024-07-10 20:51:46
$response->sha256Hash; // TZhZGZiMDUzMzM...
$response->uri; // https://generativelanguage.googleapis.com/v1beta/files/m8uuuytf6niz
$response->state->value; // ACTIVE

$response->toArray(); // ['name' => 'files/m8uuuytf6niz', ...]
```

### list

[](#list-1)

Lists the metadata for `File`s owned by the requesting project.

```
$response = $gemini->files()->list();

$response->nextPageToken; //

foreach ($response->files as $file) {
    $file->name; // files/qrbxtbaehccw
    $file->displayName; // Sample File
    $file->mimeType; // image/png
    $file->sizeBytes; // 357556
    $file->createTime->format('Y-m-d H:i:s'); // 2024-07-08 20:26:59
    $file->updateTime->format('Y-m-d H:i:s'); // 2024-07-08 20:26:59
    $file->expirationTime->format('Y-m-d H:i:s'); // 2024-07-10 20:26:59
    $file->sha256Hash; // NmI4NmM3M...
    $file->uri; // https://generativelanguage.googleapis.com/v1beta/files/qrbxtbaehccw
    $file->state->value; // ACTIVE
}

$response->toArray(); // ['files' => [...]]
```

Media Resource
--------------

[](#media-resource)

### upload

[](#upload)

Creates a `File`.

```
use GeminiAPI\Data\File;

# Example uses video downloaded from
# https://storage.googleapis.com/generativeai-downloads/data/Sherlock_Jr_FullMovie.mp4

$metaData = new File(
    displayName: 'Demo File'
);

# The file was excluded from commit due to impact it'd have on cloning this repo,
# download and change path, or can upload any file of choice
$response = $gemini->media()->upload(__DIR__ .'/files/Sherlock_Jr_FullMovie.mp4', $metaData);

$file = $response->file;
$file->name; // files/7j0qhgcmeeqh
$file->displayName; // Sherlock Jr. video
$file->mimeType; // video/mp4
$file->sizeBytes; // 331623233
$file->createTime->format('Y-m-d H:i:s'); // 2024-07-27 22:31:25
$file->updateTime->format('Y-m-d H:i:s'); // 2024-07-27 22:31:25
$file->expirationTime->format('Y-m-d H:i:s'); // 2024-07-29 22:31:25
$file->sha256Hash; // ZjAwNGM2ZjJiMzNlNjYxYzYwOTU1MzU3MDliYzUzMjY4ZDUzMjNlYzdhNTdlOGJjNGFlOTczNjJlZDM0MWI1Yg==
$file->uri; // https://generativelanguage.googleapis.com/v1beta/files/7j0qhgcmeeqh
$file->state->value; // PROCESSING

$response->toArray(); // ['file' => [...]]
```

### Tokens counting

[](#tokens-counting)

```
use GeminiAPI\Gemini;
use GeminiAPI\Resources\Parts\TextPart;

$gemini = new Gemini('GEMINI_API_KEY');
$response = $gemini->geminiPro()->countTokens(
    new TextPart('PHP in less than 100 chars'),
);

print $response->totalTokens;
// 10
```

### Listing models

[](#listing-models)

```
use GeminiAPI\Gemini;

$gemini = new Gemini('GEMINI_API_KEY');
$response = $gemini->listModels();

print_r($response->models);
//[
//  [0] => GeminiAPI\Resources\Model Object
//    (
//      [name] => models/gemini-pro
//      [displayName] => Gemini Pro
//      [description] => The best model for scaling across a wide range of tasks
//      ...
//    )
//  [1] => GeminiAPI\Resources\Model Object
//    (
//      [name] => models/gemini-pro-vision
//      [displayName] => Gemini Pro Vision
//      [description] => The best image understanding model to handle a broad range of applications
//      ...
//    )
//]
```

### Advanced Usages

[](#advanced-usages)

#### Safety Settings and Generation Configuration

[](#safety-settings-and-generation-configuration)

```
use GeminiAPI\Gemini;
use GeminiAPI\Enums\HarmCategory;
use GeminiAPI\Enums\HarmBlockThreshold;
use GeminiAPI\GenerationConfig;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\SafetySetting;

$safetySetting = new SafetySetting(
    HarmCategory::HARM_CATEGORY_HATE_SPEECH,
    HarmBlockThreshold::BLOCK_LOW_AND_ABOVE,
);
$generationConfig = (new GenerationConfig())
    ->withCandidateCount(1)
    ->withMaxOutputTokens(40)
    ->withTemperature(0.5)
    ->withTopK(40)
    ->withTopP(0.6)
    ->withStopSequences(['STOP']);

$gemini = new Gemini('GEMINI_API_KEY');
$response = $gemini->geminiPro()
    ->withAddedSafetySetting($safetySetting)
    ->withGenerationConfig($generationConfig)
    ->generateContent(
        new TextPart('PHP in less than 100 chars')
    );
```

#### Using your own HTTP client

[](#using-your-own-http-client)

```
use GeminiAPI\Gemini as Gemini;
use GeminiAPI\Resources\Parts\TextPart;
use GuzzleHttp\Client as GuzzleClient;

$guzzle = new GuzzleClient([
  'proxy' => 'http://localhost:8125',
]);

$gemini = new Gemini('GEMINI_API_KEY', $guzzle);
$response = $gemini->geminiPro()->generateContent(
    new TextPart('PHP in less than 100 chars')
);
```

#### Using your own HTTP client for streaming responses

[](#using-your-own-http-client-for-streaming-responses)

> Requires `curl` extension to be enabled

Since streaming responses are fetched using `curl` extension, they cannot use the custom HTTP client passed to the Gemini Client. You need to pass a `CurlHandler` if you want to override connection options.

The following curl options will be overwritten by the Gemini.

- `CURLOPT_URL`
- `CURLOPT_POST`
- `CURLOPT_POSTFIELDS`
- `CURLOPT_WRITEFUNCTION`

You can also pass the headers you want to be used in the requests.

```
use GeminiAPI\Gemini;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\Responses\GenerateContentResponse;

$callback = function (GenerateContentResponse $response): void {
    print $response->text();
};

$ch = curl_init();
curl_setopt($ch, \CURLOPT_PROXY, 'http://localhost:8125');

$gemini = new Gemini('GEMINI_API_KEY');
$gemini->withRequestHeaders([
        'User-Agent' => 'My Gemini-backed app'
    ])
    ->geminiPro()
    ->generateContentStream(
        $callback,
        [new TextPart('PHP in less than 100 chars')],
        $ch,
    );
```

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 72.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

3

Last Release

613d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/68989ff1d47a3b930fb4c500c1bc6405b374ad3c952cba76408420c4627b4905?d=identicon)[usmanilamdin](/maintainers/usmanilamdin)

---

Top Contributors

[![UsmanIlamdin](https://avatars.githubusercontent.com/u/55306553?v=4)](https://github.com/UsmanIlamdin "UsmanIlamdin (8 commits)")[![usman-ilamdin-nexius-ai](https://avatars.githubusercontent.com/u/136356564?v=4)](https://github.com/usman-ilamdin-nexius-ai "usman-ilamdin-nexius-ai (3 commits)")

---

Tags

phpapiclientsdkgoogleaiGeminigemini-progemini pro vision

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/google-gemini-api-php-client/health.svg)

```
[![Health](https://phpackages.com/badges/google-gemini-api-php-client/health.svg)](https://phpackages.com/packages/google-gemini-api-php-client)
```

###  Alternatives

[gemini-api-php/client

API client for Google's Gemini API

216221.4k5](/packages/gemini-api-php-client)[openai-php/client

OpenAI PHP is a supercharged PHP API client that allows you to interact with the Open AI API

5.8k22.6M232](/packages/openai-php-client)[gemini-api-php/laravel

Gemini API client for Laravel

8915.7k](/packages/gemini-api-php-laravel)[mozex/anthropic-php

Anthropic PHP is a supercharged community-maintained PHP API client that allows you to interact with Anthropic API.

46365.1k13](/packages/mozex-anthropic-php)[getbrevo/brevo-php

Official Brevo provided RESTFul API V3 php library

963.1M35](/packages/getbrevo-brevo-php)[google-gemini-php/client

Gemini API is a supercharged PHP API client that allows you to interact with the Gemini API

402986.7k21](/packages/google-gemini-php-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
