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

ActiveLibrary[API Development](/categories/api)

sanjarani/gemini
================

A professional Laravel package for working with Google Gemini API

v1.0.6(1y ago)180MITPHPPHP ^8.2

Since May 18Pushed 5mo ago1 watchersCompare

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

READMEChangelogDependencies (12)Versions (8)Used By (0)

Gemini for Laravel
==================

[](#gemini-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/60a4ee4ced528fa0e0508e30c514a815c0df304320c3cd144f23739143a01020/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616e6a6172616e692f67656d696e692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sanjarani/gemini)[![Total Downloads](https://camo.githubusercontent.com/97352cdecb64fe66bd58433765f63cc15b87455932aee1673627f53a4e2c7948/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616e6a6172616e692f67656d696e692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sanjarani/gemini)[![License](https://camo.githubusercontent.com/393c1f5290821dfe64bb6184cc1faf080f5c026c136dd3d29fc830300bb82339/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73616e6a6172616e692f67656d696e692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sanjarani/gemini)

A professional, extensible, and scalable package for integrating the Google Gemini API into the Laravel framework.

Features
--------

[](#features)

- Support for all Gemini models (gemini-pro, gemini-pro-vision, etc.)
- Capability to switch models at runtime
- Built on Laravel HTTP Client with precise error handling
- Service-oriented architecture with Dependency Injection support
- Support for Prompt Caching to save on tokens and achieve faster response times
- Input/Output token counting with cost estimation
- Support for async execution using dedicated Queues and Jobs
- Precise rate limiting control and handling of Rate Limit errors
- Facade for easy access
- Middleware for request management
- Configurable logging system
- Support for generating embeddings and calculating text similarity

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

[](#installation)

You can install this package via Composer:

```
composer require sanjarani/gemini
```

Then, publish the configuration file:

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

Configuration
-------------

[](#configuration)

After publishing the configuration file, you can configure the settings in `config/gemini.php`. You can also use environment variables in your `.env` file:

```
GEMINI_API_KEY=your-api-key
GEMINI_DEFAULT_MODEL=gemini-pro
GEMINI_REQUEST_TIMEOUT=30
GEMINI_ENABLE_CACHE=false
GEMINI_CACHE_TTL=3600
GEMINI_ENABLE_LOGGING=false
```

Usage
-----

[](#usage)

### Text Generation with Gemini Model

[](#text-generation-with-gemini-model)

```
use Sanjarani\Gemini\Facades\Gemini;

// Simple usage
$response = Gemini::generate('Tell me about Artificial Intelligence');
echo $response->content();

// Usage with additional configuration
$response = Gemini::generate('Tell me about Artificial Intelligence', [
    'temperature' => 0.7,
    'top_p' => 0.9,
    'top_k' => 40,
    'max_tokens' => 500,
]);
```

### Chatting with Gemini Model

[](#chatting-with-gemini-model)

```
use Sanjarani\Gemini\Facades\Gemini;

$messages = [
    ['role' => 'user', 'content' => 'Hello, how are you?'],
    ['role' => 'model', 'content' => 'Hello! I am doing well, how can I help you?'],
    ['role' => 'user', 'content' => 'I want to learn more about PHP programming.'],
];

$response = Gemini::chat($messages);
echo $response->content();
```

### Using Vision Model for Image Analysis

[](#using-vision-model-for-image-analysis)

```
use Sanjarani\Gemini\Facades\Gemini;

// Analyze a single image
$response = Gemini::generateFromImage(
    '/path/to/image.jpg',
    'Describe this image'
);

// Analyze multiple images
$response = Gemini::generateFromMultipleImages(
    ['/path/to/image1.jpg', '/path/to/image2.jpg'],
    'Compare these two images'
);

### Using Base64 Image
$base64Image = 'data:image/jpeg;base64,...';
$response = Gemini::generateFromBase64Image(
    $base64Image,
    'Describe this image'
);
```

### Embeddings

[](#embeddings)

```
// Create embedding for text
$response = Gemini::embedText('This is a sample text');
$embedding = $response->raw()['embedding']['values'];

// Create embedding for a batch of texts
$texts = ['First text', 'Second text', 'Third text'];
$response = Gemini::embedBatch($texts);

// Calculate similarity between two embeddings
$embedding1 = $response1->raw()['embedding']['values'];
$embedding2 = $response2->raw()['embedding']['values'];
$similarity = Gemini::calculateSimilarity($embedding1, $embedding2);
echo "Similarity score: {$similarity}"; // A number between 0 and 1
```

### Runtime Model Switching

[](#runtime-model-switching)

```
use Sanjarani\Gemini\Facades\Gemini;

$response = Gemini::setModel('gemini-ultra')
    ->generate('Write a short story');
```

### Async Execution

[](#async-execution)

```
use Sanjarani\Gemini\Facades\Gemini;
use App\Handlers\GeminiResponseHandler;

// Async execution with callback
Gemini::generateAsync(
    'Write an article about AI',
    [],
    GeminiResponseHandler::class,
    'handleResponse',
    ['article_id' => 123]
);
```

### Accessing Response Data

[](#accessing-response-data)

```
use Sanjarani\Gemini\Facades\Gemini;

$response = Gemini::generate('Hello, how are you?');

// Access response text
echo $response->content();

// Access raw response data
$rawData = $response->raw();

// Access token usage information
$tokenUsage = $response->tokenUsage();
echo "Prompt tokens: {$tokenUsage['prompt_tokens']}\n";
echo "Completion tokens: {$tokenUsage['completion_tokens']}\n";
echo "Total tokens: {$tokenUsage['total_tokens']}\n";

// Access estimated cost
echo "Estimated cost: \${$response->estimatedCost()}\n";

// Access used model
echo "Model: {$response->model()}\n";

// Access finish reason
echo "Finish reason: {$response->finishReason()}\n";

// Check if request was successful
if ($response->successful()) {
    echo "Request was successful!\n";
}
```

### Dependency Injection

[](#dependency-injection)

```
use Sanjarani\Gemini\Contracts\TextGenerationServiceInterface;

class MyService
{
    protected $textService;

    public function __construct(TextGenerationServiceInterface $textService)
    {
        $this->textService = $textService;
    }

    public function generateContent($prompt)
    {
        return $this->textService->generate($prompt);
    }
}
```

### Rate Limiting Middleware

[](#rate-limiting-middleware)

In `app/Http/Kernel.php`:

```
protected $routeMiddleware = [
    // ...
    'gemini.limit' => \Sanjarani\Gemini\Middleware\GeminiRateLimitMiddleware::class,
];
```

In Routes:

```
Route::post('/generate', [GeminiController::class, 'generate'])
    ->middleware('gemini.limit:60,1'); // 60 requests per minute
```

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

[](#artisan-commands)

### Test Gemini API

[](#test-gemini-api)

```
php artisan gemini:test "Hello, how are you?"
```

### Clear Gemini Cache

[](#clear-gemini-cache)

```
php artisan gemini:cache-clear
```

Error Handling
--------------

[](#error-handling)

This package handles various errors using dedicated exceptions:

```
use Sanjarani\Gemini\Facades\Gemini;
use Sanjarani\Gemini\Exceptions\GeminiApiException;
use Sanjarani\Gemini\Exceptions\GeminiApiRateLimitException;
use Sanjarani\Gemini\Exceptions\GeminiModelNotFoundException;
use Sanjarani\Gemini\Exceptions\GeminiNetworkException;
use Sanjarani\Gemini\Exceptions\GeminiConfigurationException;

try {
    $response = Gemini::generate('Hello, how are you?');
} catch (GeminiApiRateLimitException $e) {
    // Handle rate limit error
    echo "Rate limit exceeded: {$e->getMessage()}";
} catch (GeminiModelNotFoundException $e) {
    // Handle model not found error
    echo "Model not found: {$e->getMessage()}";
} catch (GeminiNetworkException $e) {
    // Handle network error
    echo "Network error: {$e->getMessage()}";
} catch (GeminiConfigurationException $e) {
    // Handle configuration error
    echo "Configuration error: {$e->getMessage()}";
} catch (GeminiApiException $e) {
    // Handle other API errors
    echo "API error: {$e->getMessage()}";
}
```

Testing
-------

[](#testing)

To run tests:

```
composer test
```

Contribution
------------

[](#contribution)

Contributions are welcome! Please run the tests before submitting a pull request.

License
-------

[](#license)

This package is released under the MIT License. Please see the [LICENSE](LICENSE) file for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance62

Regular maintenance activity

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

7

Last Release

365d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/aa38ec624baac08eb699378a389b667c81d27d2d0521ffa187149ea9127078d0?d=identicon)[sanjarani](/maintainers/sanjarani)

---

Top Contributors

[![sanjarani](https://avatars.githubusercontent.com/u/4986757?v=4)](https://github.com/sanjarani "sanjarani (1 commits)")

---

Tags

apiclientlaravelgoogleaiGemini

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[laravel-zero/framework

The Laravel Zero Framework.

3371.4M369](/packages/laravel-zero-framework)[gemini-api-php/laravel

Gemini API client for Laravel

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

PHPackages © 2026

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