承接 adachsoft/ai-integration-gemini 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

adachsoft/ai-integration-gemini

Composer 安装命令:

composer require adachsoft/ai-integration-gemini

包简介

Gemini SPI provider for adachsoft/ai-integration: tool-calling chat integration with Google Gemini 2.5 and 3.x models.

README 文档

README

Integration library that provides a single gemini SPI provider for adachsoft/ai-integration.

It enables tool-calling and reasoning for Gemini 2.5 and 3.x models using Guzzle as HTTP client.

Status: Provider implementation and unit tests are complete. A production test and example script are available for real end-to-end verification against Gemini API.

Requirements

  • PHP: ^8.3
  • adachsoft/ai-integration: ^0.6 (installed as a dependency)
  • guzzlehttp/guzzle: ^7.0
  • A valid Gemini API key exported as environment variable GOOGLE_GEMINI_API_KEY
  • Network access to https://generativelanguage.googleapis.com (v1beta/v1alpha endpoints, depending on model)

Installation

Install via Composer in a project that already uses adachsoft/ai-integration:

composer require adachsoft/ai-integration-gemini

Composer will register the AdachSoft\AiIntegrationGemini\ namespace pointing to the src/ directory.

Configuration

The provider is configured through the GeminiConfig value object:

use AdachSoft\AiIntegrationGemini\Config\GeminiConfig;

$config = new GeminiConfig(
    apiKey: getenv('GOOGLE_GEMINI_API_KEY') ?: '',
    defaultModelId: 'gemini-2.5-pro', // e.g. gemini-2.5-pro or gemini-3-pro-preview
    defaultThinkingLevel: 'HIGH',     // optional, reasoning level for v3 models
    defaultThinkingBudget: 2000,      // optional, reasoning token budget for v3 models
    // baseUri and defaultTemperature have sensible defaults
    toolCallingPipelineStrategy: 'self_healing', // 'self_healing' (default), 'noop', or 'retriable'
);

GOOGLE_GEMINI_API_KEY must be available in the environment (for example via your framework's .env handling or system-level configuration). This library does not manage or modify .env files.

AI integration parameters

In addition to standard Gemini generation parameters, the provider supports a small set of AI integration parameters that control how the request history is normalised before it is sent to the Gemini HTTP API.

These parameters are passed via ToolCallingChatRequestDto::$parameters and are recognised by their ai_integration- prefix. Recognised parameters are consumed by the provider and not forwarded to the underlying Gemini generationConfig payload.

Currently supported parameters:

  • ai_integration-leading_function_call_strategy
  • ai_integration-leading_function_call_user_message

For a detailed description of these parameters, their allowed values and behaviour, see:

Quick Start

The Gemini provider is exposed as a single SPI provider gemini for the ToolCallingChatFacade from adachsoft/ai-integration.

1. Build the SPI provider

use AdachSoft\AiIntegrationGemini\Config\GeminiConfig;
use AdachSoft\AiIntegrationGemini\GeminiToolCallingChatSpiFactory;
use GuzzleHttp\Client;

$apiKey = getenv('GOOGLE_GEMINI_API_KEY');

if ($apiKey === false || $apiKey === '') {
    throw new RuntimeException('GOOGLE_GEMINI_API_KEY is not configured.');
}

$config = new GeminiConfig(
    apiKey: $apiKey,
    defaultModelId: 'gemini-2.5-pro',
    defaultThinkingLevel: 'HIGH',
    defaultThinkingBudget: 2000,
    toolCallingPipelineStrategy: 'self_healing',
);

$factory = new GeminiToolCallingChatSpiFactory(
    httpClient: new Client(),
    config: $config,
);

$spiProvider = $factory->create();

2. Register provider in the facade

use AdachSoft\AiIntegration\PublicApi\Builder\ToolCallingChatFacadeBuilder;

$facadeBuilder = new ToolCallingChatFacadeBuilder();
$facadeBuilder->withSpiProvider('gemini', $spiProvider);
$facade = $facadeBuilder->build();

3. Define tools, generation parameters and run a simple roundtrip

use AdachSoft\AiIntegration\PublicApi\ToolCalling\Dto\ChatMessageDto;
use AdachSoft\AiIntegration\PublicApi\ToolCalling\Dto\Collection\ChatMessageDtoCollection;
use AdachSoft\AiIntegration\PublicApi\ToolCalling\Dto\Collection\ToolCallDtoCollection;
use AdachSoft\AiIntegration\PublicApi\ToolCalling\Dto\Collection\ToolDefinitionDtoCollection;
use AdachSoft\AiIntegration\PublicApi\ToolCalling\Dto\ToolCallDto;
use AdachSoft\AiIntegration\PublicApi\ToolCalling\Dto\ToolCallingChatRequestDto;
use AdachSoft\AiIntegration\PublicApi\ToolCalling\Dto\ToolDefinitionDto;

$tools = new ToolDefinitionDtoCollection([
    new ToolDefinitionDto(
        name: 'sum',
        description: 'Sums two integers',
        parametersSchema: [
            'type' => 'object',
            'properties' => [
                'a' => ['type' => 'integer'],
                'b' => ['type' => 'integer'],
            ],
            'required' => ['a', 'b'],
        ],
    ),
]);

$messages = new ChatMessageDtoCollection([
    ChatMessageDto::createUserMessage('Please call sum(a=2, b=3).'),
]);

// Generation parameters are forwarded 1:1 to the underlying provider.
$parameters = [
    'temperature' => 0.0,
];

$request1 = new ToolCallingChatRequestDto(
    messages: $messages,
    tools: $tools,
    providerId: 'gemini',
    modelId: 'gemini-2.5-pro',
    parameters: $parameters,
);

$response1 = $facade->chat($request1);

$toolCall = $response1->toolCalls->first();
$result = ((int) ($toolCall->arguments['a'] ?? 0)) + ((int) ($toolCall->arguments['b'] ?? 0));

// Tool result must be sent back as a tool-role message with explicit toolCalls collection.
$toolResponseMessage = ChatMessageDto::createToolMessage(
    content: (string) $result,
    toolCalls: new ToolCallDtoCollection([
        new ToolCallDto(
            toolCallId: $toolCall->toolCallId,
            toolName: $toolCall->toolName,
            arguments: $toolCall->arguments,
            result: null,
            metadata: [],
        ),
    ]),
);

$messages2 = new ChatMessageDtoCollection([
    ...$messages,
    $toolResponseMessage,
]);

$request2 = new ToolCallingChatRequestDto(
    messages: $messages2,
    tools: $tools,
    providerId: 'gemini',
    modelId: 'gemini-3-pro-preview',
    parameters: $parameters,
);

$response2 = $facade->chat($request2);

$finalText = $response2->result; // string|null

Generation parameters semantics

On the adachsoft/ai-integration side, generation parameters are carried in the ToolCallingChatRequestDto::$parameters array. For the Gemini provider:

  • parameters are forwarded 1:1 to the SPI request (ToolCallingChatSpiRequest::$parameters).
  • The Gemini SPI mapper forwards this array 1:1 to the Gemini generationConfig payload, excluding any ai_integration-* keys, which are consumed by the provider itself.
  • The only implicit behaviour is a default temperature value taken from GeminiConfig::$defaultTemperature when the temperature key is missing or null.
  • Any invalid or unsupported keys (except ai_integration-* parameters, which are validated separately) are considered configuration issues and are not filtered or altered by the mapper.

This means you can control Gemini generation knobs (such as temperature) directly from the public API request without changing the Gemini provider code, while still using ai_integration-* parameters to control integration-specific behaviour.

Examples and production test

This repository contains two ways to validate the integration end-to-end against real Gemini models:

1. CLI example

examples/test_gemini_tool_calling_via_spi.php shows a full roundtrip:

  • Builds GeminiToolCallingChatSpi and registers it under provider id gemini.
  • Defines a simple sum(a, b) tool.
  • Passes generation parameters (for example temperature) via the parameters array.
  • Runs two calls (2.5 and 3.x) and prints the final answer.
  • Exits with code 0 when a non-empty final result is returned; otherwise exits with 1.

Run it with:

export GOOGLE_GEMINI_API_KEY="your-key-here" # or equivalent for your environment
php examples/test_gemini_tool_calling_via_spi.php

2. Production PHPUnit test

tests/Production/GeminiProviderProductionTest.php contains a production-style PHPUnit test that:

  • Builds a real GeminiToolCallingChatSpi instance.
  • Registers it in ToolCallingChatFacadeBuilder under provider id gemini.
  • Uses a reveal_secret tool.
  • Executes a two-step tool-calling roundtrip for:
    • gemini-2.5-pro (expects at least one tool call and a non-empty final result),
    • gemini-3-pro-preview (same behaviour, additionally asserting presence of a non-empty thoughtSignature in response metadata).

The test is skipped automatically when GOOGLE_GEMINI_API_KEY is not configured in the environment.

The PHPUnit configuration defines separate test suites:

  • unit (default) - fast unit tests under tests/Unit.
  • production - live integration test under tests/Production.

Run tests with:

# unit tests only (default)
vendor/bin/phpunit

# production test against real Gemini API
vendor/bin/phpunit --testsuite production

Error handling and reasoning metadata

The provider translates Gemini-specific HTTP and JSON errors into SPI-level exceptions defined by adachsoft/ai-integration:

  • Quota/limit issues (HTTP 429 or RESOURCE_EXHAUSTED) become ResourceExhaustedSpiException.
  • Transient errors (5xx) become RetriableSpiException with an optional retryAfterSeconds hint.
  • Invalid or unexpected JSON structures become SpiException via GeminiInvalidResponseException.

For Gemini 3.x models, the provider can additionally expose reasoning-related metadata in the SPI response, such as:

  • thinking and thoughtSignature (when present in Gemini response),
  • usageMetadata with token usage details.

These are made available through the metadata and tokenUsage fields of ToolCallingChatSpiResponse.

adachsoft/ai-integration-gemini 适用场景与选型建议

adachsoft/ai-integration-gemini 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 21 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 26 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 adachsoft/ai-integration-gemini 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-26