PHPackages                             hosseinhezami/laravel-gemini - 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. hosseinhezami/laravel-gemini

ActiveLibrary[API Development](/categories/api)

hosseinhezami/laravel-gemini
============================

A production-ready Laravel package to integrate with the Google Gemini API. Supports text, image, video, audio, long-context, structured output, files, caching, function-calling and understanding capabilities.

1.0.5(3w ago)14015.5k↓66.6%231MITPHPPHP ^8.2|^8.3|^8.4|^8.5CI passing

Since Sep 13Pushed 3w ago5 watchersCompare

[ Source](https://github.com/hosseinhezami/laravel-gemini)[ Packagist](https://packagist.org/packages/hosseinhezami/laravel-gemini)[ RSS](/packages/hosseinhezami-laravel-gemini/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (6)Dependencies (4)Versions (7)Used By (1)

Laravel Gemini
==============

[](#laravel-gemini)

A production-ready Laravel package to integrate with the Google Gemini API. Supports text, image, video, audio, long-context, structured output, files, caching, function-calling and understanding capabilities.

[![Version](https://camo.githubusercontent.com/9baa85fb2ef6e6483e38361631fbcd8e1cad172cfbf978165d561e0fae678dac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f686f737365696e68657a616d692f6c61726176656c2d67656d696e692e737667)](https://packagist.org/packages/hosseinhezami/laravel-gemini)[![Downloads](https://camo.githubusercontent.com/8456c5f30a51e886f53d2325f38814f9fe3e9a1c4b9ff5145667c640f9bd2ccb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686f737365696e68657a616d692f6c61726176656c2d67656d696e692e737667)](https://packagist.org/packages/hosseinhezami/laravel-gemini)[![Star](https://camo.githubusercontent.com/700a407d3edab83b3f80b713a02b1b3a690831fa8eeb25168c1c200baca19be6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f73746172732f686f737365696e68657a616d692f6c61726176656c2d67656d696e692e737667)](https://packagist.org/packages/hosseinhezami/laravel-gemini)[![License](https://camo.githubusercontent.com/54d568e29fb8f6297facb5596a04bd527a84c4f8a7a6c68c1bc43349d629eb47/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f686f737365696e68657a616d692f6c61726176656c2d67656d696e692e737667)](https://packagist.org/packages/hosseinhezami/laravel-gemini)[![Laravel Compatible](https://camo.githubusercontent.com/30ed7e63c5c0756f6adcba531b17f675688ccf82890a93438dcb9cc706d2e0c6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302532422d627269676874677265656e2e737667)](https://hosseinhezami.github.io/laravel-gemini)

Features
--------

[](#features)

- 🤖 Text generation with context and history
- 🖼️ Image generation and understanding
- 🎥 Video generation and analysis
- 🔊 Audio synthesis and transcription
- 📄 Document processing and understanding
- 🔍 Embeddings generation
- 📊 File management capabilities
- ⚡ Real-time streaming responses
- 🛡️ Configurable safety settings
- 🗄️ Caching for pre-processed content

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

[](#installation)

```
composer require hosseinhezami/laravel-gemini
```

Publish the configuration file:

```
php artisan vendor:publish --tag=gemini-config
```

Add your Gemini API key to your `.env` file:

```
GEMINI_API_KEY=your_gemini_api_key_here
```

Configuration (detailed)
------------------------

[](#configuration-detailed)

Configuration lives in `config/gemini.php`. Below are the most important keys and recommended defaults:

KeyDescriptionDefault`api_key`Your Gemini API key.`env('GEMINI_API_KEY')``base_uri`Base API endpoint.`https://generativelanguage.googleapis.com/v1beta/``default_provider`Which provider config to use by default.`gemini``timeout`Request timeout in seconds.`30``retry_policy.max_retries`Retry attempts for failed requests.`30``retry_policy.retry_delay`Delay between retries in ms.`1000``logging`Log requests/responses (useful for debugging).`false``stream.chunk_size`Stream buffer chunk size.`1024``stream.timeout`Stream timeout (ms).`1000``caching.default_ttl`Default TTL for cache expiration (e.g., '3600s').`'3600s'``caching.default_page_size`Default page size for listing caches.`50`### Providers / models / methods

[](#providers--models--methods)

The `providers` array lets you map capability types to models and HTTP methods the provider uses:

ProviderCapabilityConfig keyDefault modelDefault method`gemini`text`providers.gemini.models.text``gemini-2.5-flash-lite``generateContent``gemini`image`providers.gemini.models.image``gemini-2.5-flash-image-preview``generateContent` or `predict``gemini`video`providers.gemini.models.video``veo-3.0-fast-generate-001``predictLongRunning``gemini`audio`providers.gemini.models.audio``gemini-2.5-flash-preview-tts``generateContent``gemini`embeddings`providers.gemini.models.embedding``gemini-embedding-001`n/a (embeddings endpoint)**Speech config** (`providers.gemini.default_speech_config`) example:

```
'default_speech_config' => [
    'voiceName' => 'Kore',
    // 'speakerVoices' => [
    //     ['speaker' => 'Joe', 'voiceName' => 'Kore'],
    //     ['speaker' => 'Jane', 'voiceName' => 'Puck'],
    // ],
],
```

Dynamic API Key Configuration
-----------------------------

[](#dynamic-api-key-configuration)

By default, Laravel Gemini reads the API key from your `.env` file (`GEMINI_API_KEY`).

However, you can now **set the API key dynamically at runtime** using the new `setApiKey()` method.
This is useful when you want to switch between multiple keys (e.g. per-user or per-request).

**Example:**

```
use HosseinHezami\LaravelGemini\Facades\Gemini;

// Dynamically set API key (takes priority over .env)
Gemini::setApiKey('my-custom-api-key');

// Use Gemini as usual
$response = Gemini::text()
    ->prompt('Hello Gemini!')
    ->generate();

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

If `setApiKey()` is not called, the package will automatically use the default key from `.env`.

**ApiKey priority order:**

1. Manually set key via `Gemini::setApiKey()`
2. Config value (`config/gemini.php`)
3. `.env` variable (`GEMINI_API_KEY`)

---

Builder APIs — full method reference
------------------------------------

[](#builder-apis--full-method-reference)

This package exposes a set of builder-style facades: `Gemini::text()`, `Gemini::image()`, `Gemini::video()`, `Gemini::audio()`, `Gemini::embeddings()`, `Gemini::files()` and `Gemini::caches()`.

Below is a concise reference of commonly available chainable methods and what they do. Method availability depends on the builder.

### Common response helpers (Response object)

[](#common-response-helpers-response-object)

When you call `->generate()` (or a polling save on long-running jobs) you typically get a response object with these helpers:

- `content()` — main textual output (string).
- `model()` — model name used.
- `usage()` — usage / billing info returned by the provider.
- `requestId()` — provider request id.
- `save($path)` — convenience method to download and persist a result to disk (media).

---

### Gemini::

[](#gemini)

```
use HosseinHezami\LaravelGemini\Facades\Gemini;
```

### TextBuilder (`Gemini::text()`)

[](#textbuilder-geminitext)

Use for: chat-like generation, long-context text, structured output, and multimodal understanding (text responses after uploading files).

Common methods:

MethodArgsDescription`model(string)`model idChoose model to use.`prompt(string/array)`user prompt or partsMain prompt(s).`system(string)`system instructionSystem-level instruction.`history(array)`chat historyConversation history array (role/parts structure).`structuredSchema(array)`JSON SchemaAsk model to produce structured JSON (schema validation).`temperature(float)`0.0-1.0Sampling temperature.`maxTokens(int)`token limitMax tokens for generation.`safetySettings(array)`arraySafety thresholds from config.`method(string)`provider methodOverride provider method name (e.g., `generateContent`).`upload(string $type, string $path)`(type, local-file-path)Attach a file (image/document/audio/video) to the request.`cache(array $tools = [], array $toolConfig = [], string $displayName = null, string $ttl = null, string $expireTime = null)`optional paramsCreate a cache from current builder params and return cache name.`getCache(string $name)`cache nameGet details of a cached content.`cachedContent(string $name)`cache nameUse a cached content for generation.`stream(callable)`callbackStream chunks (SSE / server events).`generate()`—Execute request and return a Response object.**Notes on `history` structure**
History entries follow a `role` + `parts` format:

```
[
    ['role' => 'user', 'parts' => [['text' => 'User message']]],
    ['role' => 'model', 'parts' => [['text' => 'Assistant reply']]]
]
```

**Text**

```
$response = Gemini::text()
    ->model('gemini-2.5-flash')
    ->system('You are a helpful assistant.')
    ->prompt('Write a conversation between human and Ai')
    ->history([
        ['role' => 'user', 'parts' => [['text' => 'Hello AI']]],
        ['role' => 'model', 'parts' => [['text' => 'Hello human!']]]
    ])
    ->temperature( 0.7)
    ->maxTokens(1024)
    ->generate();

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

**Streaming Responses**

```
return response()->stream(function () use ($request) {
    Gemini::text()
        ->model('gemini-2.5-flash')
        ->prompt('Tell a long story about artificial intelligence.')
        ->stream(function ($chunk) {
            $text = $chunk['text'] ?? '';
            if (!empty(trim($text))) {
                echo "data: " . json_encode(['text' => $text]) . "\n\n";
                ob_flush();
                flush();
            }
        });
}, 200, [
    'Content-Type' => 'text/event-stream',
    'Cache-Control' => 'no-cache',
    'Connection' => 'keep-alive',
    'X-Accel-Buffering' => 'no',
]);
```

**Document Understanding**

```
$response = Gemini::text()
    ->upload('document', $filePath) // image, video, audio, document
    ->prompt('Extract the key points from this document.')
    ->generate();

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

**Structured output**

```
$response = Gemini::text()
    ->model('gemini-2.5-flash')
    ->structuredSchema([
    'type' => 'object',
    'properties' => [
        'name' => ['type' => 'string'],
        'age'  => ['type' => 'integer']
    ],
    'required' => ['name']
    ])
    ->prompt('Return a JSON object with name and age.')
    ->generate();

$json = $response->content(); // Parsable JSON matching the schema
```

---

### ImageBuilder (`Gemini::image()`)

[](#imagebuilder-geminiimage)

Use for image generation.

MethodArgsDescription`model(string)`model idModel for image generation.`prompt(string)`prompt textImage description.`method(string)`e.g. `predict`Provider method (predict / generateContent).`cache(array $tools = [], array $toolConfig = [], string $displayName = null, string $ttl = null, string $expireTime = null)`optional paramsCreate a cache from current builder params and return cache name.`getCache(string $name)`cache nameGet details of a cached content.`cachedContent(string $name)`cache nameUse a cached content for generation.`generate()`—Run generation.`save($path)`local pathSave image bytes to disk.**Image**

```
$response = Gemini::image()
    ->model('gemini-2.5-flash-image-preview')
    ->method('generateContent')
    ->prompt('A futuristic city skyline at sunset.')
    ->generate();

$response->save('image.png');
```

---

### VideoBuilder (`Gemini::video()`)

[](#videobuilder-geminivideo)

Use for short or long-running video generation.

MethodArgsDescription`model(string)`model idVideo model.`prompt(string)`promptDescribe the video.`cache(array $tools = [], array $toolConfig = [], string $displayName = null, string $ttl = null, string $expireTime = null)`optional paramsCreate a cache from current builder params and return cache name.`getCache(string $name)`cache nameGet details of a cached content.`cachedContent(string $name)`cache nameUse a cached content for generation.`generate()`—Initiates video creation (may be long-running).`save($path)`local pathPolls provider and saves final video file.**Note:** long-running video generation typically uses `predictLongRunning` or similar. The package abstracts polling &amp; saving.

---

### AudioBuilder (`Gemini::audio()`)

[](#audiobuilder-geminiaudio)

Use for TTS generation.

MethodArgsDescription`model(string)`model idTTS model.`prompt(string)`text-to-speakAudio file description`voiceName(string)`voice idSelect a voice (e.g. `Kore`).`speakerVoices(array)`speakers arraySpeakers (e.g. \[\['speaker' =&gt; 'Joe', 'voiceName' =&gt; 'Kore'\], \['speaker' =&gt; 'Jane', 'voiceName' =&gt; 'Puck'\]\]).`cache(array $tools = [], array $toolConfig = [], string $displayName = null, string $ttl = null, string $expireTime = null)`optional paramsCreate a cache from current builder params and return cache name.`getCache(string $name)`cache nameGet details of a cached content.`cachedContent(string $name)`cache nameUse a cached content for generation.`generate()`—Generate audio bytes.`save($path)`local pathSave generated audio (wav/mp3).---

### Embeddings (`Gemini::embeddings()`)

[](#embeddings-geminiembeddings)

Accepts a payload array. Typical shape:

```
$embeddings = Gemini::embeddings([
    'model' => 'gemini-embedding-001',
    'content' => ['parts' => [['text' => 'Text to embed']]],
]);

/* embedding_config */
// https://ai.google.dev/gemini-api/docs/embeddings
// 'embedding_config': {
//     'embedding_config': {
//         'task_type': 'SEMANTIC_SIMILARITY', // SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING, RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, CODE_RETRIEVAL_QUERY, QUESTION_ANSWERING, FACT_VERIFICATION
//         'embedding_dimensionality': 768 // 128, 256, 512, 768, 1536, 2048
//     }
// }
```

Return value is the raw embeddings structure (provider-specific). Use these vectors for semantic search, similarity, clustering, etc.

---

### Files API (`Gemini::files()`)

[](#files-api-geminifiles)

High level file manager for uploads used by the "understanding" endpoints.

MethodArgsDescription`upload(string $type, string $localPath)``type` in `[document,image,video,audio]`Upload a local file and return a provider `uri` or `file id`.`list()`—Return a list of uploaded files (metadata).`get(string $id)`file idGet file metadata (name, uri, state, mimeType, displayName).`delete(string $id)`file idDelete a previously uploaded file.**Files**

```
// Upload a file
$uri = Gemini::files()->upload('document', $pathToFile);

// List all files
$files = Gemini::files()->list();

// Get file details
$fileInfo = Gemini::files()->get($file_id);

// Delete a file
$success = Gemini::files()->delete($file_id);
```

**Supported file types &amp; MIME**

CategoryExtensionMIME typeimagepngimage/pngimagejpegimage/jpegimagejpgimage/jpegimagewebpimage/webpimageheicimage/heicimageheifimage/heifvideomp4video/mp4videompegvideo/mpegvideomovvideo/movvideoavivideo/avivideoflvvideo/x-flvvideompgvideo/mpgvideowebmvideo/webmvideowmvvideo/wmvvideo3gppvideo/3gppaudiowavaudio/wavaudiomp3audio/mp3audioaiffaudio/aiffaudioaacaudio/aacaudiooggaudio/oggaudioflacaudio/flacdocumentpdfapplication/pdfdocumenttxttext/plaindocumentmdtext/markdown---

### Caching API (`Gemini::caches()`)

[](#caching-api-geminicaches)

High-level cache manager for pre-processing and storing content (prompts, system instructions, history, files) to reuse in generation requests, reducing latency and costs. Caches are model-specific and temporary.

MethodArgsDescription`create(string $model, array $contents, ?string $systemInstruction = null, array $tools = [], array $toolConfig = [], ?string $displayName = null, ?string $ttl = null, ?string $expireTime = null)`required/optional paramsCreate a cached content and return CacheResponse.`list(?int $pageSize = null, ?string $pageToken = null)`optional paramsList cached contents (supports pagination).`get(string $name)`cache nameGet details of a cached content.`update(string $name, ?string $ttl = null, ?string $expireTime = null)`cache name and expirationUpdate cache expiration (TTL or expireTime).`delete(string $name)`cache nameDelete a cached content.**Caching**

```
// Create a cache
$cache = Gemini::caches()->create(
    model: 'gemini-2.5-flash',
    contents: [['role' => 'user', 'parts' => [['text' => 'Sample content']]]],
    systemInstruction: 'You are a helpful assistant.',
    tools: [], // Optional
    toolConfig: [], // Optional
    displayName: 'My Cache', // Optional
    ttl: '600s' // Optional TTL (e.g., '300s') or expireTime: '2024-12-31T23:59:59Z'
);
$cacheName = $cache->name(); // e.g., 'cachedContents/abc123'

// List all caches
$caches = Gemini::caches()->list(pageSize: 50, pageToken: 'nextPageToken');

// Get cache details
$cacheInfo = Gemini::caches()->get($cacheName);

// Update cache expiration
$updatedCache = Gemini::caches()->update(
    name: $cacheName,
    ttl: '1200s' // Or expireTime: '2024-12-31T23:59:59Z'
);

// Delete a cache
$success = Gemini::caches()->delete($cacheName);
```

**CacheResponse Methods**

- `name()`: Returns the cache name (e.g., 'cachedContents/abc123')
- `displayName()`: Returns the Display Name (e.g., 'Default Cache')
- `model()`: Returns the model used
- `expireTime()`: Returns expiration
- `usageMetadata()`: Returns usage metadata
- `toArray()`: Full response as array

**Caching in Generation Builders**

Caching is also integrated into text, image, video, and audio builders for seamless use:

```
// Create cache from builder params
$cacheName = Gemini::text()
    ->model('gemini-2.5-flash')
    ->prompt('Sample prompt')
    ->system('System instruction')
    ->history([['role' => 'user', 'parts' => [['text' => 'History item']]]]) // optional
    ->cache(
        tools: [], // optional
        toolConfig: [], // optional
        displayName: 'My Cache', // optional
        ttl: '600s' // optional, or expireTime
    );

// Get cache details from builder
$cacheInfo = Gemini::text()->getCache($cacheName);

// Use cached content in generation
$response = Gemini::text()
    ->prompt('Summarize this.')
    ->cachedContent($cacheName)
    ->generate();
```

For more details, refer to the [Gemini API Caching Documentation](https://ai.google.dev/api/caching).

---

Streaming (Server-Sent Events)
------------------------------

[](#streaming-server-sent-events)

The `stream` route uses `Content-Type: text/event-stream`. Connect from a browser or SSE client and consume `data: ` messages per chunk.

---

### Streaming behaviour

[](#streaming-behaviour)

- Implemented using SSE (Server-Sent Events). The stream yields chunks where each chunk is typically `['text' => '...']`.
- Client should reconnect behaviorally for resilience and handle partial chunks.
- Use response headers:
    - `Content-Type: text/event-stream`
    - `Cache-Control: no-cache`
    - `Connection: keep-alive`
    - `X-Accel-Buffering: no`

---

Tips, error handling &amp; best practices
-----------------------------------------

[](#tips-error-handling--best-practices)

- Respect provider limits — pick appropriate `maxTokens` and `temperature`.
- For large media (video) prefer long-running `predictLongRunning` models and rely on `save()` to poll and download final asset.
- Use `safetySettings` from config for content filtering. You can override per-request.
- When uploading user-supplied files, validate MIME type and size before calling `Gemini::files()->upload`.
- For caching, use TTL wisely to avoid expired caches; always check expiration in responses.

---

Artisan Commands
----------------

[](#artisan-commands)

The package includes helpful Artisan commands:

CommandDescription`php artisan gemini:models`List available models.---

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance96

Actively maintained with recent releases

Popularity45

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 81.8% 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 ~54 days

Total

6

Last Release

21d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/38b7c34a3bb546140c926613060af92984bc184c8731e1cf9aaea704ca88a685?d=identicon)[hosseinhezami](/maintainers/hosseinhezami)

---

Top Contributors

[![hosseinhezami](https://avatars.githubusercontent.com/u/8210576?v=4)](https://github.com/hosseinhezami "hosseinhezami (9 commits)")[![kkobold](https://avatars.githubusercontent.com/u/1929003?v=4)](https://github.com/kkobold "kkobold (1 commits)")[![mimbar](https://avatars.githubusercontent.com/u/2446798?v=4)](https://github.com/mimbar "mimbar (1 commits)")

---

Tags

aiapigeminilaravelpackagephpapilaravelgoogleaiGemini

### Embed Badge

![Health badge](/badges/hosseinhezami-laravel-gemini/health.svg)

```
[![Health](https://phpackages.com/badges/hosseinhezami-laravel-gemini/health.svg)](https://phpackages.com/packages/hosseinhezami-laravel-gemini)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816334.1k3](/packages/defstudio-telegraph)[api-platform/laravel

API Platform support for Laravel

58171.8k14](/packages/api-platform-laravel)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)[gemini-api-php/laravel

Gemini API client for Laravel

8917.4k](/packages/gemini-api-php-laravel)

PHPackages © 2026

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