### Install Dev Dependencies Source: https://github.com/google-gemini-php/client/blob/main/CONTRIBUTING.md Install development dependencies for the project. Run this after cloning your fork. ```bash composer install ``` -------------------------------- ### Install Gemini PHP Client Source: https://github.com/google-gemini-php/client/blob/main/README.md Install the Gemini PHP client using Composer. Ensure a PSR-18 HTTP client is available, or install Guzzle. ```bash composer require google-gemini-php/client ``` ```bash composer require guzzlehttp/guzzle ``` -------------------------------- ### Install Gemini PHP Client Source: https://github.com/google-gemini-php/client/blob/main/README.md Use Composer to install the Gemini PHP client library, ensuring compatibility with Gemini API v1beta. ```bash composer require google-gemini-php/client:^2.0 ``` -------------------------------- ### Combine System Instructions with Generation Config Source: https://github.com/google-gemini-php/client/blob/main/README.md Combines system instructions for model persona with generation configuration for response format. This example sets the model to act as a JSON API and respond with valid JSON. ```php use Gemini\Data\Content; use Gemini\Data\GenerationConfig; use Gemini\Enums\ResponseMimeType; $response = $client ->generativeModel(model: 'gemini-2.0-flash') ->withSystemInstruction( Content::parse('You are a JSON API. Always respond with valid JSON objects. Be concise.') ) ->withGenerationConfig( new GenerationConfig(responseMimeType: ResponseMimeType::APPLICATION_JSON) ) ->generateContent('Give me information about the Eiffel Tower'); print_r($response->json()); ``` -------------------------------- ### Set Gemini System Instructions (Pirate) Source: https://github.com/google-gemini-php/client/blob/main/README.md Steers model behavior by defining its role and personality. This example sets the model to act as a helpful assistant that responds in the style of a pirate. ```php use Gemini\Data\Content; $response = $client ->generativeModel(model: 'gemini-2.0-flash') ->withSystemInstruction( Content::parse('You are a helpful assistant that always responds in the style of a pirate. Use nautical terms and pirate slang in all your responses.') ) ->generateContent('Tell me about PHP programming'); echo $response->text(); // Ahoy there, matey! Let me tell ye about this fine treasure called PHP programming... ``` -------------------------------- ### Text-and-video Input Generation Source: https://github.com/google-gemini-php/client/blob/main/README.md Process video content and get AI-generated descriptions by providing text and a video file reference to the Gemini model. ```php 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 video shows... ``` -------------------------------- ### Start Multi-turn Chat Conversation Source: https://github.com/google-gemini-php/client/blob/main/README.md Initiates a chat conversation with a specified model and history. Use this to maintain context across multiple user messages. ```php 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. ``` -------------------------------- ### Manage File Search Stores with Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Shows how to create, upload documents to, list, get, and delete file search stores and documents. Essential for implementing grounded file search capabilities. ```php fileSearchStores()->create( displayName: 'Technical Documentation Store' ); echo "Store created: {$store->name}\n"; // Upload document to store $uploadResult = $client->fileSearchStores()->upload( storeName: $store->name, filename: 'api-documentation.pdf', mimeType: MimeType::APPLICATION_PDF, displayName: 'API Docs', customMetadata: ['version' => '2.0', 'category' => 'api'] ); // List documents in store $docs = $client->fileSearchStores()->listDocuments($store->name); foreach ($docs->documents as $doc) { echo "{$doc->displayName}\n"; } // Get specific document $document = $client->fileSearchStores()->getDocument( 'fileSearchStores/my-store/fileSearchDocuments/doc-id' ); // List all stores $stores = $client->fileSearchStores()->list(pageSize: 10); // Delete document and store $client->fileSearchStores()->deleteDocument($document->name); $client->fileSearchStores()->delete($store->name, force: true); ``` -------------------------------- ### Upload a File to Gemini Storage Source: https://github.com/google-gemini-php/client/blob/main/README.md Upload files, such as videos, to Gemini storage for use in prompts. This example shows the process of uploading a video file and monitoring its processing status. ```php use Gemini\Enums\FileState; use Gemini\Enums\MimeType; $files = $client->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}"; ``` -------------------------------- ### PHP Unit Testing with ClientFake Source: https://context7.com/google-gemini-php/client/llms.txt Use ClientFake to mock Gemini API responses and assert requests in unit tests. Ensure proper setup with necessary use statements. ```php [[ 'content' => [ 'parts' => [['text' => 'Mocked response text']], 'role' => 'model' ] ]] ]) ]); // Use fake client in tests $result = $fake->generativeModel(model: 'gemini-2.0-flash') ->generateContent('Test prompt'); assert($result->text() === 'Mocked response text'); // Assert requests were made $fake->assertSent( resource: GenerativeModel::class, model: 'gemini-2.0-flash', callback: fn($method, $params) => $method === 'generateContent' && $params[0] === 'Test prompt' ); // Assert request count $fake->assertSent(resource: GenerativeModel::class, model: 'gemini-2.0-flash', callback: 1); // Assert nothing sent $freshFake = new ClientFake([]); $freshFake->assertNothingSent(); // Test error scenarios $errorFake = new ClientFake([ new \Gemini\Exceptions\ErrorException([ 'message' => 'Model not found', 'status' => 'NOT_FOUND', 'code' => 404 ]) ]); try { $errorFake->generativeModel('invalid-model')->generateContent('test'); } catch (\Gemini\Exceptions\ErrorException $e) { assert($e->getMessage() === 'Model not found'); } ``` -------------------------------- ### Generate Speech from Text with Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Use the Gemini PHP client to convert text into audio speech. This example shows how to configure a single speaker voice and save the generated audio to a file. ```php generativeModel(model: 'gemini-2.5-flash-preview-tts') ->withGenerationConfig(new GenerationConfig( responseModalities: [ResponseModality::AUDIO], speechConfig: new SpeechConfig( voiceConfig: new VoiceConfig( new PrebuiltVoiceConfig(voiceName: 'Kore') ) ) )) ->generateContent('Hello, welcome to our podcast!'); // Save audio file $audioData = $response->parts()[0]->inlineData->data; file_put_contents('output.wav', base64_decode($audioData)); ``` -------------------------------- ### Create Cached Content Source: https://github.com/google-gemini-php/client/blob/main/README.md Cache content for reuse across multiple requests to reduce costs and latency. This example shows how to create cached content with a specified model, system instruction, parts, and time-to-live (TTL). ```php use Gemini\Data\Content; $cachedContent = $client->cachedContents()->create( model: 'gemini-2.0-flash', systemInstruction: Content::parse('You are an expert PHP developer.னமாக'), parts: [ 'This is a large codebase...', 'File 1 contents...', 'File 2 contents...' ], ttl: '3600s', // Cache for 1 hour displayName: 'PHP Codebase Cache' ); echo "Cached content created: {$cachedContent->name}\n"; ``` -------------------------------- ### Get File Search Store Source: https://github.com/google-gemini-php/client/blob/main/README.md Retrieves a specific file search store using its unique name, displaying its name and display name. ```php $fileSearchStore = $client->fileSearchStores()->get('fileSearchStores/my-search-store'); echo "Name: {$fileSearchStore->name} "; echo "Display Name: {$fileSearchStore->displayName} "; ``` -------------------------------- ### Retrieve Specific Model Information with PHP Source: https://github.com/google-gemini-php/client/blob/main/README.md Use `models()->retrieve()` with a model name to get detailed information about a specific Gemini model. The response contains a `Model` object. ```php $response = $client->models()->retrieve('models/gemini-2.5-pro-preview-05-06'); $response->model; //Gemini\Data\Model Object //( // [name] => models/gemini-2.5-pro-preview-05-06 // [version] => 2.5-preview-05-06 // [displayName] => Gemini 2.5 Pro Preview 05-06 // [description] => Preview release (May 6th, 2025) of Gemini 2.5 Pro // ... //) ``` -------------------------------- ### Configure HTTP Client Timeout with PHP Source: https://github.com/google-gemini-php/client/blob/main/README.md Increase the API request timeout by configuring the HTTP client, for example, using Guzzle. Pass the configured client to the Gemini factory using `withHttpClient`. ```php Gemini::factory() ->withApiKey($apiKey) ->withHttpClient(new \GuzzleHttp\Client(['timeout' => $timeout])) ->make(); ``` -------------------------------- ### Fake Client for Standard Responses Source: https://github.com/google-gemini-php/client/blob/main/README.md Initialize the fake client with a list of `GenerateContentResponse` objects. These responses will be returned in the order they are provided. Use the `fake()` method on response objects to easily create mock responses. ```php use Gemini\Testing\ClientFake; use Gemini\Responses\GenerativeModel\GenerateContentResponse; $client = new ClientFake([ GenerateContentResponse::fake([ 'candidates' => [ [ 'content' => [ 'parts' => [ [ 'text' => 'success', ], ], ], ], ], ]), ]); $result = $fake->generativeModel(model: 'gemini-2.0-flash')->generateContent('test'); expect($result->text())->toBe('success'); ``` -------------------------------- ### Get File Search Document Source: https://github.com/google-gemini-php/client/blob/main/README.md Retrieves details for a specific document within a file search store, identified by its full name. ```php $fileSearchDocument = $client->fileSearchStores()->getDocument('fileSearchStores/my-search-store/fileSearchDocuments/my-document'); echo "Name: {$fileSearchDocument->name} "; echo "Display Name: {$fileSearchDocument->displayName} "; ``` -------------------------------- ### Configure System Instructions in PHP Source: https://context7.com/google-gemini-php/client/llms.txt Configure model behavior and personality by providing system instructions. Useful for creating specialized assistants with specific response styles. ```php generativeModel(model: 'gemini-2.0-flash') ->withSystemInstruction( Content::parse('You are a technical documentation expert. Always provide code examples and explain concepts clearly. Use markdown formatting.') ) ->withGenerationConfig( new GenerationConfig( temperature: 0.7, maxOutputTokens: 2048 ) ) ->generateContent('Explain dependency injection in PHP'); echo $response->text(); ``` -------------------------------- ### Stream Chat Conversation Response Source: https://github.com/google-gemini-php/client/blob/main/README.md Starts a chat and streams the response back incrementally. The chat history is updated automatically after the stream completes. ```php $chat = $client->generativeModel(model: 'gemini-2.0-flash')->startChat(); $stream = $chat->streamSendMessage('Hello'); foreach ($stream as $response) { echo $response->text(); } ``` -------------------------------- ### Configure Gemini Client with Safety and Generation Settings Source: https://github.com/google-gemini-php/client/blob/main/README.md Set up safety settings to block harmful content and configure generation parameters like temperature and max output tokens. This snippet demonstrates how to instantiate and configure the client for content generation. ```php 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.'); ``` -------------------------------- ### List and Retrieve Model Information with Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Demonstrates how to list available models with pagination and retrieve details for a specific model. Useful for understanding model capabilities like token limits and supported features. ```php models()->list(pageSize: 10); foreach ($response->models as $model) { echo "Model: {$model->displayName}\n"; echo " Name: {$model->name}\n"; echo " Input limit: {$model->inputTokenLimit} tokens\n"; echo " Output limit: {$model->outputTokenLimit} tokens\n"; echo " Methods: " . implode(', ', $model->supportedGenerationMethods) . "\n\n"; } // Pagination if ($response->nextPageToken) { $nextPage = $client->models()->list( pageSize: 10, nextPageToken: $response->nextPageToken ); } // Get specific model details $model = $client->models()->retrieve('models/gemini-2.0-flash'); echo "Temperature range: 0 - {$model->model->maxTemperature}\n"; ``` -------------------------------- ### Get File Metadata Source: https://github.com/google-gemini-php/client/blob/main/README.md Fetch metadata for a specific file using its ID or full URI. This allows you to check the file's display name, state, and size. ```php $meta = $client->files()->metadataGet('abc123'); // or use the full URI $meta = $client->files()->metadataGet($file->uri); echo "File: {$meta->displayName}\n"; echo "State: {$meta->state->value}\n"; echo "Size: {$meta->sizeBytes} bytes\n"; ``` -------------------------------- ### Initialize Gemini PHP Client Source: https://context7.com/google-gemini-php/client/llms.txt Instantiate the Gemini client using an API key. The factory pattern allows for advanced configuration of base URL, HTTP client, headers, and query parameters. ```php withApiKey($apiKey) ->withBaseUrl('https://generativelanguage.googleapis.com/v1beta/') ->withHttpHeader('X-Custom-Header', 'value') ->withQueryParam('custom-param', 'value') ->withHttpClient(new GuzzleHttp\Client(['timeout' => 60])) ->withStreamHandler(fn($request) => $guzzle->send($request, ['stream' => true])) ->make(); ``` -------------------------------- ### Ground Responses with Google Search in PHP Source: https://context7.com/google-gemini-php/client/llms.txt Connect the model to real-time web content using Google Search grounding for up-to-date information with source citations. ```php generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool(googleSearch: GoogleSearch::from())) ->generateContent('What are the latest developments in AI regulation?'); echo $response->text(); // Access grounding metadata and sources $metadata = $response->candidates[0]->groundingMetadata; if ($metadata !== null) { foreach ($metadata->groundingChunks ?? [] as $chunk) { if ($chunk->web !== null) { echo "Source: {$chunk->web->title} - {$chunk->web->uri}\n"; } } } ``` -------------------------------- ### Model Configuration and Generation Source: https://github.com/google-gemini-php/client/blob/main/README.md Demonstrates how to configure safety settings and generation parameters for the Gemini model and generate content. ```APIDOC ## Model Configuration and Generation ### Description This section shows how to configure safety settings and generation parameters like `temperature`, `topP`, and `maxOutputTokens` to control the model's response. It also includes an example of generating content using the configured model. ### Method N/A (Client-side configuration and generation) ### Endpoint N/A ### Parameters #### Safety Settings - **category** (HarmCategory) - Required - The category of harm to configure. - **threshold** (HarmBlockThreshold) - Required - The blocking threshold for the specified harm category. #### Generation Config - **stopSequences** (array) - Optional - Sequences that will cause the model to stop generating further tokens. - **maxOutputTokens** (int) - Optional - The maximum number of tokens to generate. - **temperature** (float) - Optional - Controls randomness. Lower values make the output more focused and deterministic. - **topP** (float) - Optional - Controls the diversity of the output. Top-p sampling considers the smallest set of tokens whose cumulative probability exceeds top-p. - **topK** (int) - Optional - Controls the diversity of the output. Top-k sampling considers the largest number of tokens whose cumulative probability exceeds top-k. ### Request Example ```php 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.'); ``` ### Response #### Success Response (200) - **generativeModel** (GenerativeModel) - The configured generative model object. #### Response Example N/A (This is a configuration example, not a direct response example.) ``` -------------------------------- ### Create File Search Store and Upload Document Source: https://github.com/google-gemini-php/client/blob/main/README.md Creates a file search store and uploads a document, including a loop to poll for completion status. Requires importing enums for file state and MIME types. ```php use Gemini\Enums\FileState; use Gemini\Enums\MimeType; use Gemini\Enums\Schema; use Gemini\Enums\DataType; $files = $client->files(); echo "Uploading "; $meta = $files->upload( filename: 'document.pdf', mimeType: MimeType::APPLICATION_PDF, displayName: 'Document for search' ); echo "Processing"; do { echo "."; sleep(2); $meta = $files->metadataGet($meta->uri); } while (! $meta->state->complete()); echo " "; if ($meta->state == FileState::Failed) { die("Upload failed:".json_encode($meta->toArray(), JSON_PRETTY_PRINT)); } $fileSearchStore = $client->fileSearchStores()->create( displayName: 'My Search Store', ); echo "File search store created: {$fileSearchStore->name} "; ``` -------------------------------- ### Upload and Manage Files with Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Demonstrates how to upload files to Gemini storage, monitor their processing status, list existing files, and delete them using the Gemini PHP client. ```php files(); $meta = $files->upload( filename: 'document.pdf', mimeType: MimeType::APPLICATION_PDF, displayName: 'Technical Documentation' ); // Wait for processing do { sleep(2); $meta = $files->metadataGet($meta->uri); } while (!$meta->state->complete()); if ($meta->state === FileState::ACTIVE) { echo "File ready: {" . $meta->uri . "}\n"; echo "Size: {" . $meta->sizeBytes . "} bytes\n"; } // List all files $fileList = $files->list(pageSize: 10); foreach ($fileList->files as $file) { echo "{$file->displayName} - {$file->state->value}\n"; } // Delete a file $files->delete($meta->uri); ``` -------------------------------- ### Run All Tests Source: https://github.com/google-gemini-php/client/blob/main/CONTRIBUTING.md Execute all tests in the project. This command runs the full test suite. ```bash composer test ``` -------------------------------- ### Configure Generation Parameters in PHP Source: https://context7.com/google-gemini-php/client/llms.txt Fine-tune model output with generation parameters including temperature, token limits, stop sequences, and penalties. Also configures safety settings. ```php generativeModel(model: 'gemini-2.0-flash') ->withGenerationConfig(new GenerationConfig( candidateCount: 1, stopSequences: ['END', '---'], maxOutputTokens: 1000, temperature: 0.9, topP: 0.95, topK: 40, presencePenalty: 0.5, frequencyPenalty: 0.5, seed: 42 )) ->withSafetySetting(new SafetySetting( category: HarmCategory::HARM_CATEGORY_DANGEROUS_CONTENT, threshold: HarmBlockThreshold::BLOCK_ONLY_HIGH )) ->generateContent('Generate a creative story'); echo $response->text(); ``` -------------------------------- ### Generate Model String with Helper Source: https://github.com/google-gemini-php/client/blob/main/README.md Utilize the GeminiHelper to construct a model string for advanced generation configurations, including specific versions and preview releases. ```php use Gemini\Enums\ModelVariation; use Gemini\GeminiHelper; use Gemini; $yourApiKey = getenv('YOUR_API_KEY'); $client = Gemini::client($yourApiKey); $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? ``` -------------------------------- ### Run Unit Tests Source: https://github.com/google-gemini-php/client/blob/main/CONTRIBUTING.md Execute only the unit tests. This command focuses on testing individual components. ```bash composer test:unit ``` -------------------------------- ### Fake Client for Streamed Responses Source: https://github.com/google-gemini-php/client/blob/main/README.md For streamed responses, initialize the fake client with `GenerateContentResponse::fakeStream()`. You can optionally provide a resource holding the fake response data. The `streamGenerateContent` method will then return an iterator for the fake stream. ```php 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'); ``` -------------------------------- ### Custom Client Configuration Source: https://github.com/google-gemini-php/client/blob/main/README.md Configure a custom Gemini client instance with specific API keys, base URLs, HTTP headers, query parameters, and HTTP clients. Useful for advanced or specific network configurations. ```php use Gemini; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; $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($guzzleClient = new GuzzleHttp Client(['timeout' => 30])) // default: HTTP client found using PSR-18 HTTP Client Discovery ->withStreamHandler(fn(RequestInterface $request): ResponseInterface => $guzzleClient->send($request, [ 'stream' => true // Allows to provide a custom stream handler for the http client. ])) ->make(); ``` -------------------------------- ### Ground Responses with File Search in PHP Source: https://context7.com/google-gemini-php/client/llms.txt Search through indexed document collections to ground model responses with specific file content. Requires specifying store names and optional metadata filters. ```php generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool( fileSearch: new FileSearch( fileSearchStoreNames: ['files/my-document-store'], metadataFilter: 'category = "technical"' ) )) ->generateContent('What does the documentation say about authentication?'); echo $response->text(); ``` -------------------------------- ### List File Search Stores Source: https://github.com/google-gemini-php/client/blob/main/README.md Lists all available file search stores, iterating through the response and displaying the name and display name for each store. ```php $response = $client->fileSearchStores()->list(pageSize: 10); foreach ($response->fileSearchStores as $fileSearchStore) { echo "Name: {$fileSearchStore->name} "; echo "Display Name: {$fileSearchStore->displayName} "; echo "--- "; } ``` -------------------------------- ### Simulating API Errors Source: https://github.com/google-gemini-php/client/blob/main/README.md To test error handling, initialize the fake client with a `Throwable` object, such as `ErrorException`. This will cause the specified exception to be thrown when the corresponding method is called. ```php 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'); ``` -------------------------------- ### Enable Thinking Mode in Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Demonstrates how to enable and utilize thinking mode for models that support extended reasoning. This allows you to see the model's reasoning process alongside its final answer. ```php generativeModel(model: 'gemini-2.0-flash-thinking-exp') ->withGenerationConfig(new GenerationConfig( thinkingConfig: new ThinkingConfig( includeThoughts: true, thinkingBudget: 2048 ) )) ->generateContent('Solve: If 3x + 7 = 22, what is x?'); foreach ($response->candidates[0]->content->parts as $part) { if ($part->thought === true) { echo "Thinking: " . $part->text . "\n\n"; } else if ($part->text !== null) { echo "Answer: " . $part->text . "\n"; } } ``` -------------------------------- ### Ground Gemini with File Search Source: https://github.com/google-gemini-php/client/blob/main/README.md Allows the model to access and utilize information from your indexed files. Specify file store names and optional metadata filters to narrow down the search. ```php use Gemini\Data\FileSearch; use Gemini\Data\Tool; $tool = new Tool( fileSearch: new FileSearch( fileSearchStoreNames: ['files/my-document-store'], metadataFilter: 'author = "Robert Graves"' ) ); $response = $client ->generativeModel(model: 'gemini-2.0-flash') ->withTool($tool) ->generateContent('Summarize the document about Greek myths by Robert Graves'); echo $response->text(); // (Model output summarizing the document) ``` -------------------------------- ### Ground Responses with Google Maps in PHP Source: https://context7.com/google-gemini-php/client/llms.txt Ground model responses with geographical data and places information using Google Maps integration. Requires specifying latitude and longitude for location context. ```php generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool(googleMaps: new GoogleMaps(enableWidget: true))) ->withToolConfig(new ToolConfig( retrievalConfig: new RetrievalConfig( latitude: 37.7749, longitude: -122.4194 ) )) ->generateContent('Find highly rated Italian restaurants nearby'); echo $response->text(); ``` -------------------------------- ### Manage Cached Content with Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Demonstrates creating, using, listing, updating TTL, and deleting cached content. Use this to reduce latency and costs for repeated requests with shared context. ```php cachedContents()->create( model: 'gemini-2.0-flash', systemInstruction: Content::parse('You are an expert code reviewer.'), displayName: 'Code Review Context', ttl: '3600s', parts: [ 'Project guidelines: Always follow PSR-12 coding standards...', 'Security checklist: Check for SQL injection, XSS, CSRF...' ] ); echo "Cache created: {$cachedContent->name}\n"; // Use cached content in generation $response = $client->generativeModel(model: 'gemini-2.0-flash') ->withCachedContent($cachedContent->name) ->generateContent('Review this code: function login($user, $pass) {...}'); echo $response->text(); // List cached contents $list = $client->cachedContents()->list(pageSize: 10); foreach ($list->cachedContents as $cached) { echo "{$cached->displayName} expires: {$cached->expireTime}\n"; } // Update TTL $client->cachedContents()->update( name: $cachedContent->name, ttl: '7200s' ); // Delete when done $client->cachedContents()->delete($cachedContent->name); ``` -------------------------------- ### List Available Gemini Models with PHP Source: https://github.com/google-gemini-php/client/blob/main/README.md Use `models()->list()` to retrieve a paginated list of available Gemini models. Optional parameters `pageSize` and `nextPageToken` can be used for pagination. ```php $response = $client->models()->list(pageSize: 3, nextPageToken: 'ChFtb2RlbHMvZ2VtaW5pLXBybw=='); $response->models; //[ // [0] => Gemini\Data\Model Object // ( // [name] => models/gemini-2.0-flash // [version] => 2.0 // [displayName] => Gemini 2.0 Flash // [description] => Gemini 2.0 Flash // ... // ) // [1] => Gemini\Data\Model Object // ( // [name] => models/gemini-2.5-pro-preview-05-06 // [version] => 2.5-preview-05-06 // [displayName] => Gemini 2.5 Pro Preview 05-06 // [description] => Preview release (May 6th, 2025) of Gemini 2.5 Pro // ... // ) // [2] => Gemini\Data\Model Object // ( // [name] => models/text-embedding-004 // [version] => 004 // [displayName] => Text Embedding 004 // [description] => Obtain a distributed representation of a text. // ... // ) //] ``` -------------------------------- ### Troubleshooting API Timeouts Source: https://github.com/google-gemini-php/client/blob/main/README.md Guidance on how to handle and increase API request timeouts when using the Gemini PHP client. ```APIDOC ### Timeout Configuration When encountering timeouts with API requests, you can increase the default timeout by configuring the underlying HTTP client. #### Example using Guzzle This example demonstrates how to set a custom timeout value using the Guzzle HTTP client. ```php $apiKey = 'YOUR_API_KEY'; $timeout = 60; // Timeout in seconds $client = Gemini::factory() ->withApiKey($apiKey) ->withHttpClient(new GuzzleHttp Client(['timeout' => $timeout])) ->make(); ``` ``` -------------------------------- ### PHP Multi-turn Chat with Gemini Source: https://context7.com/google-gemini-php/client/llms.txt Initialize a chat session with optional history, send messages, and receive responses. Supports streaming responses for a smoother user experience. ```php generativeModel(model: 'gemini-2.0-flash') ->startChat(history: [ Content::parse(part: 'You are a helpful coding assistant', role: Role::USER), Content::parse(part: 'Understood! I will help with coding questions.', role: Role::MODEL) ]); // Send messages and get responses $response = $chat->sendMessage('How do I read a file in PHP?'); echo $response->text(); // Continue the conversation $response = $chat->sendMessage('Now show me how to write to a file'); echo $response->text(); // Stream chat responses $stream = $chat->streamSendMessage('Explain error handling best practices'); foreach ($stream as $chunk) { echo $chunk->text(); } ``` -------------------------------- ### List Uploaded Files Source: https://github.com/google-gemini-php/client/blob/main/README.md Retrieve a list of all files currently stored in your Gemini project. This snippet iterates through the files and displays their metadata. ```php $response = $client->files()->list(pageSize: 10); foreach ($response->files as $file) { echo "Name: {$file->name}\n"; echo "Display Name: {$file->displayName}\n"; echo "Size: {$file->sizeBytes} bytes\n"; echo "MIME Type: {$file->mimeType}\n"; echo "State: {$file->state->value}\n"; echo "---\n"; } // Get next page if available if ($response->nextPageToken) { $nextPage = $client->files()->list(pageSize: 10, nextPageToken: $response->nextPageToken); } ``` -------------------------------- ### Check Types Source: https://github.com/google-gemini-php/client/blob/main/CONTRIBUTING.md Perform type checking on the codebase. This command verifies type correctness. ```bash composer test:types ``` -------------------------------- ### Ground Gemini with Google Search Source: https://github.com/google-gemini-php/client/blob/main/README.md Connects the Gemini model to real-time web content using the GoogleSearch tool. Automatically handles search queries and provides grounding metadata including search queries, sources, and text segment support. ```php use Gemini\Data\GoogleSearch; use Gemini\Data\Tool; $response = $client ->generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool(googleSearch: GoogleSearch::from())) ->generateContent('Who won the Euro 2024?'); echo $response->text(); // Spain won Euro 2024, defeating England 2-1 in the final. // Access grounding metadata to see sources $groundingMetadata = $response->candidates[0]->groundingMetadata; if ($groundingMetadata !== null) { // Get the search queries that were executed foreach ($groundingMetadata->webSearchQueries ?? [] as $query) { echo "Search query: {$query}\n"; } // Get the web sources foreach ($groundingMetadata->groundingChunks ?? [] as $chunk) { if ($chunk->web !== null) { echo "Source: {$chunk->web->title} - {$chunk->web->uri}\n"; } } // Get grounding supports (links text segments to sources) foreach ($groundingMetadata->groundingSupports ?? [] as $support) { if ($support->segment !== null) { echo "Text segment: {$support->segment->text}\n"; echo "Supported by chunks: " . implode(', ', $support->groundingChunkIndices ?? []) . "\n"; } } } ``` -------------------------------- ### Upload Document to File Search Store Source: https://github.com/google-gemini-php/client/blob/main/README.md Uploads a local file directly into a specified file search store. Requires the store name and file details, including MIME type. ```php use Gemini\Enums\MimeType; $response = $client->fileSearchStores()->upload( storeName: 'fileSearchStores/my-search-store', filename: 'document2.pdf', mimeType: MimeType::APPLICATION_PDF, displayName: 'Another Search Document' ); echo "File search document upload operation: {$response->name} "; ``` -------------------------------- ### Basic Text Generation Source: https://github.com/google-gemini-php/client/blob/main/README.md Generate a text response from the Gemini API using the generativeModel method. Requires an API key. ```php use Gemini; $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? ``` -------------------------------- ### Enable Thinking Mode for Model Reasoning Source: https://github.com/google-gemini-php/client/blob/main/README.md Configure models that support thinking mode to include their reasoning process in the output. This is useful for debugging and understanding complex problem-solving steps. Set `includeThoughts` to true and optionally specify a `thinkingBudget`. ```php use Gemini\Data\GenerationConfig; use Gemini\Data\ThinkingConfig; $response = $client ->generativeModel(model: 'gemini-2.0-flash-thinking-exp') ->withGenerationConfig( new GenerationConfig( thinkingConfig: new ThinkingConfig( includeThoughts: true, thinkingBudget: 1024 ) ) ) ->generateContent('Solve this logic puzzle: If all Bloops are Razzies and all Razzies are Lazzies, are all Bloops definitely Lazzies?'); // Access the model's thoughts and final answer foreach ($response->candidates[0]->content->parts as $part) { if ($part->thought === true) { // This part contains the model's thinking process echo "Model's thinking: " . $part->text . "\n\n"; } else if ($part->text !== null) { // This is the final answer echo "Final answer: " . $part->text . "\n"; } } ``` -------------------------------- ### Image Generation Source: https://github.com/google-gemini-php/client/blob/main/README.md Generate images from text prompts using the Imagen model. Allows configuration of image aspect ratio and saves the generated image to a file. ```php use Gemini\Data\ImageConfig; use Gemini\Data\GenerationConfig; $imageConfig = new ImageConfig(aspectRatio: '16:9'); $generationConfig = new GenerationConfig(imageConfig: $imageConfig); $response = $client->generativeModel(model: 'gemini-2.5-flash-image') ->withGenerationConfig($generationConfig) ->generateContent('Draw a futuristic city'); // Save the image file_put_contents('image.png', base64_decode($response->parts()[0]->inlineData->data)); ``` -------------------------------- ### Video Processing with Uploaded Files Source: https://context7.com/google-gemini-php/client/llms.txt Process video content by referencing files previously uploaded to Gemini storage. Use the UploadedFile object with the correct file URI and MimeType. ```php generativeModel(model: 'gemini-2.0-flash') ->generateContent([ 'Summarize what happens in this video', new UploadedFile( fileUri: 'files/abc123-xyz789', mimeType: MimeType::VIDEO_MP4 ) ]); echo $response->text(); // Output: "The video shows a tutorial on..." ``` -------------------------------- ### Ground Gemini with Google Maps Source: https://github.com/google-gemini-php/client/blob/main/README.md Enables the model to use real-world geographical data for precise location-based responses. Requires specifying latitude and longitude for the search context. ```php use Gemini\Data\GoogleMaps; use Gemini\Data\RetrievalConfig; use Gemini\Data\Tool; use Gemini\Data\ToolConfig; $tool = new Tool( googleMaps: new GoogleMaps(enableWidget: true) ); $toolConfig = new ToolConfig( retrievalConfig: new RetrievalConfig( latitude: 40.758896, longitude: -73.985130 ) ); $response = $client ->generativeModel(model: 'gemini-2.0-flash') ->withTool($tool) ->withToolConfig($toolConfig) ->generateContent('Find coffee shops near me'); echo $response->text(); // (Model output referencing coffee shops) ``` -------------------------------- ### Execute Python Code with Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Enable code execution for computational tasks. The model returns both the Python code and its execution results. ```php generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool(codeExecution: CodeExecution::from())) ->generateContent('Calculate the first 20 Fibonacci numbers'); foreach ($response->parts() as $part) { if ($part->executableCode !== null) { echo "Code:\n" . $part->executableCode->code . "\n"; } if ($part->codeExecutionResult !== null) { echo "Output:\n" . $part->codeExecutionResult->output . "\n"; } } ``` -------------------------------- ### Count Tokens with Gemini PHP Source: https://context7.com/google-gemini-php/client/llms.txt Estimate the number of tokens in a given text prompt before sending it to the model. This is useful for cost estimation and staying within model limits. ```php generativeModel(model: 'gemini-2.0-flash') ->countTokens('This is a sample text to count tokens for.'); echo "Total tokens: " . $response->totalTokens; ``` -------------------------------- ### Lint Code Source: https://github.com/google-gemini-php/client/blob/main/CONTRIBUTING.md Run the linter to ensure code style compliance. This command checks for coding style issues. ```bash composer lint ``` -------------------------------- ### Streaming Responses for Real-time Output Source: https://context7.com/google-gemini-php/client/llms.txt Stream responses for real-time delivery of generated content. Iterate over the stream to process partial results as they become available, using flush() to output immediately. ```php generativeModel(model: 'gemini-2.0-flash') ->streamGenerateContent('Write a detailed essay about artificial intelligence'); foreach ($stream as $response) { echo $response->text(); flush(); // Output partial response immediately } ```