Search by

adachsoft / ai-integration-gemini

Arkadiusz Adach

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

Package info

gitlab.com/a.adach/ai-integration-gemini

Issues

pkg:composer/adachsoft/ai-integration-gemini

Statistics

Installs: 57

Dependents: 0

Suggesters: 0

Stars: 0

v0.14.1 2026-11-16 21:19 UTC

README

Gemini SPI provider for adachsoft/ai-integration. It supports tool-calling chat with Gemini 2.5, 3.x, and 4.x models and uses Guzzle for HTTP requests.

Requirements

  • PHP ^8.3
  • adachsoft/ai-integration: ^0.10
  • adachsoft/ai-conversation-model: ^0.2
  • guzzlehttp/guzzle: ^7.0
  • A Gemini API key in GOOGLE_GEMINI_API_KEY

Installation

Install the provider in an application that already uses adachsoft/ai-integration:

composer require adachsoft/ai-integration-gemini

Usage

Create and register the Gemini provider as described in Configuration.

Configuration

Create the SPI provider and register it with the tool-calling facade:

use AdachSoft\AiIntegration\PublicApi\Builder\ToolCallingChatFacadeBuilder;
use AdachSoft\AiIntegrationGemini\Config\GeminiConfig;
use AdachSoft\AiIntegrationGemini\GeminiToolCallingChatSpiFactory;
use GuzzleHttp\Client;

$apiKey = getenv('GOOGLE_GEMINI_API_KEY');
if (!is_string($apiKey) || $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,
);

$spiProvider = (new GeminiToolCallingChatSpiFactory(new Client(), $config))->create();
$facade = (new ToolCallingChatFacadeBuilder())
    ->withSpiProvider('gemini', $spiProvider)
    ->build();

The application supplies provider-neutral messages and tool definitions from adachsoft/ai-conversation-model in ToolCallingChatRequestDto. The request's modelId may select a model for one call; otherwise the facade's provider profile or GeminiConfig supplies the default.

Shared messages and Gemini candidates

The integration uses the shared conversation model for messages, content parts, tool calls, tool results, usage, and cost. A successful chat() call returns AdachSoft\AiIntegration\Contract\ToolCalling\Dto\ChatCompletionDto:

  • Each Gemini candidate becomes an ordered ChatChoiceDto in $completion->choices.
  • A choice owns its content, tool calls, finish reason, and provider metadata. Tool calls from parallel Gemini function calls remain together on that choice.
  • Aggregate token usage, cost, and response-level metadata are available separately on the completion.

Select the choice whose content or tool calls the application will use. Do not assume that a completion has only one candidate or move choice-specific tool-call metadata to the completion.

Tool-call history and thought signatures

For a follow-up request, preserve the selected choice as the original assistant message, including its content, all tool calls, and choice metadata. Then append a tool-results message containing a result for each call. This is especially important for Gemini 3.x and 4.x thought signatures:

  • Each signature belongs to the metadata of the individual ToolCallDto that carried it.
  • Do not copy a signature between parallel calls or place it in request-level metadata['thoughtSignature'].
  • Do not reconstruct the assistant history from only response-level tool-call data; use the chosen ChatChoiceDto's content, toolCalls, and metadata.

The legacy ai_integration-thought_signature_fallback parameter is ignored and stripped for compatibility. It does not provide or restore a signature. Remove it from application configuration and preserve the original per-call metadata instead.

Multimodal content and roles

The provider maps ordered text and media parts in requests and responses:

  • Inline/base64 media is sent as Gemini inlineData; remote URI or file-ID sources are sent as fileData.
  • Media returned by a tool is represented in Gemini function responses using functionResponse.parts and $ref entries in the response object.
  • Inline media in Gemini responses is mapped to shared media content parts, preserving its position relative to text.
  • Both System and Developer conversation roles are mapped to Gemini system instructions. Gemini does not receive a separate developer role; the configured system-message strategy determines whether later instructions are placed inline.

See AI integration parameters for system-message strategies, request profiles, and schema options.

Tool parameter schemas

Tool parameter schemas are normalized before being sent to Gemini. A type array such as ['string', 'array'] becomes anyOf, with each type-specific constraint placed on its matching branch. A null member is removed and represented as nullable: true. This normalization also applies recursively in both strict and off modes; strict mode additionally filters unsupported schema keys.

Generation parameters

Ordinary request parameters are forwarded to Gemini's generationConfig after the provider removes recognized ai_integration-* parameters. The provider supplies its configured default temperature when the request omits temperature or sets it to null. Unsupported Gemini generation keys are not silently rewritten by the SPI mapper.

The conformance profile adapts the tester's generic parameters for Gemini: n becomes candidateCount, and maxTokens becomes maxOutputTokens.

Cost calculation

Register GeminiCostCalculatorFactory to calculate built-in Gemini costs:

use AdachSoft\AiIntegrationGemini\Cost\GeminiCostCalculatorFactory;

$facade = (new ToolCallingChatFacadeBuilder())
    ->withSpiProvider('gemini', $spiProvider)
    ->withCostCalculator(GeminiCostCalculatorFactory::createWithBuiltInPricing())
    ->build();

The returned shared CostDto exposes the exact decimal amount as $completion->cost->total->value and the currency as $completion->cost->currency->value. Gemini's thoughtsTokenCount is included in billable output tokens. See cost calculation for pricing and token details.

Tests and conformance profile

The default PHPUnit suite runs unit tests and excludes the production group. Live production tests make real Gemini API requests and may incur charges:

# Unit suite
vendor/bin/phpunit

# Live Gemini API tests; requires GOOGLE_GEMINI_API_KEY
vendor/bin/phpunit --group production

A provider profile based on adachsoft/ai-integration-tester 0.5.x is in tests/Production/Conformance. It uses GOOGLE_GEMINI_API_KEY, reads the model from GEMINI_MODEL (default gemini-3.5-flash), and registers ToolCallingScenarioPack and MultimodalScenarioPack without a file uploader. Production tests are intentionally excluded from the default unit run.

The focused production tests also accept model overrides: GEMINI_THINKING_MODEL (default gemini-3.1-pro-preview), GEMINI_PROFILE_MODEL (default gemini-3.5-flash), and GEMINI_COST_MODEL (default gemini-2.5-pro). The multiple_choices conformance scenario uses GEMINI_MULTIPLE_CHOICES_MODEL, which defaults to gemini-2.5-flash.

Migration from 0.11.x (breaking)

The 0.10 integration contract uses the shared conversation model and candidate-based completions. Code that uses the previous 0.11.x DTO shape must be updated:

  1. Replace provider-local/public API message and tool DTOs with the corresponding AdachSoft\AiConversationModel types.
  2. Read generated output from $completion->choices; select a ChatChoiceDto before accessing content or tool calls.
  3. Continue a tool conversation by appending an assistant message created from that selected choice (content, toolCalls, and metadata), followed by a ChatMessageDto::toolResults() message. Supply all results for parallel calls.
  4. Read cost through the shared CostDto: $cost->total->value and $cost->currency->value.
  5. Remove ai_integration-thought_signature_fallback. The legacy option is ignored; thought signatures must remain on their individual tool calls in conversation history.

Update dependency constraints to adachsoft/ai-integration ^0.10 and adachsoft/ai-conversation-model ^0.2 when moving to this contract.