PHP code example of hosseinhezami / laravel-gemini
1. Go to this page and download the library: Download hosseinhezami/laravel-gemini library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hosseinhezami / laravel-gemini example snippets
'default_speech_config' => [
'voiceName' => 'Kore',
// 'speakerVoices' => [
// ['speaker' => 'Joe', 'voiceName' => 'Kore'],
// ['speaker' => 'Jane', 'voiceName' => 'Puck'],
// ],
],
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();
use HosseinHezami\LaravelGemini\Facades\Gemini;
[
['role' => 'user', 'parts' => [['text' => 'User message']]],
['role' => 'model', 'parts' => [['text' => 'Assistant reply']]]
]
$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();
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',
]);
$response = Gemini::text()
->upload('document', $filePath) // image, video, audio, document
->prompt('Extract the key points from this document.')
->generate();
echo $response->content();
$response = Gemini::text()
->model('gemini-2.5-flash')
->structuredSchema([
'type' => 'object',
'properties' => [
'name' => ['type' => 'string'],
'age' => ['type' => 'integer']
],
'
$response = Gemini::image()
->model('gemini-2.5-flash-image-preview')
->method('generateContent')
->prompt('A futuristic city skyline at sunset.')
->generate();
$response->save('image.png');
$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
// }
// }
// 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);
// 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);
// 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();
bash
php artisan vendor:publish --tag=gemini-config