### Artisan Command: gemini:install Source: https://context7.com/google-gemini-php/laravel/llms.txt The `gemini:install` command is a one-time setup wizard that publishes configuration files, creates environment variable stubs, and optionally directs users to the GitHub repository. ```APIDOC ## Artisan Command — `gemini:install` The install command is a one-shot setup wizard that publishes config, writes env stubs, and optionally opens the GitHub repository in the browser. ```bash # Run interactively (prompts to star on GitHub) php artisan gemini:install # Sample output: # INFO Installing Gemini for Laravel. # config/gemini.php .......... File created. # .env ...................... GEMINI_API_KEY variable added. # .env.example .............. GEMINI_API_KEY variable added. # Repository ................ https://github.com/google-gemini-php/laravel # Manually publish config without the install command php artisan vendor:publish --provider="Gemini\Laravel\ServiceProvider" ``` ``` -------------------------------- ### Installation Source: https://context7.com/google-gemini-php/laravel/llms.txt Install the package via Composer and run the Artisan command to publish the configuration and environment variables. ```APIDOC ## Installation Install via Composer and run the Artisan install command to publish the config file and inject environment variable stubs. ```bash composer require google-gemini-php/laravel php artisan gemini:install ``` The install command publishes `config/gemini.php` and appends `GEMINI_API_KEY=` to both `.env` and `.env.example`. It is idempotent — re-running it safely skips already-existing config files and env variables. ``` -------------------------------- ### Run Gemini Install Command Source: https://github.com/google-gemini-php/laravel/blob/main/README.md After installing the package, run this Artisan command to set up the configuration file and .env variables. ```bash php artisan gemini:install ``` -------------------------------- ### Install Dev Dependencies Source: https://github.com/google-gemini-php/laravel/blob/main/CONTRIBUTING.md Install development dependencies for the project. This is a prerequisite for local development and testing. ```bash composer install ``` -------------------------------- ### Artisan Install Command Source: https://context7.com/google-gemini-php/laravel/llms.txt Run `php artisan gemini:install` to set up the Gemini for Laravel package. This command publishes configuration files, adds environment variable stubs, and can optionally open the GitHub repository. ```bash # Run interactively (prompts to star on GitHub) php artisan gemini:install # Sample output: # INFO Installing Gemini for Laravel. # config/gemini.php .......... File created. # .env ...................... GEMINI_API_KEY variable added. # .env.example .............. GEMINI_API_KEY variable added. # Repository ................ https://github.com/google-gemini-php/laravel # Manually publish config without the install command php artisan vendor:publish --provider="Gemini\Laravel\ServiceProvider" ``` -------------------------------- ### Install Google Gemini PHP for Laravel Source: https://context7.com/google-gemini-php/laravel/llms.txt Install the package via Composer and run the Artisan command to publish configuration and environment variables. ```bash composer require google-gemini-php/laravel php artisan gemini:install ``` -------------------------------- ### Install Gemini PHP for Laravel Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Install the Gemini PHP package using Composer. This command fetches and installs the necessary files for the Laravel integration. ```bash composer require google-gemini-php/laravel ``` -------------------------------- ### System Instructions Source: https://context7.com/google-gemini-php/laravel/llms.txt Steer the model's persona and response style with a persistent system instruction. This allows you to guide the model's behavior, such as its tone or output format. ```APIDOC ## `Gemini::generativeModel()` — System Instructions Steer the model's persona and response style with a persistent system instruction. ```php use Gemini\Data\Content; use Gemini\Data\GenerationConfig; use Gemini\Enums\ResponseMimeType; use Gemini\Laravel\Facades\Gemini; // Plain persona instruction $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withSystemInstruction( Content::parse('You are a terse senior engineer. Answer in bullet points only. No fluff.') ) ->generateContent('Explain the CAP theorem.'); echo $response->text(); // Combined with JSON output $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withSystemInstruction(Content::parse('You are a JSON API. Only emit valid JSON.')) ->withGenerationConfig(new GenerationConfig(responseMimeType: ResponseMimeType::APPLICATION_JSON)) ->generateContent('Return the top 3 programming languages by popularity as an array of objects with "name" and "rank".'); print_r($response->json()); ``` ``` -------------------------------- ### Text-and-video Input Generation Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Process video content and get AI-generated descriptions. Use UploadedFile with the video's URI and MIME type. ```php 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 video shows... ``` -------------------------------- ### Initiate Multi-turn Chat with History Source: https://context7.com/google-gemini-php/laravel/llms.txt Start a stateful chat session using `startChat`, optionally seeding it with a history of previous messages. The SDK automatically appends exchanges to the history. ```php use Gemini\Data\Content; use Gemini\Enums\Role; use Gemini\Laravel\Facades\Gemini; $chat = Gemini::generativeModel(model: 'gemini-2.0-flash') ->startChat(history: [ Content::parse(part: 'Keep all replies under 20 words.'), Content::parse(part: 'Understood, I will be very concise.', role: Role::MODEL), ]); $r1 = $chat->sendMessage('What is recursion?'); echo $r1->text(); // "A function calling itself to solve a smaller version of the same problem." $r2 = $chat->sendMessage('Give a PHP example.'); echo $r2->text(); // "function factorial(int $n): int { return $n <= 1 ? 1 : $n * factorial($n - 1); }" ``` -------------------------------- ### Text-and-video Input Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Process video content and get AI-generated descriptions using the Gemini API with an uploaded video file. ```APIDOC ## Text-and-video Input ### Description Process video content and get AI-generated descriptions using the Gemini API with an uploaded video file. ### Method ```php 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 ) ]); ``` ### Response Example ```php $result->text(); // The video shows... ``` ``` -------------------------------- ### Multi-turn Conversations (Chat) Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Build freeform conversations across multiple turns. Start a chat with initial history and send messages sequentially. ```php use Gemini\Data\Content; use Gemini\Enums\Role; use Gemini\Laravel\Facades\Gemini; $chat = Gemini::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. ``` -------------------------------- ### List, Get Metadata, and Delete Files with Gemini Source: https://context7.com/google-gemini-php/laravel/llms.txt Manages uploaded files by paginating through them, retrieving metadata for a specific file, and deleting files that are no longer needed. ```php use Gemini\Laravel\Facades\Gemini; $files = Gemini::files(); // List first page $page = $files->list(pageSize: 20); foreach ($page->files as $file) { echo "{$file->name} — {$file->displayName} — {$file->sizeBytes} bytes\n"; } // Fetch next page if available if ($page->nextPageToken) { $page2 = $files->list(pageSize: 20, nextPageToken: $page->nextPageToken); } // Retrieve metadata for a specific file $meta = $files->metadataGet('files/abc123'); echo "State: {$meta->state->value}, Expires: {$meta->expirationTime}\n"; // Delete a file $files->delete('files/abc123'); ``` -------------------------------- ### List and Retrieve Gemini Models Source: https://context7.com/google-gemini-php/laravel/llms.txt Use `Gemini::models()->list()` to get paginated results of available models. Use `Gemini::models()->retrieve()` with a model name to fetch detailed metadata for a specific model. ```php use Gemini\Laravel\Facades\Gemini; // List models (paginated) $response = Gemini::models()->list(pageSize: 10); foreach ($response->models as $model) { echo "{$model->name} — {$model->displayName} (v{$model->version})\n"; } // models/gemini-2.0-flash — Gemini 2.0 Flash (v2.0) // models/gemini-2.5-pro-preview-05-06 — Gemini 2.5 Pro Preview 05-06 (v2.5-preview-05-06) // Retrieve a specific model $detail = Gemini::models()->retrieve('models/gemini-2.5-pro-preview-05-06'); echo $detail->model->displayName . "\n"; // "Gemini 2.5 Pro Preview 05-06" ``` -------------------------------- ### Get Model Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Retrieve detailed information about a specific Gemini model. ```APIDOC ## Get Model ### Description Get information about a model, such as version, display name, input token limit, etc. ### Method ```php use Gemini\Laravel\Facades\Gemini; $response = Gemini::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 // ... //) ``` ``` -------------------------------- ### Get Metadata for a Specific File Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Fetches metadata for a given file using its ID or full URI. This allows you to check the file's display name, state, and size. ```php use Gemini\Laravel\Facades\Gemini; $meta = Gemini::files()->metadataGet('abc123'); // or use the full URI $meta = Gemini::files()->metadataGet($file->uri); echo "File: {$meta->displayName}\n"; echo "State: {$meta->state->value}\n"; echo "Size: {$meta->sizeBytes} bytes\n"; ``` -------------------------------- ### Configure Gemini API Key and Settings Source: https://context7.com/google-gemini-php/laravel/llms.txt Configuration is managed through environment variables. Ensure GEMINI_API_KEY is set. Optional settings include GEMINI_BASE_URL and GEMINI_REQUEST_TIMEOUT. ```php // config/gemini.php return [ // Required. Obtain at https://aistudio.google.com/app/apikey 'api_key' => env('GEMINI_API_KEY'), // Optional. Override the default v1beta endpoint. 'base_url' => env('GEMINI_BASE_URL'), // Optional. HTTP timeout in seconds (default 30). 'request_timeout' => env('GEMINI_REQUEST_TIMEOUT', 30), ]; ``` ```dotenv # .env GEMINI_API_KEY=AIza... GEMINI_BASE_URL= # leave blank for default https://generativelanguage.googleapis.com/v1beta/ GEMINI_REQUEST_TIMEOUT=60 ``` -------------------------------- ### Configuration Source: https://context7.com/google-gemini-php/laravel/llms.txt Configure the API key, base URL, and request timeout through environment variables, managed by the `config/gemini.php` file. ```APIDOC ## Configuration — `config/gemini.php` All three knobs are read from environment variables, making the package fully 12-factor compliant. ```php // config/gemini.php return [ // Required. Obtain at https://aistudio.google.com/app/apikey 'api_key' => env('GEMINI_API_KEY'), // Optional. Override the default v1beta endpoint. 'base_url' => env('GEMINI_BASE_URL'), // Optional. HTTP timeout in seconds (default 30). 'request_timeout' => env('GEMINI_REQUEST_TIMEOUT', 30), ]; ``` ```dotenv # .env GEMINI_API_KEY=AIza... GEMINI_BASE_URL= # leave blank for default https://generativelanguage.googleapis.com/v1beta/ GEMINI_REQUEST_TIMEOUT=60 ``` If `GEMINI_API_KEY` is absent or not a string, the container throws `Gemini\Laravel\Exceptions\MissingApiKey` on first resolution. If `GEMINI_BASE_URL` is set but not a string, it throws `InvalidArgumentException`. ``` -------------------------------- ### Get File Metadata Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Retrieves metadata for a specific file. ```APIDOC ## Get File Metadata ### Description Fetches the metadata for a specific file using its ID or URI. ### Method `Gemini::files()->metadataGet()` ### Parameters - `fileIdOrUri` (string) - Required - The ID or full URI of the file. ### Request Example ```php use Gemini\Laravel\Facades\Gemini; $meta = Gemini::files()->metadataGet('abc123'); // or use the full URI $meta = Gemini::files()->metadataGet($file->uri); echo "File: {$meta->displayName}\n"; echo "State: {$meta->state->value}\n"; echo "Size: {$meta->sizeBytes} bytes\n"; ``` ``` -------------------------------- ### Get Cached Content Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Retrieve a specific cached content by its name. ```APIDOC ## Get Cached Content ### Description Retrieve a specific cached content by name. ### Method ```php use Gemini\Laravel\Facades\Gemini; $cached = Gemini::cachedContents()->retrieve('cachedContents/abc123'); echo "Model: {$cached->model}\n"; echo "Created: {$cached->createTime}\n"; echo "Expires: {$cached->expireTime}\n"; ``` ``` -------------------------------- ### Combine System Instructions with Generation Config Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Combine system instructions with generation configurations, such as specifying the response MIME type, to steer model behavior and output format. ```php use Gemini\Data\Content; use Gemini\Data\GenerationConfig; use Gemini\Enums\ResponseMimeType; use Gemini\Laravel\Facades\Gemini; $response = Gemini::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()); ``` -------------------------------- ### Steer Model Persona with System Instructions Source: https://context7.com/google-gemini-php/laravel/llms.txt Control the model's persona and response style using persistent system instructions. This can be combined with JSON output for structured responses. ```php use Gemini\Data\Content; use Gemini\Data\GenerationConfig; use Gemini\Enums\ResponseMimeType; use Gemini\Laravel\Facades\Gemini; // Plain persona instruction $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withSystemInstruction( Content::parse('You are a terse senior engineer. Answer in bullet points only. No fluff.') ) ->generateContent('Explain the CAP theorem.'); echo $response->text(); // Combined with JSON output $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withSystemInstruction(Content::parse('You are a JSON API. Only emit valid JSON.')) ->withGenerationConfig(new GenerationConfig(responseMimeType: ResponseMimeType::APPLICATION_JSON)) ->generateContent('Return the top 3 programming languages by popularity as an array of objects with "name" and "rank".'); print_r($response->json()); ``` -------------------------------- ### Using the Gemini Facade for API Interactions Source: https://context7.com/google-gemini-php/laravel/llms.txt The Gemini facade is the main entry point for API calls. It re-exports all methods from the underlying Gemini\Client. ```php use Gemini\Laravel\Facades\Gemini; // Available facade methods: // Gemini::generativeModel(string|BackedEnum $model): GenerativeModel // Gemini::embeddingModel(string|BackedEnum $model): GenerativeModel // Gemini::models(): Models // Gemini::chat(string|BackedEnum $model): ChatSession // Gemini::files(): Files // Gemini::cachedContents(): CachedContents (via underlying client) ``` -------------------------------- ### Gemini::generativeModel() — Multi-turn Chat Source: https://context7.com/google-gemini-php/laravel/llms.txt Start a stateful chat session with optional seeded history. The session automatically appends each exchange. ```APIDOC ## `Gemini::generativeModel()` — Multi-turn Chat Start a stateful chat session with optional seeded history; the session automatically appends each exchange. ```php use Gemini\Data\Content; use Gemini\Enums\Role; use Gemini\Laravel\Facades\Gemini; $chat = Gemini::generativeModel(model: 'gemini-2.0-flash') ->startChat(history: [ Content::parse(part: 'Keep all replies under 20 words.'), Content::parse(part: 'Understood, I will be very concise.', role: Role::MODEL), ]); $r1 = $chat->sendMessage('What is recursion?'); echo $r1->text(); // "A function calling itself to solve a smaller version of the same problem." $r2 = $chat->sendMessage('Give a PHP example.'); echo $r2->text(); // "function factorial(int $n): int { return $n <= 1 ? 1 : $n * factorial($n - 1); }" ``` ``` -------------------------------- ### Run Unit Tests Source: https://github.com/google-gemini-php/laravel/blob/main/CONTRIBUTING.md Execute only the unit tests for the project. This is useful for quickly verifying the behavior of individual components. ```bash composer test:unit ``` -------------------------------- ### Ground Response with Google Search Source: https://context7.com/google-gemini-php/laravel/llms.txt Connect the model to live web content to provide up-to-date information and cite sources. Inspect grounding metadata to see search queries and source details. ```php use Gemini\Data\GoogleSearch; use Gemini\Data\Tool; use Gemini\Laravel\Facades\Gemini; $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool(googleSearch: GoogleSearch::from())) ->generateContent('Who won the most recent FIFA World Cup?'); echo $response->text(); // Inspect grounding metadata $meta = $response->candidates[0]->groundingMetadata; foreach ($meta->groundingChunks ?? [] as $chunk) { if ($chunk->web !== null) { echo "Source: {" . $chunk->web->title . "} — {" . $chunk->web->uri . "}\n"; } } foreach ($meta->webSearchQueries ?? [] as $query) { echo "Searched: {" . $query . "}\n"; } ``` -------------------------------- ### List Files Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Lists all uploaded files in your project. ```APIDOC ## List Files ### Description Retrieves a list of all files uploaded to your Gemini project. ### Method `Gemini::files()->list()` ### Parameters - `pageSize` (int) - Optional - The maximum number of files to return per page. - `nextPageToken` (string) - Optional - A token to retrieve the next page of results. ### Request Example ```php use Gemini\Laravel\Facades\Gemini; $response = Gemini::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 = Gemini::files()->list(pageSize: 10, nextPageToken: $response->nextPageToken); } ``` ``` -------------------------------- ### Run All Tests Source: https://github.com/google-gemini-php/laravel/blob/main/CONTRIBUTING.md Execute all tests in the project, including unit, integration, and type checks. This ensures the codebase is stable. ```bash composer test ``` -------------------------------- ### Implement Function Calling with Gemini PHP Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Define custom functions that the Gemini model can call to perform specific actions or calculations. This example demonstrates handling an addition function. ```php name === 'addition') { return new Content( parts: [ new Part( functionResponse: new FunctionResponse( name: 'addition', response: ['answer' => $functionCall->args['number1'] + $functionCall->args['number2']], ), thoughtSignature: 'some-signature' // Optional: Required for some models (e.g. Gemini 3 Pro) ) ], 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' ), ], required: ['number1', 'number2'] ) ) ] )) ->startChat(); $response = $chat->sendMessage('What is 4 + 3?'); if ($response->parts()[0]->functionCall !== null) { $thoughtSignature = $response->parts()[0]->thoughtSignature; // Access the thought signature $functionResponse = handleFunctionCall($response->parts()[0]->functionCall); $response = $chat->sendMessage($functionResponse); } echo $response->text(); // 4 + 3 = 7 ``` -------------------------------- ### List All Uploaded Files Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Retrieves a paginated list of all files uploaded to your project. It displays key metadata for each file and shows how to fetch the next page of results if available. ```php use Gemini\Laravel\Facades\Gemini; $response = Gemini::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 = Gemini::files()->list(pageSize: 10, nextPageToken: $response->nextPageToken); } ``` -------------------------------- ### Retrieve Specific Gemini Model Information with Laravel SDK Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Get detailed information about a specific Gemini model, such as its version, display name, and input token limits. Ensure the model name is correct. ```php use Gemini\Laravel\Facades\Gemini; $response = Gemini::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 // ... //) ``` -------------------------------- ### Generative Model Configuration Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Demonstrates how to configure a generative model with safety settings and generation configurations. ```APIDOC ## Generative Model Configuration ### Description Configure a generative model with specific safety settings and generation parameters to control the output. ### Method `Gemini::generativeModel()` ### Parameters - `model` (string) - Required - The name of the model to use (e.g., 'gemini-2.0-flash'). - `withSafetySetting` (SafetySetting) - Optional - Adds a safety setting to the model configuration. - `withGenerationConfig` (GenerationConfig) - Optional - Sets the generation configuration for the model. ### Request Example ```php 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."); ``` ``` -------------------------------- ### Grounding with Google Search Source: https://context7.com/google-gemini-php/laravel/llms.txt Connect the model to live web content so it can cite up-to-date sources beyond its training cutoff. This allows the model to provide answers based on current information from the web. ```APIDOC ## `Gemini::generativeModel()` — Grounding with Google Search Connect the model to live web content so it can cite up-to-date sources beyond its training cutoff. ```php use Gemini\Data\GoogleSearch; use Gemini\Data\Tool; use Gemini\Laravel\Facades\Gemini; $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool(googleSearch: GoogleSearch::from())) ->generateContent('Who won the most recent FIFA World Cup?'); echo $response->text(); // Inspect grounding metadata $meta = $response->candidates[0]->groundingMetadata; foreach ($meta->groundingChunks ?? [] as $chunk) { if ($chunk->web !== null) { echo "Source: {" . $chunk->web->title . "} — {" . $chunk->web->uri . "}\n"; } } foreach ($meta->webSearchQueries ?? [] as $query) { echo "Searched: {" . $query . "}\n"; } ``` ``` -------------------------------- ### Configure Safety Settings and Generation Parameters Source: https://context7.com/google-gemini-php/laravel/llms.txt Fine-tune model behavior by setting safety categories and thresholds, alongside generation parameters like temperature and token limits. ```php use Gemini\Data\GenerationConfig; use Gemini\Data\SafetySetting; use Gemini\Enums\HarmBlockThreshold; use Gemini\Enums\HarmCategory; use Gemini\Laravel\Facades\Gemini; $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withSafetySetting(new SafetySetting( category: HarmCategory::HARM_CATEGORY_DANGEROUS_CONTENT, threshold: HarmBlockThreshold::BLOCK_ONLY_HIGH, )) ->withSafetySetting(new SafetySetting( category: HarmCategory::HARM_CATEGORY_HATE_SPEECH, threshold: HarmBlockThreshold::BLOCK_ONLY_HIGH, )) ->withGenerationConfig(new GenerationConfig( temperature: 0.7, topP: 0.9, topK: 40, maxOutputTokens: 1024, stopSequences: ['END'], )) ->generateContent('Describe the French Revolution.'); echo $response->text(); ``` -------------------------------- ### Execute Code with Gemini Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Use the `CodeExecution` tool to allow Gemini models to generate and execute code, returning the results. Ensure the model supports code execution. ```php use Gemini\Data\CodeExecution; use Gemini\Data\Tool; use Gemini\Laravel\Facades\Gemini; $response = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool(codeExecution: CodeExecution::from())) ->generateContent('What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'); // Access the executed code and results foreach ($response->parts() as $part) { if ($part->executableCode !== null) { echo "Language: " . $part->executableCode->language->value . "\n"; echo "Code: " . $part->executableCode->code . "\n"; } if ($part->codeExecutionResult !== null) { echo "Outcome: " . $part->codeExecutionResult->outcome->value . "\n"; echo "Output: " . $part->codeExecutionResult->output . "\n"; } } ``` -------------------------------- ### Generate Content with Gemini Generative Model Source: https://context7.com/google-gemini-php/laravel/llms.txt Send a single-turn prompt to a Gemini generative model and receive a GenerateContentResponse. Use the Gemini facade for this operation. ```php use Gemini\Laravel\Facades\Gemini; $result = Gemini::generativeModel(model: 'gemini-2.0-flash') ->generateContent('Summarize the history of the internet in two sentences.'); echo $result->text(); // The internet began as ARPANET in the late 1960s, a US military research network... ``` -------------------------------- ### Testing with Gemini Fakes Source: https://context7.com/google-gemini-php/laravel/llms.txt Replace the real Gemini client with fakes for testing. You can queue responses, assert that specific methods were called with certain arguments, and simulate API errors. ```php use Gemini\Laravel\Facades\Gemini; use Gemini\Resources\GenerativeModel; use Gemini\Resources\Models; use Gemini\Responses\GenerativeModel\GenerateContentResponse; // --- Basic fake --- Gemini::fake([ GenerateContentResponse::fake([ 'candidates' => [[ 'content' => ['parts' => [['text' => 'Mocked answer']]], ]], ]), ]); $result = Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('Tell me a joke'); expect($result->text())->toBe('Mocked answer'); // --- Add more responses mid-test --- Gemini::addResponses([ GenerateContentResponse::fake([ 'candidates' => [[ 'content' => ['parts' => [['text' => 'Second response']]], ]], ]), ]); // --- Assert a specific call was made --- Gemini::assertSent( resource: GenerativeModel::class, model: 'gemini-2.0-flash', callback: fn(string $method, array $params) => $method === 'generateContent' && $params[0] === 'Tell me a joke' ); // --- Assert via the resource instance --- Gemini::generativeModel('gemini-2.0-flash')->assertSent( fn(string $method, array $params) => $method === 'generateContent' ); // --- Assert call count --- Gemini::assertSent(GenerativeModel::class, 'gemini-2.0-flash', 1); // --- Assert a call was NOT made --- Gemini::assertNotSent(Models::class); // --- Assert nothing was sent at all --- Gemini::fake(); Gemini::assertNothingSent(); // --- Simulate an API error --- use Gemini\Exceptions\ErrorException; Gemini::fake([ new ErrorException([ 'message' => 'The model does not exist', 'status' => 'INVALID_ARGUMENT', 'code' => 400, ]), ]); expect(fn () => Gemini::generativeModel('gemini-2.0-flash')->generateContent('test')) ->toThrow(ErrorException::class); ``` -------------------------------- ### Gemini API Key Environment Variable Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Add your Gemini API key to the .env file. This is required for authentication with the Gemini API. ```dotenv GEMINI_API_KEY= ``` -------------------------------- ### Configure Gemini SDK with Safety Settings and Generation Config Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Set up safety settings for dangerous content and hate speech, and define generation parameters like stop sequences and token limits. This configuration is applied when generating content. ```php 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."); ``` -------------------------------- ### Image Generation with Imagen Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Generate images from text prompts using the Imagen model. Configure aspect ratio and save the output to a file. ```php use Gemini\Data\ImageConfig; use Gemini\Data\GenerationConfig; use Gemini\Laravel\Facades\Gemini; $imageConfig = new ImageConfig(aspectRatio: '16:9'); $generationConfig = new GenerationConfig(imageConfig: $imageConfig); $response = Gemini::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)); ``` -------------------------------- ### Upload a File Source: https://context7.com/google-gemini-php/laravel/llms.txt Uploads a local file to Gemini storage (up to 2 GB; retained for 48 hours) and polls until processing completes. ```APIDOC ## `Gemini::files()` — Upload a File Upload a local file to Gemini storage (up to 2 GB; retained for 48 hours) and poll until processing completes. ```php use Gemini\Enums\FileState; use Gemini\Enums\MimeType; use Gemini\Laravel\Facades\Gemini; $files = Gemini::files(); $meta = $files->upload( filename: storage_path('app/lecture.mp4'), mimeType: MimeType::VIDEO_MP4, displayName: 'CS101 Lecture', ); // Poll until the file is ACTIVE do { sleep(2); $meta = $files->metadataGet($meta->name); } while (! $meta->state->complete()); if ($meta->state === FileState::FAILED) { throw new \RuntimeException('File processing failed: ' . json_encode($meta->toArray())); } echo "Ready: {$meta->uri}\n"; // use this URI in subsequent prompts ``` ``` -------------------------------- ### Gemini::fake() Source: https://context7.com/google-gemini-php/laravel/llms.txt Replace the real client with a queue of canned responses for testing purposes. Assert which methods were invoked and with what arguments. ```APIDOC ## `Gemini::fake()` — Testing with Fakes Replace the real client with a queue of canned responses; assert which methods were invoked and with what arguments. ```php use Gemini\Laravel\Facades\Gemini; use Gemini\Resources\GenerativeModel; use Gemini\Resources\Models; use Gemini\Responses\GenerativeModel\GenerateContentResponse; // --- Basic fake --- Gemini::fake([ GenerateContentResponse::fake([ 'candidates' => [[ 'content' => ['parts' => [['text' => 'Mocked answer']]], ]], ]), ]); $result = Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('Tell me a joke'); expect($result->text())->toBe('Mocked answer'); // --- Add more responses mid-test --- Gemini::addResponses([ GenerateContentResponse::fake([ 'candidates' => [[ 'content' => ['parts' => [['text' => 'Second response']]], ]], ]), ]); // --- Assert a specific call was made --- Gemini::assertSent( resource: GenerativeModel::class, model: 'gemini-2.0-flash', callback: fn(string $method, array $params) => $method === 'generateContent' && $params[0] === 'Tell me a joke' ); // --- Assert via the resource instance --- Gemini::generativeModel('gemini-2.0-flash')->assertSent( fn(string $method, array $params) => $method === 'generateContent' ); // --- Assert call count --- Gemini::assertSent(GenerativeModel::class, 'gemini-2.0-flash', 1); // --- Assert a call was NOT made --- Gemini::assertNotSent(Models::class); // --- Assert nothing was sent at all --- Gemini::fake(); Gemini::assertNothingSent(); // --- Simulate an API error --- use Gemini\Exceptions\ErrorException; Gemini::fake([ new ErrorException([ 'message' => 'The model does not exist', 'status' => 'INVALID_ARGUMENT', 'code' => 400, ]), ]); expect(fn () => Gemini::generativeModel('gemini-2.0-flash')->generateContent('test')) ->toThrow(ErrorException::class); ``` ``` -------------------------------- ### Define Callable Tools for Function Calling Source: https://context7.com/google-gemini-php/laravel/llms.txt Configure the model to invoke application logic by defining callable tools. Ensure the function declaration accurately describes the function's purpose and parameters. ```php 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; $chat = Gemini::generativeModel(model: 'gemini-2.0-flash') ->withTool(new Tool( functionDeclarations: [ new FunctionDeclaration( name: 'get_weather', description: 'Returns current temperature for a city', parameters: new Schema( type: DataType::OBJECT, properties: [ 'city' => new Schema(type: DataType::STRING, description: 'City name'), ], required: ['city'], ), ), ], )) ->startChat(); $response = $chat->sendMessage('What is the weather in Paris right now?'); if ($response->parts()[0]->functionCall !== null) { $call = $response->parts()[0]->functionCall; // FunctionCall { name: 'get_weather', args: ['city' => 'Paris'] } // Execute your actual logic $temperature = 22; // retrieved from weather service $functionResult = new Content( parts: [new Part( functionResponse: new FunctionResponse( name: $call->name, response: ['temperature' => $temperature, 'unit' => 'Celsius'], ), )], role: Role::USER, ); $response = $chat->sendMessage($functionResult); } echo $response->text(); // "The current temperature in Paris is 22°C." ``` -------------------------------- ### Text and Video Input Source: https://context7.com/google-gemini-php/laravel/llms.txt Reference a previously uploaded video file by its URI to generate descriptions or answer questions about video content. ```APIDOC ## `Gemini::generativeModel()` — Text and Video Input Reference a previously uploaded video file by its URI to generate descriptions or answer questions about video content. ```php use Gemini\Data\UploadedFile; use Gemini\Enums\MimeType; use Gemini\Laravel\Facades\Gemini; $result = Gemini::generativeModel(model: 'gemini-2.0-flash') ->generateContent([ 'List the main topics covered in this video.', new UploadedFile( fileUri: 'files/abc123xyz', // name or full URI from Files API mimeType: MimeType::VIDEO_MP4 ), ]); echo $result->text(); // The video covers: 1) Introduction to neural networks, 2) Backpropagation... ``` ``` -------------------------------- ### Generate Content with Text and Image Input (Multimodal) Source: https://context7.com/google-gemini-php/laravel/llms.txt Send multimodal prompts by including a Blob object containing image data alongside a text prompt. This allows for vision-based queries. ```php use Gemini\Data\Blob; use Gemini\Enums\MimeType; use Gemini\Laravel\Facades\Gemini; $imageData = base64_encode(file_get_contents('/path/to/receipt.jpg')); $result = Gemini::generativeModel(model: 'gemini-2.0-flash') ->generateContent([ 'What items are listed on this receipt and what is the total?', new Blob( mimeType: MimeType::IMAGE_JPEG, data: $imageData ), ]); echo $result->text(); // Items: Coffee ($4.50), Sandwich ($9.00). Total: $13.50 ``` -------------------------------- ### Enable Thinking Mode for Gemini Models Source: https://context7.com/google-gemini-php/laravel/llms.txt Use `withGenerationConfig` and `ThinkingConfig` to enable explicit chain-of-thought reasoning. This separates internal thought processes from the final answer. ```php use Gemini\Data\GenerationConfig; use Gemini\Data\ThinkingConfig; use Gemini\Laravel\Facades\Gemini; $response = Gemini::generativeModel(model: 'gemini-2.0-flash-thinking-exp') ->withGenerationConfig(new GenerationConfig( thinkingConfig: new ThinkingConfig( includeThoughts: true, thinkingBudget: 2048, // max tokens spent on internal reasoning ), )) ->generateContent('A farmer has 17 sheep. All but 9 die. How many are left?'); foreach ($response->candidates[0]->content->parts as $part) { if ($part->thought === true) { echo "[Thinking] " . $part->text . "\n"; } else { echo "[Answer] " . $part->text . "\n"; // "9 sheep remain." } } ``` -------------------------------- ### Set System Instructions for Gemini Model Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Customize Gemini model behavior by providing system instructions. This allows defining the model's role, personality, response format, and guardrails. ```php use Gemini\Data\Content; use Gemini\Laravel\Facades\Gemini; $response = Gemini::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... ``` -------------------------------- ### List and Delete Files Source: https://context7.com/google-gemini-php/laravel/llms.txt Paginate through uploaded files and remove those that are no longer needed. ```APIDOC ## `Gemini::files()` — List and Delete Files Paginate through uploaded files and remove those that are no longer needed. ```php use Gemini\Laravel\Facades\Gemini; $files = Gemini::files(); // List first page $page = $files->list(pageSize: 20); foreach ($page->files as $file) { echo "{$file->name} — {$file->displayName} — {$file->sizeBytes} bytes\n"; } // Fetch next page if available if ($page->nextPageToken) { $page2 = $files->list(pageSize: 20, nextPageToken: $page->nextPageToken); } // Retrieve metadata for a specific file $meta = $files->metadataGet('files/abc123'); echo "State: {$meta->state->value}, Expires: {$meta->expirationTime}\n"; // Delete a file $files->delete('files/abc123'); ``` ``` -------------------------------- ### Enable Thinking Mode for Model Reasoning Source: https://github.com/google-gemini-php/laravel/blob/main/README.md Configure the model to include its reasoning process by setting `includeThoughts` to true and optionally specifying a `thinkingBudget`. This is useful for complex problem-solving. ```php use Gemini\Data\GenerationConfig; use Gemini\Data\ThinkingConfig; use Gemini\Laravel\Facades\Gemini; $response = Gemini::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"; } } ```