gemini-api-php/client 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

gemini-api-php/client

Composer 安装命令:

composer require gemini-api-php/client

包简介

API client for Google's Gemini API

README 文档

README

Gemini API PHP Client - Example

Total Downloads Latest Version License

Gemini API PHP Client

Gemini API PHP Client allows you to use the Google's generative AI models, like Gemini Pro and Gemini Pro Vision.

This library is not developed or endorsed by Google.

Table of Contents

Installation

You need an API key to gain access to Google's Gemini API. Visit Google AI Studio to get an API key.

First step is to install the Gemini API PHP client with Composer.

composer require gemini-api-php/client

Gemini API PHP client does not come with an HTTP client. If you are just testing or do not have an HTTP client library in your project, you need to allow php-http/discovery composer plugin or install a PSR-18 compatible client library.

How to use

Basic text generation

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$client = new Client('GEMINI_API_KEY');
$response = $client->generativeModel(ModelName::GEMINI_PRO)->generateContent(
    new TextPart('PHP in less than 100 chars'),
);

print $response->text();
// PHP: A server-side scripting language used to create dynamic web applications.
// Easy to learn, widely used, and open-source.

Text generation with system instruction

System instruction is currently supported only in beta version

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$client = new Client('GEMINI_API_KEY');
$response = $client->withV1BetaVersion()
    ->generativeModel(ModelName::GEMINI_1_5_FLASH)
    ->withSystemInstruction('You are a cat. Your name is Neko.')
    ->generateContent(
        new TextPart('PHP in less than 100 chars'),
    );

print $response->text();
// Meow?  <?php echo 'Hello, world!'; ?>  Purrfectly concise, wouldn't you say?  *Stretches luxuriously*

Multimodal input

Image input modality is only enabled for Gemini Pro Vision model

use GeminiAPI\Client;
use GeminiAPI\Enums\MimeType;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\ImagePart;
use GeminiAPI\Resources\Parts\TextPart;

$client = new Client('GEMINI_API_KEY');
$response = $client->generativeModel(ModelName::GEMINI_PRO)->generateContent(
    new TextPart('Explain what is in the image'),
    new ImagePart(
        MimeType::IMAGE_JPEG,
        base64_encode(file_get_contents('elephpant.jpg')),
    ),
);

print $response->text();
// The image shows an elephant standing on the Earth.
// The elephant is made of metal and has a glowing symbol on its forehead.
// The Earth is surrounded by a network of glowing lines.
// The image is set against a starry background.

Chat Session (Multi-Turn Conversations)

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$client = new Client('GEMINI_API_KEY');
$chat = $client->generativeModel(ModelName::GEMINI_PRO)->startChat();

$response = $chat->sendMessage(new TextPart('Hello World in PHP'));
print $response->text();

$response = $chat->sendMessage(new TextPart('in Go'));
print $response->text();
<?php
echo "Hello World!";
?>

This code will print "Hello World!" to the standard output.
package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}

This code will print "Hello World!" to the standard output.

Chat Session with history

use GeminiAPI\Client;
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$history = [
    Content::text('Hello World in PHP', Role::User),
    Content::text(
        <<<TEXT
        <?php
        echo "Hello World!";
        ?>
        
        This code will print "Hello World!" to the standard output.
        TEXT,
        Role::Model,
    ),
];

$client = new Client('GEMINI_API_KEY');
$chat = $client->generativeModel(ModelName::GEMINI_PRO)
    ->startChat()
    ->withHistory($history);

$response = $chat->sendMessage(new TextPart('in Go'));
print $response->text();
package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}

This code will print "Hello World!" to the standard output.

Streaming responses

Requires curl extension to be enabled

In the streaming response, the callback function will be called whenever a response is returned from the server.

Long responses may be broken into separate responses, and you can start receiving responses faster using a content stream.

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\Responses\GenerateContentResponse;

$callback = function (GenerateContentResponse $response): void {
    static $count = 0;

    print "\nResponse #{$count}\n";
    print $response->text();
    $count++;
};

$client = new Client('GEMINI_API_KEY');
$client->generativeModel(ModelName::GEMINI_PRO)->generateContentStream(
    $callback,
    [new TextPart('PHP in less than 100 chars')],
);
// Response #0
// PHP: a versatile, general-purpose scripting language for web development, popular for
// Response #1
//  its simple syntax and rich library of functions.

Streaming Chat Session

Requires curl extension to be enabled

use GeminiAPI\Client;
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\Responses\GenerateContentResponse;

$history = [
    Content::text('Hello World in PHP', Role::User),
    Content::text(
        <<<TEXT
        <?php
        echo "Hello World!";
        ?>
        
        This code will print "Hello World!" to the standard output.
        TEXT,
        Role::Model,
    ),
];

$callback = function (GenerateContentResponse $response): void {
    static $count = 0;

    print "\nResponse #{$count}\n";
    print $response->text();
    $count++;
};

$client = new Client('GEMINI_API_KEY');
$chat = $client->generativeModel(ModelName::GEMINI_PRO)
    ->startChat()
    ->withHistory($history);

$chat->sendMessageStream($callback, new TextPart('in Go'));
Response #0
package main

import "fmt"

func main() {

Response #1
    fmt.Println("Hello World!")
}

This code will print "Hello World!" to the standard output.

Embed Content

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$client = new Client('GEMINI_API_KEY');
$response = $client->embeddingModel(ModelName::EMBEDDING_001)
    ->embedContent(
        new TextPart('PHP in less than 100 chars'),
    );

print_r($response->embedding->values);
// [
//    [0] => 0.041395925
//    [1] => -0.017692696
//    ...
// ]

Tokens counting

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$client = new Client('GEMINI_API_KEY');
$response = $client->generativeModel(ModelName::GEMINI_PRO)->countTokens(
    new TextPart('PHP in less than 100 chars'),
);

print $response->totalTokens;
// 10

Listing models

use GeminiAPI\Client;

$client = new Client('GEMINI_API_KEY');
$response = $client->listModels();

print_r($response->models);
//[
//  [0] => GeminiAPI\Resources\Model Object
//    (
//      [name] => models/gemini-pro
//      [displayName] => Gemini Pro
//      [description] => The best model for scaling across a wide range of tasks
//      ...
//    )
//  [1] => GeminiAPI\Resources\Model Object
//    (
//      [name] => models/gemini-pro-vision
//      [displayName] => Gemini Pro Vision
//      [description] => The best image understanding model to handle a broad range of applications
//      ...
//    )
//]

Advanced Usages

Using Beta version

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;

$client = (new Client('GEMINI_API_KEY'))
    ->withV1BetaVersion();
$response = $client->generativeModel(ModelName::GEMINI_PRO)->countTokens(
    new TextPart('PHP in less than 100 chars'),
);

print $response->totalTokens;
// 10

Safety Settings and Generation Configuration

use GeminiAPI\Client;
use GeminiAPI\Enums\HarmCategory;
use GeminiAPI\Enums\HarmBlockThreshold;
use GeminiAPI\GenerationConfig;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\SafetySetting;

$safetySetting = new SafetySetting(
    HarmCategory::HARM_CATEGORY_HATE_SPEECH,
    HarmBlockThreshold::BLOCK_LOW_AND_ABOVE,
);
$generationConfig = (new GenerationConfig())
    ->withCandidateCount(1)
    ->withMaxOutputTokens(40)
    ->withTemperature(0.5)
    ->withTopK(40)
    ->withTopP(0.6)
    ->withStopSequences(['STOP']);

$client = new Client('GEMINI_API_KEY');
$response = $client->generativeModel(ModelName::GEMINI_PRO)
    ->withAddedSafetySetting($safetySetting)
    ->withGenerationConfig($generationConfig)
    ->generateContent(
        new TextPart('PHP in less than 100 chars')
    );

Using your own HTTP client

use GeminiAPI\Client as GeminiClient;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;
use GuzzleHttp\Client as GuzzleClient;

$guzzle = new GuzzleClient([
  'proxy' => 'http://localhost:8125',
]);

$client = new GeminiClient('GEMINI_API_KEY', $guzzle);
$response = $client->generativeModel(ModelName::GEMINI_PRO)->generateContent(
    new TextPart('PHP in less than 100 chars')
);

Using your own HTTP client for streaming responses

Requires curl extension to be enabled

Since streaming responses are fetched using curl extension, they cannot use the custom HTTP client passed to the Gemini Client. You need to pass a CurlHandler if you want to override connection options.

The following curl options will be overwritten by the Gemini Client.

  • CURLOPT_URL
  • CURLOPT_POST
  • CURLOPT_POSTFIELDS
  • CURLOPT_WRITEFUNCTION

You can also pass the headers you want to be used in the requests.

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;
use GeminiAPI\Responses\GenerateContentResponse;

$callback = function (GenerateContentResponse $response): void {
    print $response->text();
};

$ch = curl_init();
curl_setopt($ch, \CURLOPT_PROXY, 'http://localhost:8125');

$client = new Client('GEMINI_API_KEY');
$client->withRequestHeaders([
        'User-Agent' => 'My Gemini-backed app'
    ])
    ->generativeModel(ModelName::GEMINI_PRO)
    ->generateContentStream(
        $callback,
        [new TextPart('PHP in less than 100 chars')],
        $ch,
    );

gemini-api-php/client 适用场景与选型建议

gemini-api-php/client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 273.05k 次下载、GitHub Stars 达 224, 最近一次更新时间为 2023 年 12 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「api」 「client」 「google」 「sdk」 「ai」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 gemini-api-php/client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 gemini-api-php/client 我们能提供哪些服务?
定制开发 / 二次开发

基于 gemini-api-php/client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 273.05k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 225
  • 点击次数: 24
  • 依赖项目数: 5
  • 推荐数: 0

GitHub 信息

  • Stars: 224
  • Watchers: 9
  • Forks: 49
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-12-23