PHPackages                             ggnanobanano-php/client-cryptoman3 - 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. ggnanobanano-php/client-cryptoman3

ActiveLibrary[API Development](/categories/api)

ggnanobanano-php/client-cryptoman3
==================================

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

v6(2mo ago)03.0k↓39.1%MITPHPPHP ^8.1.0

Since Nov 22Pushed 2mo agoCompare

[ Source](https://github.com/cryptoman3/client-google-gemeni)[ Packagist](https://packagist.org/packages/ggnanobanano-php/client-cryptoman3)[ GitHub Sponsors](https://github.com/Plytas)[ GitHub Sponsors](https://github.com/aydinfatih)[ RSS](/packages/ggnanobanano-php-client-cryptoman3/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (18)Versions (7)Used By (0)

 [![Google Gemini PHP](https://raw.githubusercontent.com/google-gemini-php/client/main/art/example.png)](https://raw.githubusercontent.com/google-gemini-php/client/main/art/example.png)

 [![Latest Version](https://camo.githubusercontent.com/44f9cc08f9324be800f87bed123be5beeea51cd9502348499b93a458cd72daee/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f676f6f676c652d67656d696e692d7068702f636c69656e74)](https://packagist.org/packages/google-gemini-php/client) [![License](https://camo.githubusercontent.com/95d4dbf964b629cdccf3f09a15bfcd04970469284788895c39be2ea08cbbfb80/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f676f6f676c652d67656d696e692d7068702f636c69656e74)](https://packagist.org/packages/google-gemini-php/client)

---

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

- Fatih AYDIN [github.com/aydinfatih](https://github.com/aydinfatih)
- Vytautas Smilingis [github.com/Plytas](https://github.com/Plytas)

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

[](#table-of-contents)

- [Prerequisites](#prerequisites)
- [Setup](#setup)
    - [Installation](#installation)
    - [Setup your API key](#setup-your-api-key)
    - [Upgrade to 2.0](#upgrade-to-20)
- [Usage](#usage)
    - [Chat Resource](#chat-resource)
        - [Text-only Input](#text-only-input)
        - [Text-and-image Input](#text-and-image-input)
        - [Text-and-video Input](#text-and-video-input)
        - [Image Generation](#image-generation)
        - [Multi-turn Conversations (Chat)](#multi-turn-conversations-chat)
        - [Chat with Streaming](#chat-with-streaming)
        - [Stream Generate Content](#stream-generate-content)
        - [Structured Output](#structured-output)
        - [Function calling](#function-calling)
        - [Code Execution](#code-execution)
        - [Grounding with Google Search](#grounding-with-google-search)
        - [System Instructions](#system-instructions)
        - [Speech generation](#speech-generation)
        - [Thinking Mode](#thinking-mode)
        - [Count tokens](#count-tokens)
        - [Configuration](#configuration)
    - [File Management](#file-management)
        - [File Upload](#file-upload)
        - [List Files](#list-files)
        - [Get File Metadata](#get-file-metadata)
        - [Delete File](#delete-file)
    - [Cached Content](#cached-content)
        - [Create Cached Content](#create-cached-content)
        - [List Cached Content](#list-cached-content)
        - [Get Cached Content](#get-cached-content)
        - [Update Cached Content](#update-cached-content)
        - [Delete Cached Content](#delete-cached-content)
        - [Use Cached Content](#use-cached-content)
    - [Embedding Resource](#embedding-resource)
    - [Models](#models)
        - [List Models](#list-models)
        - [Get Model](#get-model)
- [Troubleshooting](#troubleshooting)
- [Testing](#testing)

Prerequisites
-------------

[](#prerequisites)

To complete this quickstart, make sure that your development environment meets the following requirements:

- Requires [PHP 8.1+](https://php.net/releases/)

Setup
-----

[](#setup)

### Installation

[](#installation)

First, install Gemini via the [Composer](https://getcomposer.org/) package manager:

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

Ensure that the `php-http/discovery` composer plugin is allowed to run or install a client manually if your project does not already have a PSR-18 client integrated.

```
composer require guzzlehttp/guzzle
```

### Setup your API key

[](#setup-your-api-key)

To use the Gemini API, you'll need an API key. If you don't already have one, create a key in Google AI Studio.

[Get an API key](https://aistudio.google.com/app/apikey)

### Upgrade to 2.0

[](#upgrade-to-20)

Starting 2.0 release this package will work only with Gemini v1beta API ([see API versions](https://ai.google.dev/gemini-api/docs/api-versions)).

To update, run this command:

```
composer require google-gemini-php/client:^2.0
```

This release introduces support for new features:

- Structured output
- System instructions
- File uploads
- Function calling
- Code execution
- Grounding with Google Search
- Cached content
- Thinking model configuration
- Speech model configuration
- URL context retrieval

`\Gemini\Enums\ModelType` enum has been deprecated and will be removed in next major version. Together with this `$client->geminiPro()` and `$client->geminiFlash()` methods have been deprecated as well. We suggest using `$client->generativeModel()` method and pass in the model string directly. All methods that had previously accepted `ModelType` enum now accept a `BackedEnum`. We recommend implementing your own enum for convenience.

There may be other breaking changes not listed here. If you encounter any issues, please submit an issue or a pull request.

Usage
-----

[](#usage)

Interact with Gemini's API:

```
use Gemini\Enums\ModelVariation;
use Gemini\GeminiHelper;
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?

// Helper method usage
$result = $client->generativeModel(
    model: GeminiHelper::generateGeminiModel(
        variation: ModelVariation::FLASH,
        generation: 2.5,
        version: "preview-04-17"
    ), // models/gemini-2.5-flash-preview-04-17
);
$result->text(); // Hello! How can I assist you today?

```

If necessary, it is possible to configure and create a separate client.

```
use Gemini;

$yourApiKey = getenv('YOUR_API_KEY');

$client = Gemini::factory()
    ->withApiKey($yourApiKey)
    ->withBaseUrl('https://generativelanguage.example.com/v1beta') // default: https://generativelanguage.googleapis.com/v1beta/
    ->withHttpHeader('X-My-Header', 'foo')
    ->withQueryParam('my-param', 'bar')
    ->withHttpClient($guzzleClient = new \GuzzleHttp\Client(['timeout' => 30]))  // default: HTTP client found using PSR-18 HTTP Client Discovery
    ->withStreamHandler(fn(RequestInterface $request): ResponseInterface => $guzzleClient->send($request, [
        'stream' => true // Allows to provide a custom stream handler for the http client.
    ]))
    ->make();
```

### Chat Resource

[](#chat-resource)

For a complete list of supported input formats and methods in Gemini API v1, see the [models documentation](https://ai.google.dev/gemini-api/docs/models).

#### Text-only Input

[](#text-only-input)

Generate a response from the model given an input message.

```
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?

```

#### Text-and-image Input

[](#text-and-image-input)

Generate responses by providing both text prompts and images to the Gemini model.

```
use Gemini\Data\Blob;
use Gemini\Enums\MimeType;

$result = $client
    ->generativeModel(model: 'gemini-2.0-flash')
    ->generateContent([
        'What is this picture?',
        new Blob(
            mimeType: MimeType::IMAGE_JPEG,
            data: base64_encode(
                file_get_contents('https://storage.googleapis.com/generativeai-downloads/images/scones.jpg')
            )
        )
    ]);

$result->text(); //  The picture shows a table with a white tablecloth. On the table are two cups of coffee, a bowl of blueberries, a silver spoon, and some flowers. There are also some blueberry scones on the table.
```

#### Text-and-video Input

[](#text-and-video-input)

Process video content and get AI-generated descriptions using the Gemini API with an uploaded video file.

```
use Gemini\Data\UploadedFile;
use Gemini\Enums\MimeType;

$result = $client
    ->generativeModel(model: 'gemini-2.0-flash')
    ->generateContent([
        'What is this video?',
        new UploadedFile(
            fileUri: '123-456', // accepts just the name or the full URI
            mimeType: MimeType::VIDEO_MP4
        )
    ]);

$result->text(); //  The video shows...
```

#### Image Generation

[](#image-generation)

Generate images from text prompts using the Imagen model.

```
use Gemini\Data\ImageConfig;
use Gemini\Data\GenerationConfig;

$imageConfig = new ImageConfig(aspectRatio: '16:9');
$generationConfig = new GenerationConfig(imageConfig: $imageConfig);

$response = $client->generativeModel(model: 'gemini-2.5-flash-image')
    ->withGenerationConfig($generationConfig)
    ->generateContent('Draw a futuristic city');

// Save the image
file_put_contents('image.png', base64_decode($response->parts()[0]->inlineData->data));
```

#### Multi-turn Conversations (Chat)

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

Using Gemini, you can build freeform conversations across multiple turns.

```
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(); // Amidst rolling hills and winding cobblestone streets, the tranquil village of Beausoleil whispered tales of love, intrigue, and the magic of everyday life in 17th century France.

$response = $chat->sendMessage('Rewrite the same story in 1600s England');
echo $response->text(); // In the heart of England's lush countryside, amidst emerald fields and thatched-roof cottages, the village of Willowbrook unfolded a tapestry of love, mystery, and the enchantment of ordinary days in the 17th century.
```

#### Chat with Streaming

[](#chat-with-streaming)

You can also stream the response in a chat session. The history is automatically updated with the full response after the stream completes.

```
$chat = $client->generativeModel(model: 'gemini-2.0-flash')->startChat();

$stream = $chat->streamSendMessage('Hello');

foreach ($stream as $response) {
    echo $response->text();
}
```

#### Stream Generate Content

[](#stream-generate-content)

By default, the model returns a response after completing the entire generation process. You can achieve faster interactions by not waiting for the entire result, and instead use streaming to handle partial results.

```
$stream = $client
    ->generativeModel(model: 'gemini-2.0-flash')
    ->streamGenerateContent('Write long a story about a magic backpack.');

foreach ($stream as $response) {
    echo $response->text();
}
```

#### Structured Output

[](#structured-output)

Gemini generates unstructured text by default, but some applications require structured text. For these use cases, you can constrain Gemini to respond with JSON, a structured data format suitable for automated processing. You can also constrain the model to respond with one of the options specified in an enum.

```
use Gemini\Data\GenerationConfig;
use Gemini\Data\Schema;
use Gemini\Enums\DataType;
use Gemini\Enums\ResponseMimeType;

$result = $client
    ->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');

$result->json();

//[
//    {
//      +"cooking_time_in_minutes": 10,
//      +"recipe_name": "Chocolate Chip Cookies",
//    },
//    {
//      +"cooking_time_in_minutes": 12,
//      +"recipe_name": "Oatmeal Raisin Cookies",
//    },
//    {
//      +"cooking_time_in_minutes": 10,
//      +"recipe_name": "Peanut Butter Cookies",
//    },
//    {
//      +"cooking_time_in_minutes": 10,
//      +"recipe_name": "Snickerdoodles",
//    },
//    {
//      +"cooking_time_in_minutes": 12,
//      +"recipe_name": "Sugar Cookies",
//    },
//  ]
```

#### Function calling

[](#function-calling)

Gemini provides the ability to define and utilize custom functions that the model can call during conversations. This enables the model to perform specific actions or calculations through your defined functions.

```
