google-gemini-php/client
Community-maintained PHP client for the Google Gemini API. Send text, images, and video; run multi-turn chat with streaming; generate images and speech; structured output, function calling, code execution, grounding/search, token counting, plus file and cached-content management.
Installation
composer require google-gemini-php/client:^2.7.4
Verify the package loads in composer.json under require with the updated version.
First Request Initialize the client with your API key (from Google AI Studio):
use Google\Gemini\Client;
$client = new Client('YOUR_API_KEY');
Basic Usage Send a text generation request:
$response = $client->generateText('What is Laravel?');
echo $response->getText();
Key Files
src/Client.php: Core client logic (updated with new tools support).src/Exceptions/: Error handling classes.src/Tools/: New directory for tool integrations (e.g., FileSearchTool, MapsTool).config/gemini.php (if auto-generated): Updated configuration defaults.Streaming Responses Process large responses incrementally:
$response = $client->generateText('Explain Laravel', ['stream' => true]);
foreach ($response->stream() as $chunk) {
echo $chunk->getText();
}
Multi-Turn Conversations
Use sessionId for context:
$sessionId = $client->startSession();
$response = $client->generateText('Hello', ['sessionId' => $sessionId]);
$followup = $client->generateText('Continue', ['sessionId' => $sessionId]);
Image + Text Prompts Combine images and text:
$response = $client->generateText(
'Describe this image',
['imageUri' => 'https://example.com/image.jpg']
);
New: Tool-Based Prompts Leverage Google's new tools (e.g., file search, maps):
// File Search Tool Example
$response = $client->generateText(
'Summarize this document: {fileSearch}',
['tools' => ['fileSearch' => new \Google\Gemini\Tools\FileSearchTool('doc.pdf')]]
);
// Maps Tool Example
$response = $client->generateText(
'Find restaurants near {maps}',
['tools' => ['maps' => new \Google\Gemini\Tools\MapsTool('New York')]]
);
Optional Thinking Budget
Configure thinkingBudget as optional in ThinkingConfig:
$response = $client->generateText(
'Complex query',
['thinkingConfig' => new \Google\Gemini\ThinkingConfig(['optionalField' => 'value'])]
);
Laravel Service Provider
Bind the client in AppServiceProvider:
$this->app->singleton(Client::class, function ($app) {
return new Client(config('services.gemini.key'));
});
Request Caching Cache responses for repeated queries:
$response = Cache::remember("gemini:{$prompt}", now()->addHours(1), function () use ($client, $prompt) {
return $client->generateText($prompt);
});
Error Handling Centralize exception handling:
try {
$response = $client->generateText('Risky prompt');
} catch (Google\Gemini\Exception\RateLimitException $e) {
// Retry logic or notify admin
}
Tool-Specific Validation Validate tool inputs before sending:
$fileTool = new \Google\Gemini\Tools\FileSearchTool('doc.pdf');
if (!$fileTool->isValid()) {
throw new \InvalidArgumentException('Invalid file for search tool');
}
API Key Exposure
.env:
GEMINI_API_KEY=your_key_here
Rate Limits
$client->getRateLimitStatus();
Session Management
sessionId expires after inactivity. Regenerate if stale:
if (!$client->validateSession($sessionId)) {
$sessionId = $client->startSession();
}
Payload Size Limits
$tools = ['fileSearch' => new \Google\Gemini\Tools\FileSearchTool('large_file.pdf')];
if ($client->estimatePayloadSize($prompt, $tools) > 1_000_000) {
throw new \InvalidArgumentException('Payload too large');
}
Tool-Specific Quotas
Enable Verbose Logging
$client = new Client('YOUR_KEY', [
'debug' => true,
'logger' => new \Monolog\Logger('gemini')
]);
Common Errors
| Error Class | Cause | Fix |
|---|---|---|
InvalidArgumentException |
Malformed prompt/tool | Validate input/tool |
Google\Gemini\Exception\AuthError |
Invalid API key | Check .env |
Google\Gemini\Exception\ServerError |
Gemini API downtime | Retry with jitter |
Google\Gemini\Exception\ToolError |
Invalid tool configuration | Validate tool inputs |
Tool Debugging
Use getToolErrors() to inspect tool-specific failures:
try {
$response = $client->generateText('Query with tools', ['tools' => $tools]);
} catch (\Exception $e) {
if (method_exists($e, 'getToolErrors')) {
$errors = $e->getToolErrors();
// Log or handle tool-specific errors
}
}
Custom Prompt Templates
Extend Google\Gemini\Prompt for reusable formats:
class LaravelPrompt extends \Google\Gemini\Prompt {
public function __construct(string $query) {
parent::__construct("Laravel context: " . $query);
}
}
Middleware for Requests Add preprocessing/validation:
$client->setRequestMiddleware(function ($request) {
$request->setHeader('X-Custom-Header', 'value');
});
Async Processing Use queues for long-running tasks:
dispatch(new GenerateTextJob($prompt, $tools));
Custom Tools
Implement new tools by extending \Google\Gemini\Tool:
class WeatherTool extends \Google\Gemini\Tool {
public function __construct(string $location) {
$this->setInput(['location' => $location]);
}
}
Thinking Budget Configuration
Customize ThinkingConfig for advanced use cases:
$config = new \Google\Gemini\ThinkingConfig([
'optionalField' => 'value', // Now optional
'maxOutputTokens' => 1000,
]);
How can I help you explore Laravel packages today?