百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
L

laravel

> 后端框架
开源

⚡️ Gemini PHP for Laravel 是一个由社区维护的 PHP API 客户端,可让您与 Gemini AI API 进行交互。

637 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

⚡️ Gemini PHP for Laravel 是一个由社区维护的 PHP API 客户端,可让您与 Gemini AI API 进行交互。


Gemini PHP for Laravel is a community-maintained PHP API client that allows you to interact with the Gemini AI API.

  • Fatih AYDIN github.com/aydinfatih
  • Vytautas Smilingis github.com/Plytas

For more information, take a look at the google-gemini-php/client repository.

Table of Contents

  • Prerequisites
  • Setup
    • Installation
    • Setup your API key
    • Upgrade to 2.0
  • Usage
    • Chat Resource
      • Text-only Input
      • Text-and-image Input
      • Text-and-video Input
      • Image Generation
      • Multi-turn Conversations (Chat)
      • Chat with Streaming
      • Stream Generate Content
      • Structured Output
      • Function calling
      • Code Execution
      • Grounding with Google Search
      • System Instructions
      • Speech generation
      • Thinking Mode
      • Count tokens
      • Configuration
    • File Management
      • File Upload
      • List Files
      • Get File Metadata
      • Delete File
    • Cached Content
      • Create Cached Content
      • List Cached Content
      • Get Cached Content
      • Update Cached Content
      • Delete Cached Content
      • Use Cached Content
    • Embedding Resource
    • Models
      • List Models
      • Get Model
  • Troubleshooting
  • Testing

Prerequisites

To complete this quickstart, make sure that your development environment meets the following requirements:

  • Requires PHP 8.1+
  • Requires Laravel 9,10,11,12

Setup

Installation

First, install Gemini via the Composer package manager:

bash
composer require google-gemini-php/laravel

Next, execute the install command:

bash
php artisan gemini:install

This will create a config/gemini.php configuration file in your project, which you can modify to your needs using environment variables. Blank environment variables for the Gemini API key is already appended to your .env file.

GEMINI_API_KEY=

You can also define the following environment variables.

GEMINI_BASE_URL=
GEMINI_REQUEST_TIMEOUT=

Setup your API key

To use the Gemini API, you'll need an API key. If you don't already have one, create a key in Google AI Studio.

Get an API key

Upgrade to 2.0

Starting 2.0 release this package will work only with Gemini v1beta API (see API versions).

To update, run this command:

bash
composer require google-gemini-php/laravel:^2.0

This release introduces support for new features:

  • Structured output
  • System instructions
  • File uploads
  • Function calling
  • Code execution
  • Grounding with Google Search
  • Cached content
  • Thinking model configuration
  • Speech model configuration

\Gemini\Enums\ModelType enum has been deprecated and will be removed in next major version. Together with this Gemini::geminiPro() and Gemini::geminiFlash() methods have been removed. We suggest using Gemini::generativeModel() method and pass in the model string directly. All methods that had previously accepted ModelType enum now accept a BackedEnum. We recommend implementing your own enum for convenience.

There may be other breaking changes not listed here. If you encounter any issues, please submit an issue or a pull request.

Usage

Interact with Gemini's API:

php
use Gemini\Enums\ModelVariation;
use Gemini\GeminiHelper;
use Gemini\Laravel\Facades\Gemini;

$result = Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('Hello');

$result->text(); // Hello! How can I assist you today?

// Helper method usage
$result = Gemini::generativeModel(
    model: GeminiHelper::generateGeminiModel(
        variation: ModelVariation::FLASH,
        generation: 2.5,
        version: "preview-04-17"
    ), // models/gemini-2.5-flash-preview-04-17
)->generateContent('Hello');

$result->text(); // Hello! How can I assist you today?

Chat Resource

For a complete list of supported input formats and methods in Gemini API v1, see the models documentation.

Text-only Input

Generate a response from the model given an input message.

php
use Gemini\Laravel\Facades\Gemini;

$result = Gemini::generativeModel(model: 'gemini-2.0-flash')->generateContent('Hello');

$result->text(); // Hello! How can I assist you today?

Text-and-image Input

Generate responses by providing both text prompts and images to the Gemini model.

…

Text-and-video Input

Process video content and get AI-generated descriptions using the Gemini API with an uploaded video file.

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...

Image Generation

Generate images from text prompts using the Imagen model.

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));

Multi-turn Conversations (Chat)

Using Gemini, you can build freeform conversations across multiple turns.

…

Chat with Streaming

You can also stream the response in a chat session. The history is automatically updated with the full response after the stream completes.

php
use Gemini\Laravel\Facades\Gemini;

$chat = Gemini::generativeModel(model: 'gemini-2.0-flash')->startChat();

$stream = $chat->streamSendMessage('Hello');

foreach ($stream as $response) {
    echo $response->text();
}

Stream Generate Content

By default, the model returns a response after completing the entire generation process. You can achieve faster interactions by not waiting for the entire result, and instead use streaming to handle partial results.

php
use Gemini\Laravel\Facades\Gemini;

$stream = Gemini::generativeModel(model: 'gemini-2.0-flash')
    ->streamGenerateContent('Write long a story about a magic backpack.');

foreach ($stream as $response) {
    echo $response->text();
}

Structured Output

Gemini generates unstructured text by default, but some applications require structured text. For these use cases, you can constrain Gemini to respond with JSON, a structured data format suitable for automated processing. You can also constrain the model to respond with one of the options specified in an enum.

…

Function calling

Gemini provides the ability to define and utilize custom functions that the model can call during conversations. This enables the model to perform specific actions or calculations through your defined functions.

…

Code Execution

Gemini models can generate and execute code automatically, and return the result to you. This is useful for tasks that require computation, data manipulation, or other programmatic operations.

…

Grounding with Google Search

Grounding with Google Search connects the Gemini model to real-time web content and works with all available languages. This allows Gemini to provide more accurate answers and cite verifiable sources beyond its knowledge cutoff.

For Gemini 2.0 and later models (Recommended):

Use the simple GoogleSearch tool which automatically handles search queries:

…

System Instructions

System instructions let you steer the behavior of the model based on your specific needs and use cases. You can set the role and personality of the model, define the format of responses, and provide goals and guardrails for model behavior.

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...

You can also combine system instructions with other features:

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());

Speech generation

Gemini allows generating speech from a text. To use that, make sure to use a model that supports this functionality. The model will output base64 encoded audio string.

Single speaker
…
Multi speaker
…

Thinking Mode

For models that support thinking mode (like Gemini 2.0), you can configure the model to show its reasoning process. This is useful for complex problem-solving and understanding how the model arrives at its answers.

…

Count tokens

When using long prompts, it might be useful to count tokens before sending any content to the model.

php
use Gemini\Laravel\Facades\Gemini;

$response = Gemini::generativeModel(model: 'gemini-2.0-flash')
    ->countTokens('Write a story about a magic backpack.');

echo $response->totalTokens; // 9

Configuration

Every prompt you send to the model includes parameter values that control how the model generates a response. The model can generate different results for different parameter values. Learn more about model parameters.

Also, you can use safety settings to adjust the likelihood of getting responses that may be considered harmful. By default, safety settings block content with medium and/or high probability of being unsafe content across all dimensions. Learn more about safety settings.

…

File Management

The File API lets you store up to 20GB of files per project, with a per-file maximum size of 2GB. Files are stored for 48 hours and can be accessed in

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPgeminigemini-apigoogle-aigoogle-ai-client-sdk

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架