PHPackages                             google-gemini-php/symfony - 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-php/symfony

ActiveSymfony-bundle[API Development](/categories/api)

google-gemini-php/symfony
=========================

Symfony Bundle for Gemini

2.0.0(1y ago)149.4k↓20.3%11MITPHPPHP ^8.1.0

Since Feb 13Pushed 1y ago4 watchersCompare

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

READMEChangelog (2)Dependencies (11)Versions (3)Used By (1)

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

 [![Latest Version](https://camo.githubusercontent.com/0495e7d883d3bc87f03998c10a280ed67d3af9239af59bf2cabf465050473c3d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f676f6f676c652d67656d696e692d7068702f73796d666f6e79)](https://packagist.org/packages/google-gemini-php/symfony) [![License](https://camo.githubusercontent.com/4a7215ad9ae12dfe3602ae9b364e933819535ff7635f3f551d94bbee940dfb82/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f676f6f676c652d67656d696e692d7068702f73796d666f6e79)](https://packagist.org/packages/google-gemini-php/symfony)

---

**Gemini PHP** for Symfony 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)

For more information, take a look at the [google-gemini-php/client](https://github.com/google-gemini-php/client) repository.

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)
        - [File Upload](#file-upload)
        - [Text-and-video Input](#text-and-video-input)
        - [Multi-turn Conversations (Chat)](#multi-turn-conversations-chat)
        - [Stream Generate Content](#stream-generate-content)
        - [Structured Output](#structured-output)
        - [Function calling](#function-calling)
        - [Count tokens](#count-tokens)
        - [Configuration](#configuration)
    - [Embedding Resource](#embedding-resource)
    - [Models](#models)
        - [List Models](#list-models)
        - [Get Model](#get-model)
- [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/)
- Requires [Symfony 5,6,7](https://symfony.com/)

Setup
-----

[](#setup)

### Installation

[](#installation)

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

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

Next, register the bundle in your config/bundles.php:

```
return [
    // ...
    Gemini\Symfony\GeminiBundle::class => ['all' => true],
]
```

This will create a `.env` configuration file in your project, which you can modify to your needs using environment variables:

```
GEMINI_API_KEY=

```

You can also define the following environment variables.

```
GEMINI_BASE_URL=

```

### 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/symfony:^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

`\Gemini\Enums\ModelType` enum has been deprecated and will be removed in next major version. Together with this `->geminiPro()` and `->geminiFlash()` methods have been deprecated as well. We suggest using `->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:

```
$result = $container->get('gemini')->generativeModel(model: 'gemini-2.0-flash')->generateContent('Hello');

$result->text(); // Hello! How can I assist you today?

```

### 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. If the input contains only text, use the `gemini-pro` model.

```
$result = $container->get('gemini')->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)

If the input contains both text and image, use the `gemini-pro-vision` model.

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

$result = $container->get('gemini')->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.
```

#### File Upload

[](#file-upload)

To reference larger files and videos with various prompts, upload them to Gemini storage.

```
use Gemini\Enums\FileState;
use Gemini\Enums\MimeType;

$files = $container->get('gemini')->files();
echo "Uploading\n";
$meta = $files->upload(
    filename: 'video.mp4',
    mimeType: MimeType::VIDEO_MP4,
    displayName: 'Video'
);
echo "Processing";
do {
    echo ".";
    sleep(2);
    $meta = $files->metadataGet($meta->uri);
} while (!$meta->state->complete());
echo "\n";

if ($meta->state == FileState::Failed) {
    die("Upload failed:\n" . json_encode($meta->toArray(), JSON_PRETTY_PRINT));
}

echo "Processing complete\n" . json_encode($meta->toArray(), JSON_PRETTY_PRINT);
echo "\n{$meta->uri}";
```

#### 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 = $container->get('gemini')
    ->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 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.
```

#### 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 = $container->get('gemini')
    ->chat(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.
```

#### 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 = $container->get('gemini')->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 = $container->get('gemini')
    ->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.

```
