Google Gemini API 的客户端

v1.4.4 2024-08-10 13:21 UTC

README

Gemini API PHP Client - Example

Total Downloads Latest Version License

Gemini API PHP 客户端

Gemini API PHP 客户端允许您使用 Google 的生成式 AI 模型,如 Gemini Pro 和 Gemini Pro Vision。

此库不是由 Google 开发或支持的。

目录

安装

您需要 API 密钥才能访问 Google 的 Gemini API。请访问 Google AI Studio 获取 API 密钥。

第一步是使用 Composer 安装 Gemini API PHP 客户端。

composer require gemini-api-php/client

Gemini API PHP 客户端不包含 HTTP 客户端。如果您只是测试或项目中没有 HTTP 客户端库,您需要允许 php-http/discovery composer 插件或安装一个 PSR-18 兼容的客户库。

如何使用

基本文本生成

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

$client = new Client('GEMINI_API_KEY');
$response = $client->geminiPro()->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.

多模态输入

图像输入模态仅适用于 Gemini Pro Vision 模型

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

$client = new Client('GEMINI_API_KEY');
$response = $client->geminiProVision()->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.

聊天会话(多轮对话)

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

$client = new Client('GEMINI_API_KEY');
$chat = $client->geminiPro()->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.

带有历史记录的聊天会话

use GeminiAPI\Client;
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
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->geminiPro()
    ->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.

流式响应

需要启用 curl 扩展

在流式响应中,每当服务器返回响应时,回调函数将被调用。

长响应可能会被分成单独的响应,您可以通过内容流更快地开始接收响应。

use GeminiAPI\Client;
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->geminiPro()->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.

流式聊天会话

需要启用 curl 扩展

use GeminiAPI\Client;
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
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->geminiPro()
    ->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.

嵌入内容

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

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

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

令牌计数

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

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

print $response->totalTokens;
// 10

列出模型

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
//      ...
//    )
//]

高级用法

安全设置和生成配置

use GeminiAPI\Client;
use GeminiAPI\Enums\HarmCategory;
use GeminiAPI\Enums\HarmBlockThreshold;
use GeminiAPI\GenerationConfig;
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->geminiPro()
    ->withAddedSafetySetting($safetySetting)
    ->withGenerationConfig($generationConfig)
    ->generateContent(
        new TextPart('PHP in less than 100 chars')
    );

使用您自己的 HTTP 客户端

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

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

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

使用您自己的 HTTP 客户端进行流式响应

需要启用 curl 扩展

由于流式响应是通过 curl 扩展获取的,因此它们不能使用传递给 Gemini 客户端的自定义 HTTP 客户端。如果您想覆盖连接选项,则需要传递一个 CurlHandler

以下 curl 选项将被 Gemini 客户端覆盖。

  • CURLOPT_URL
  • CURLOPT_POST
  • CURLOPT_POSTFIELDS
  • CURLOPT_WRITEFUNCTION

您还可以传递您希望在请求中使用的头。

use GeminiAPI\Client;
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, 'https://:8125');

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