1. Go to this page and download the library: Download google-gemini-php/laravel 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/ */
google-gemini-php / laravel example snippets
use Gemini\Laravel\Facades\Gemini;
$result = Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('Hello');
$result->text(); // Hello! How can I assist you today?
use Gemini\Laravel\Facades\Gemini;
$result = Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('Hello');
$result->text(); // Hello! How can I assist you today?
use Gemini\Data\Blob;
use Gemini\Enums\MimeType;
use Gemini\Laravel\Facades\Gemini;
$result = Gemini::generativeModel(model: 'gemini-2.0-flash')
->generateContent([
'What is this picture?',
new Blob(
mimeType: MimeType::IMAGE_JPEG,
data: base64_encode(
file_get_contents('https://storage.googleapis.com/generativeai-downloads/images/scones.jpg')
)
)
]);
$result->text(); // The picture shows a table with a white tablecloth. On the table are two cups of coffee, a bowl of blueberries, a silver spoon, and some flowers. There are also some blueberry scones on the table.
use Gemini\Enums\FileState;
use Gemini\Enums\MimeType;
use Gemini\Laravel\Facades\Gemini;
$files = Gemini::files();
echo "Uploading\n";
$meta = $files->upload(
filename: 'video.mp4',
mimeType: MimeType::VIDEO_MP4,
displayName: 'Video'
);
echo "Processing";
do {
echo ".";
sleep(2);
$meta = $files->metadataGet($meta->uri);
} while (!$meta->state->complete());
echo "\n";
if ($meta->state == FileState::Failed) {
die("Upload failed:\n" . json_encode($meta->toArray(), JSON_PRETTY_PRINT));
}
echo "Processing complete\n" . json_encode($meta->toArray(), JSON_PRETTY_PRINT);
echo "\n{$meta->uri}";
use Gemini\Data\UploadedFile;
use Gemini\Enums\MimeType;
use Gemini\Laravel\Facades\Gemini;
$result = Gemini::generativeModel(model: 'gemini-2.0-flash')
->generateContent([
'What is this video?',
new UploadedFile(
fileUri: '123-456', // accepts just the name or the full URI
mimeType: MimeType::VIDEO_MP4
)
]);
$result->text(); // The picture shows a table with a white tablecloth. On the table are two cups of coffee, a bowl of blueberries, a silver spoon, and some flowers. There are also some blueberry scones on the table.
use Gemini\Data\Content;
use Gemini\Enums\Role;
use Gemini\Laravel\Facades\Gemini;
$chat = Gemini::chat(model: 'gemini-2.0-flash')
->startChat(history: [
Content::parse(part: 'The stories you write about what I have to say should be one line. Is that clear?'),
Content::parse(part: 'Yes, I understand. The stories I write about your input should be one line long.', role: Role::MODEL)
]);
$response = $chat->sendMessage('Create a story set in a quiet village in 1600s France');
echo $response->text(); // Amidst rolling hills and winding cobblestone streets, the tranquil village of Beausoleil whispered tales of love, intrigue, and the magic of everyday life in 17th century France.
$response = $chat->sendMessage('Rewrite the same story in 1600s England');
echo $response->text(); // In the heart of England's lush countryside, amidst emerald fields and thatched-roof cottages, the village of Willowbrook unfolded a tapestry of love, mystery, and the enchantment of ordinary days in the 17th century.
$stream = Gemini::generativeModel(model: 'gemini-2.0-flash')
->streamGenerateContent('Write long a story about a magic backpack.');
foreach ($stream as $response) {
echo $response->text();
}
use Gemini\Data\GenerationConfig;
use Gemini\Data\Schema;
use Gemini\Enums\DataType;
use Gemini\Enums\ResponseMimeType;
use Gemini\Laravel\Facades\Gemini;
$result = Gemini::generativeModel(model: 'gemini-2.0-flash')
->withGenerationConfig(
generationConfig: new GenerationConfig(
responseMimeType: ResponseMimeType::APPLICATION_JSON,
responseSchema: new Schema(
type: DataType::ARRAY,
items: new Schema(
type: DataType::OBJECT,
properties: [
'recipe_name' => new Schema(type: DataType::STRING),
'cooking_time_in_minutes' => new Schema(type: DataType::INTEGER)
],
use Gemini\Data\Content;
use Gemini\Data\FunctionCall;
use Gemini\Data\FunctionDeclaration;
use Gemini\Data\FunctionResponse;
use Gemini\Data\Part;
use Gemini\Data\Schema;
use Gemini\Data\Tool;
use Gemini\Enums\DataType;
use Gemini\Enums\Role;
use Gemini\Laravel\Facades\Gemini;
function handleFunctionCall(FunctionCall $functionCall): Content
{
if ($functionCall->name === 'addition') {
return new Content(
parts: [
new Part(
functionResponse: new FunctionResponse(
name: 'addition',
response: ['answer' => $functionCall->args['number1'] + $functionCall->args['number2']],
)
)
],
role: Role::USER
);
}
//Handle other function calls
}
$chat = Gemini::generativeModel(model: 'gemini-2.0-flash')
->withTool(new Tool(
functionDeclarations: [
new FunctionDeclaration(
name: 'addition',
description: 'Performs addition',
parameters: new Schema(
type: DataType::OBJECT,
properties: [
'number1' => new Schema(
type: DataType::NUMBER,
description: 'First number'
),
'number2' => new Schema(
type: DataType::NUMBER,
description: 'Second number'
),
],
use Gemini\Laravel\Facades\Gemini;
$response = Gemini::generativeModel(model: 'gemini-2.0-flash')
->countTokens('Write a story about a magic backpack.');
echo $response->totalTokens; // 9
use Gemini\Data\GenerationConfig;
use Gemini\Enums\HarmBlockThreshold;
use Gemini\Data\SafetySetting;
use Gemini\Enums\HarmCategory;
use Gemini\Laravel\Facades\Gemini;
$safetySettingDangerousContent = new SafetySetting(
category: HarmCategory::HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold::BLOCK_ONLY_HIGH
);
$safetySettingHateSpeech = new SafetySetting(
category: HarmCategory::HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold::BLOCK_ONLY_HIGH
);
$generationConfig = new GenerationConfig(
stopSequences: [
'Title',
],
maxOutputTokens: 800,
temperature: 1,
topP: 0.8,
topK: 10
);
$generativeModel = Gemini::generativeModel(model: 'gemini-2.0-flash')
->withSafetySetting($safetySettingDangerousContent)
->withSafetySetting($safetySettingHateSpeech)
->withGenerationConfig($generationConfig)
->generateContent("Write a story about a magic backpack.");
use Gemini\Laravel\Facades\Gemini;
use Gemini\Responses\GenerativeModel\GenerateContentResponse;
Gemini::fake([
GenerateContentResponse::fakeStream(),
]);
$result = Gemini::generativeModel(model: 'gemini-2.0-flash')->streamGenerateContent('Hello');
expect($response->getIterator()->current())
->text()->toBe('In the bustling city of Aethelwood, where the cobblestone streets whispered');
use Gemini\Laravel\Facades\Gemini;
use Gemini\Resources\GenerativeModel;
use Gemini\Resources\Models;
// assert list models request was sent
Gemini::models()->assertSent(callback: function ($method) {
return $method === 'list';
});
// or
Gemini::assertSent(resource: Models::class, callback: function ($method) {
return $method === 'list';
});
Gemini::generativeModel(model: 'gemini-2.0-flash')->assertSent(function (string $method, array $parameters) {
return $method === 'generateContent' &&
$parameters[0] === 'Hello';
});
// or
Gemini::assertSent(resource: GenerativeModel::class, model: 'gemini-2.0-flash', callback: function (string $method, array $parameters) {
return $method === 'generateContent' &&
$parameters[0] === 'Hello';
});
// assert 2 generative model requests were sent
Gemini::assertSent(resource: GenerativeModel::class, model: 'gemini-2.0-flash', callback: 2);
// or
Gemini::geminiPro()->assertSent(2);
// assert no generative model requests were sent
Gemini::assertNotSent(resource: GenerativeModel::class, model: 'gemini-2.0-flash');
// or
Gemini::geminiPro()->assertNotSent();
// assert no requests were sent
Gemini::assertNothingSent();
use Gemini\Laravel\Facades\Gemini;
use Gemini\Exceptions\ErrorException;
Gemini::fake([
new ErrorException([
'message' => 'The model `gemini-basic` does not exist',
'status' => 'INVALID_ARGUMENT',
'code' => 400,
]),
]);
// the `ErrorException` will be thrown
Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('test');
bash
composer
bash
php artisan gemini:install
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.