1. Go to this page and download the library: Download google-gemini-php/client 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 / client example snippets
use Gemini\Enums\ModelVariation;
use Gemini\GeminiHelper;
$yourApiKey = getenv('YOUR_API_KEY');
$client = Gemini::client($yourApiKey);
$result = $client->generativeModel(model: 'gemini-2.0-flash')->generateContent('Hello');
$result->text(); // Hello! How can I assist you today?
// Helper method usage
$result = $client->generativeModel(
model: GeminiHelper::generateGeminiModel(
variation: ModelVariation::FLASH,
generation: 2.5,
version: "preview-04-17"
), // models/gemini-2.5-flash-preview-04-17
);
$result->text(); // Hello! How can I assist you today?
$yourApiKey = getenv('YOUR_API_KEY');
$client = Gemini::factory()
->withApiKey($yourApiKey)
->withBaseUrl('https://generativelanguage.example.com/v1beta') // default: https://generativelanguage.googleapis.com/v1beta/
->withHttpHeader('X-My-Header', 'foo')
->withQueryParam('my-param', 'bar')
->withHttpClient(new \GuzzleHttp\Client([])) // default: HTTP client found using PSR-18 HTTP Client Discovery
->withStreamHandler(fn(RequestInterface $request): ResponseInterface => $client->send($request, [
'stream' => true // Allows to provide a custom stream handler for the http client.
]))
->make();
$yourApiKey = getenv('YOUR_API_KEY');
$client = Gemini::client($yourApiKey);
$result = $client->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;
$result = $client
->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\Data\UploadedFile;
use Gemini\Enums\MimeType;
$result = $client
->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;
$chat = $client
->generativeModel(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 = $client
->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;
$result = $client
->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;
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 = $client
->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'
),
],
$response = $client
->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;
$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 = $client
->generativeModel(model: 'gemini-2.0-flash')
->withSafetySetting($safetySettingDangerousContent)
->withSafetySetting($safetySettingHateSpeech)
->withGenerationConfig($generationConfig)
->generateContent('Write a story about a magic backpack.');
use Gemini\Testing\ClientFake;
use Gemini\Responses\GenerativeModel\GenerateContentResponse;
$client = new ClientFake([
GenerateContentResponse::fakeStream(),
]);
$result = $client->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');
// assert list models request was sent
use Gemini\Resources\GenerativeModel;
use Gemini\Resources\Models;
$fake->models()->assertSent(callback: function ($method) {
return $method === 'list';
});
// or
$fake->assertSent(resource: Models::class, callback: function ($method) {
return $method === 'list';
});
$fake->geminiPro()->assertSent(function (string $method, array $parameters) {
return $method === 'generateContent' &&
$parameters[0] === 'Hello';
});
// or
$fake->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
$client->assertSent(resource: GenerativeModel::class, model: 'gemini-2.0-flash', callback: 2);
// or
$client->->generativeModel(model: 'gemini-2.0-flash')->assertSent(2);
// assert no generative model requests were sent
$client->assertNotSent(resource: GenerativeModel::class, model: 'gemini-2.0-flash');
// or
$client->->generativeModel(model: 'gemini-2.0-flash')->assertNotSent();
// assert no requests were sent
$client->assertNothingSent();
use Gemini\Testing\ClientFake;
use Gemini\Exceptions\ErrorException;
$client = new ClientFake([
new ErrorException([
'message' => 'The model `gemini-basic` does not exist',
'status' => 'INVALID_ARGUMENT',
'code' => 400,
]),
]);
// the `ErrorException` will be thrown
$client->generativeModel(model: 'gemini-2.0-flash')->generateContent('test');
bash
composer
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.