sanjarani/gemini 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sanjarani/gemini

Composer 安装命令:

composer require sanjarani/gemini

包简介

A professional Laravel package for working with Google Gemini API

README 文档

README

Latest Version on Packagist Total Downloads License

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

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

You can install this package via Composer:

composer require sanjarani/gemini

Then, publish the configuration file:

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

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

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

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

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

// 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

use Sanjarani\Gemini\Facades\Gemini;

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

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

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

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

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

Test Gemini API

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

Clear Gemini Cache

php artisan gemini:cache-clear

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

To run tests:

composer test

Contribution

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

License

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

sanjarani/gemini 适用场景与选型建议

sanjarani/gemini 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 167 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 05 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「client」 「google」 「laravel」 「ai」 「Gemini」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sanjarani/gemini 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sanjarani/gemini 我们能提供哪些服务?
定制开发 / 二次开发

基于 sanjarani/gemini 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 167
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 7
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-05-18