hosseinhezami/laravel-gemini
Laravel package for integrating Google Gemini into your app. Send prompts, manage chats and responses, and work with text generation via a clean, developer-friendly API. Ideal for quickly adding AI features to Laravel projects.
Installation
composer require hosseinhezami/laravel-gemini
php artisan vendor:publish --provider="Hosseinhezami\Gemini\GeminiServiceProvider" --tag="config"
config/gemini.php.Environment Configuration
Add your Google API key to .env:
GEMINI_API_KEY=your_api_key_here
First Use Case: Basic Text Generation
use Hosseinhezami\Gemini\Gemini;
$response = Gemini::prompt("What is Laravel?");
echo $response->text();
config/gemini.php for:
gemini.model).gemini.endpoint).gemini.cache).Structured Output (JSON)
$response = Gemini::prompt("Summarize this in JSON: {text}", [
'structuredOutput' => [
'schema' => [
'type' => 'object',
'properties' => [
'summary' => ['type' => 'string'],
'keyPoints' => ['type' => 'array', 'items' => ['type' => 'string']],
],
],
],
]);
$data = $response->json();
Function Calling
$response = Gemini::prompt("Book a flight from NYC to LA", [
'functions' => [
[
'name' => 'book_flight',
'description' => 'Book a flight',
'parameters' => [
'type' => 'object',
'properties' => [
'departure' => ['type' => 'string'],
'destination' => ['type' => 'string'],
],
],
],
],
]);
$actions = $response->actions();
File Uploads (Multimodal)
$filePath = storage_path('image.jpg');
$response = Gemini::prompt("Describe this image", [
'files' => [$filePath],
]);
Caching Responses
Enable caching in config/gemini.php:
'cache' => [
'enabled' => true,
'driver' => 'redis',
'prefix' => 'gemini_',
],
Cache responses for 5 minutes by default; override via:
$response = Gemini::prompt("...", ['cache' => ['ttl' => 3600]]);
Rate Limiting Use middleware to throttle requests:
use Hosseinhezami\Gemini\Middleware\ThrottleGeminiRequests;
$router->middleware(ThrottleGeminiRequests::class);
Queueing Long Requests Dispatch jobs for async processing:
use Hosseinhezami\Gemini\Jobs\ProcessGeminiRequest;
ProcessGeminiRequest::dispatch("Your long prompt here");
API Key Leaks
.env or hardcode keys. Use Laravel's .env or a secrets manager.config/gemini.php:
'validate_key' => env('APP_ENV') !== 'local',
Rate Limits
$rateLimit = Gemini::rateLimit();
'retry' => [
'max_attempts' => 3,
'delay' => 1000, // ms
],
Structured Output Parsing
if ($response->isStructured()) {
$data = $response->json();
} else {
$data = ['error' => 'Invalid structured output'];
}
File Size Limits
Enable Logging
'debug' => [
'enabled' => true,
'log_requests' => true,
'log_responses' => true,
],
Logs appear in storage/logs/gemini.log.
Common Errors
| Error | Solution |
|---|---|
Invalid API Key |
Verify GEMINI_API_KEY in .env. |
Rate Limit Exceeded |
Check Gemini::rateLimit() and implement retries. |
Invalid JSON Schema |
Validate schema syntax (use JSON Schema Validator). |
File Too Large |
Compress files or split into chunks. |
Model Not Found |
Ensure gemini.model in config matches a valid Gemini model (e.g., gemini-pro). |
Custom Models Override the default model dynamically:
$response = Gemini::setModel('gemini-1.5-flash')->prompt("Your prompt");
Event Listeners Listen for request/response events:
use Hosseinhezami\Gemini\Events\RequestSent;
use Hosseinhezami\Gemini\Events\ResponseReceived;
Event::listen(RequestSent::class, function ($event) {
logger()->info('Gemini request sent', $event->payload);
});
Service Provider Extensions Bind custom Gemini clients:
$this->app->bind(Gemini::class, function ($app) {
return new CustomGeminiClient($app['config']['gemini']);
});
Testing
Use the GeminiFake class for unit tests:
use Hosseinhezami\Gemini\Testing\GeminiFake;
public function test_gemini_response()
{
GeminiFake::fake([
'What is Laravel?' => 'A PHP framework...',
]);
$response = Gemini::prompt("What is Laravel?");
$this->assertEquals('A PHP framework...', $response->text());
}
How can I help you explore Laravel packages today?