class GeminiGateway implements Gateway, StepTextGateway

Traits

Methods

array
buildStepBody(Provider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, StepContext $stepContext)

Build the request body for the current text generation step.

array
buildTextRequestBody(Provider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options)

Build the request body for the Gemini Interactions API.

array
buildFunctionResultSteps(array $toolResults)

Build function result steps from tool results for the Gemini API.

array
buildResponseSchema(array $schema)

Build the response schema for structured output.

string|array
toolChoiceConfig(ToolChoice $choice)

Map a tool choice to the Gemini tool choice configuration.

createClient(string $baseUrl, array $headers = [], array $configuredHeaders = [], int|null $timeout = 60, bool $throw = true)

Create an HTTP client with the provider's request options.

string
httpConnection(Provider $provider)

Select a boot-registered connection without retaining dynamic provider names.

client(Provider $provider, int|null $timeout = null)

Get an HTTP client for the Gemini API.

string
baseUrl(Provider $provider)

Get the base URL for the Gemini API.

processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody)

Process a Gemini streaming response and yield Hypervel stream events.

void
appendStepText(array $steps, int|string $index, string $type, string $text, string $key = 'content')

Append streamed text to the step being accumulated at the given index.

string
generateEventId()

Generate a lowercase UUID v7 for use as a stream event ID.

array
mapAttachments(Collection $attachments)

Map the given Hypervel attachments to Gemini content blocks.

array
mapAttachment(mixed $attachment)

Map a Hypervel attachment to a Gemini content block.

string
contentTypeFor(string|null $mime)

Resolve the Gemini content block type for the given MIME type.

bool
isYouTubeUrl(string $url)

Determine if the given URL is a YouTube URL, which Gemini accepts as a file URI.

string
normalizeEmbeddingModel(string $model)

Normalize model names accepted by the Gemini API.

array
mapEmbeddingInput(mixed $input)

Map a Hypervel embeddings input to a Gemini content part.

array
mapMessagesToInput(array $messages)

Map the given Hypervel messages to Gemini interaction input steps.

void
mapUserMessage(UserMessage|Message $message, array $input)

Map a user message to a Gemini user input step.

void
mapAssistantMessage(AssistantMessage|Message $message, array $input)

Map an assistant message to the Gemini steps that produced it.

void
mapToolResultMessage(ToolResultMessage|Message $message, array $input)

Map a tool result message to Gemini function result steps.

array
mapTools(array $tools, Provider $provider)

Map the given tools to Gemini tool definitions.

array
mapTool(Tool $tool)

Map a regular tool to a Gemini function declaration.

array
convertNullableTypes(array $schema)

Recursively convert JSON Schema nullable types to OpenAPI-style for Gemini.

array
mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to a Gemini provider tool definition.

array
mapCodeExecutionTool(CodeExecution $tool, Provider $provider)

Map a code execution tool to a Gemini code execution definition.

array
mapFileSearchTool(FileSearch $tool, Provider $provider)

Map a file search tool to a Gemini file search definition.

array
mapWebFetchTool(WebFetch $tool, Provider $provider)

Map a web fetch tool to a Gemini URL context definition.

array
mapWebSearchTool(WebSearch $tool, Provider $provider)

Map a web search tool to a Gemini Google Search definition.

array
decodeStructuredOutput(string|null $text)

Decode a structured output payload, tolerating markdown code fences.

static string
joinReasoning(iterable $blocks)

Join reasoning blocks, separating each block with a blank line.

void
validateTextResponse(array $data)

Validate the Gemini response data.

parseTextResponse(array $data, Provider $provider, string $model, bool $structured)

Parse the Gemini response data into a single step response.

array
replayableSteps(array $steps)

Get the steps that must be replayed verbatim on the next request.

array
extractProviderToolCalls(array $steps)

Extract the provider-executed tool steps, such as search and code execution.

bool
isProviderToolStep(array $step)

Determine if the given step was executed by Gemini rather than by us.

bool
isThinkingStep(array $step)

Determine if a step carries the model's reasoning.

string
extractReasoning(array $steps)

Extract the reasoning text from the response steps.

string
extractText(array $steps)

Extract the answer text from the model output steps.

string
textOf(array $step)

Concatenate the text blocks of the given step, which thought steps carry as a summary.

array
extractFunctionCallSteps(array $steps)

Extract the steps carrying function calls.

array
mapToolCalls(array $functionCallSteps, string|null $thoughtSignature = null)

Map function call steps to ToolCall DTOs.

string|null
thoughtSignature(array $steps)

Get the signature of the turn's last thought step, which the next request must replay beside its calls.

array
decodeArguments(mixed $arguments)

Normalize function call arguments, which stream as a partial JSON string.

extractCitations(array $steps)

Extract citations from the annotations Gemini attaches to its text blocks.

extractUsage(array $data)

Extract usage data from the response.

extractImageUsage(array $data)

Extract usage data from an image generation response.

int|null
modalityTokens(array $details, string $modality)

Get the token count Gemini reported for the given modality.

FinishReason
extractFinishReason(array $data, array $functionCallSteps)

Extract and map the finish reason from the Gemini response.

bool
wasBlocked(array $errors)

Determine if the interaction failed because Gemini withheld the content.

mixed
withErrorHandling(string $providerName, Closure $callback)

Execute a callback with failoverable error handling.

int|null
retryAfterSeconds(Throwable $exception)

Get the short Retry-After delay of a rate limited or overloaded response, if it has one.

bool
isInsufficientCredits(RequestException $exception)

Determine if the response is a 402, or a 429 insufficient credits or quota error rather than a rate limit.

array
overloadedStatusCodes()

Get the status codes that indicate a provider is transiently unavailable and the request should fail over.

array
insufficientCreditPatterns()

Get the patterns used to detect insufficient credits or quota errors.

array
insufficientCreditCodes()

Get the error codes or types that indicate insufficient credits or quota on a 429 response.

parseServerSentEvents(StreamInterface $streamBody)

Parse an SSE stream body into decoded JSON data objects.

string
readLine(StreamInterface $streamBody)

Read one line without waiting for a larger body buffer to fill.

string
pcmToWav(string $pcm, int $sampleRate = 24000, int $channels = 1, int $bitsPerSample = 16)

Wrap PCM audio in a WAV container.

__construct(Dispatcher $events)

Create a Gemini gateway.

generateTextStep(TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Generate text for a single Gemini step.

generateStreamStep(string $invocationId, TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Stream text for a single Gemini step.

generateImage(ImageProvider $provider, string $model, string $prompt, array $attachments = [], string|null $size = null, string|null $quality = null, int|null $timeout = null, array $providerOptions = [])

Generate an image.

array
outputBlocks(array $data, string $type)

Get the content blocks of the given type from an interaction response.

generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])

Generate embeddings for the given inputs.

generateAudio(AudioProvider $provider, string $model, string $text, string $voice, string|null $instructions = null, int $timeout = 30, array $providerOptions = [])

Generate audio from the given text.

generateTranscription(TranscriptionProvider $provider, string $model, TranscribableAudio $audio, string|null $language = null, bool $diarize = false, int $timeout = 30, array $providerOptions = [])

Generate text from the given audio.

transcribeWithConfig(TranscriptionProvider $provider, string $model, array $audioBlock, string|null $language, bool $diarize, int $timeout, array $providerOptions)

Transcribe the given audio using the Gemini transcription config.

speakerSegments(array $steps)

Group the word annotations Gemini returns into one segment per speaker turn.

array
wordAnnotations(array $steps)

Get the word annotations Gemini attached to the transcribed text.

float
offsetToSeconds(string $offset)

Convert a Gemini duration offset, such as "1.500s", to seconds.

transcribeWithPrompt(TranscriptionProvider $provider, string $model, array $audioBlock, string|null $language, bool $diarize, int $timeout, array $providerOptions)

Transcribe the given audio by asking a general purpose model for the text.

float
timestampToSeconds(string $timestamp)

Convert a timestamp string to seconds.

Details

in BuildsTextRequests at line 32
protected array buildStepBody(Provider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, StepContext $stepContext)

Build the request body for the current text generation step.

Parameters

Provider $provider
string $model
string|null $instructions
array $messages
array $tools
array|null $schema
TextGenerationOptions|null $options
StepContext $stepContext

Return Value

array

in BuildsTextRequests at line 48
protected array buildTextRequestBody(Provider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options)

Build the request body for the Gemini Interactions API.

Parameters

Provider $provider
string $model
string|null $instructions
array $messages
array $tools
array|null $schema
TextGenerationOptions|null $options

Return Value

array

in BuildsTextRequests at line 141
protected array buildFunctionResultSteps(array $toolResults)

Build function result steps from tool results for the Gemini API.

Parameters

array $toolResults

Return Value

array

in BuildsTextRequests at line 154
protected array buildResponseSchema(array $schema)

Build the response schema for structured output.

Parameters

array $schema

Return Value

array

in BuildsTextRequests at line 162
protected string|array toolChoiceConfig(ToolChoice $choice)

Map a tool choice to the Gemini tool choice configuration.

Parameters

ToolChoice $choice

Return Value

string|array

in CreatesClient at line 21
protected PendingRequest createClient(string $baseUrl, array $headers = [], array $configuredHeaders = [], int|null $timeout = 60, bool $throw = true)

Create an HTTP client with the provider's request options.

Parameters

string $baseUrl
array $headers
array $configuredHeaders
int|null $timeout
bool $throw

Return Value

PendingRequest

in CreatesClient at line 43
protected string httpConnection(Provider $provider)

Select a boot-registered connection without retaining dynamic provider names.

Parameters

Provider $provider

Return Value

string

protected PendingRequest client(Provider $provider, int|null $timeout = null)

Get an HTTP client for the Gemini API.

Parameters

Provider $provider
int|null $timeout

Return Value

PendingRequest

protected string baseUrl(Provider $provider)

Get the base URL for the Gemini API.

Parameters

Provider $provider

Return Value

string

protected Generator processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody)

Process a Gemini streaming response and yield Hypervel stream events.

Parameters

string $invocationId
Provider $provider
string $model
StreamInterface $streamBody

Return Value

Generator

in HandlesTextStreaming at line 262
protected void appendStepText(array $steps, int|string $index, string $type, string $text, string $key = 'content')

Append streamed text to the step being accumulated at the given index.

Parameters

array $steps
int|string $index
string $type
string $text
string $key

Return Value

void

in HandlesTextStreaming at line 272
protected string generateEventId()

Generate a lowercase UUID v7 for use as a stream event ID.

Return Value

string

in MapsAttachments at line 36
protected array mapAttachments(Collection $attachments)

Map the given Hypervel attachments to Gemini content blocks.

Parameters

Collection $attachments

Return Value

array

in MapsAttachments at line 44
protected array mapAttachment(mixed $attachment)

Map a Hypervel attachment to a Gemini content block.

Parameters

mixed $attachment

Return Value

array

in MapsAttachments at line 165
protected string contentTypeFor(string|null $mime)

Resolve the Gemini content block type for the given MIME type.

Parameters

string|null $mime

Return Value

string

in MapsAttachments at line 178
protected bool isYouTubeUrl(string $url)

Determine if the given URL is a YouTube URL, which Gemini accepts as a file URI.

Parameters

string $url

Return Value

bool

protected string normalizeEmbeddingModel(string $model)

Normalize model names accepted by the Gemini API.

Parameters

string $model

Return Value

string

protected array mapEmbeddingInput(mixed $input)

Map a Hypervel embeddings input to a Gemini content part.

Parameters

mixed $input

Return Value

array

in MapsMessages at line 18
protected array mapMessagesToInput(array $messages)

Map the given Hypervel messages to Gemini interaction input steps.

Parameters

array $messages

Return Value

array

in MapsMessages at line 38
protected void mapUserMessage(UserMessage|Message $message, array $input)

Map a user message to a Gemini user input step.

Parameters

UserMessage|Message $message
array $input

Return Value

void

in MapsMessages at line 56
protected void mapAssistantMessage(AssistantMessage|Message $message, array $input)

Map an assistant message to the Gemini steps that produced it.

Parameters

AssistantMessage|Message $message
array $input

Return Value

void

in MapsMessages at line 97
protected void mapToolResultMessage(ToolResultMessage|Message $message, array $input)

Map a tool result message to Gemini function result steps.

Parameters

ToolResultMessage|Message $message
array $input

Return Value

void

in MapsTools at line 29
protected array mapTools(array $tools, Provider $provider)

Map the given tools to Gemini tool definitions.

Parameters

array $tools
Provider $provider

Return Value

array

in MapsTools at line 47
protected array mapTool(Tool $tool)

Map a regular tool to a Gemini function declaration.

Parameters

Tool $tool

Return Value

array

in MapsTools at line 76
protected array convertNullableTypes(array $schema)

Recursively convert JSON Schema nullable types to OpenAPI-style for Gemini.

Parameters

array $schema

Return Value

array

in MapsTools at line 106
protected array mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to a Gemini provider tool definition.

Parameters

ProviderTool $tool
Provider $provider

Return Value

array

in MapsTools at line 120
protected array mapCodeExecutionTool(CodeExecution $tool, Provider $provider)

Map a code execution tool to a Gemini code execution definition.

Parameters

CodeExecution $tool
Provider $provider

Return Value

array

in MapsTools at line 132
protected array mapFileSearchTool(FileSearch $tool, Provider $provider)

Map a file search tool to a Gemini file search definition.

Parameters

FileSearch $tool
Provider $provider

Return Value

array

in MapsTools at line 144
protected array mapWebFetchTool(WebFetch $tool, Provider $provider)

Map a web fetch tool to a Gemini URL context definition.

Parameters

WebFetch $tool
Provider $provider

Return Value

array

in MapsTools at line 156
protected array mapWebSearchTool(WebSearch $tool, Provider $provider)

Map a web search tool to a Gemini Google Search definition.

Parameters

WebSearch $tool
Provider $provider

Return Value

array

protected array decodeStructuredOutput(string|null $text)

Decode a structured output payload, tolerating markdown code fences.

Parameters

string|null $text

Return Value

array

in JoinsReasoning at line 16
static protected string joinReasoning(iterable $blocks)

Join reasoning blocks, separating each block with a blank line.

Parameters

iterable $blocks

Return Value

string

protected void validateTextResponse(array $data)

Validate the Gemini response data.

Parameters

array $data

Return Value

void

Exceptions

AiException

protected StepResponse parseTextResponse(array $data, Provider $provider, string $model, bool $structured)

Parse the Gemini response data into a single step response.

Parameters

array $data
Provider $provider
string $model
bool $structured

Return Value

StepResponse

protected array replayableSteps(array $steps)

Get the steps that must be replayed verbatim on the next request.

Parameters

array $steps

Return Value

array

in ParsesTextResponses at line 102
protected array extractProviderToolCalls(array $steps)

Extract the provider-executed tool steps, such as search and code execution.

Parameters

array $steps

Return Value

array

in ParsesTextResponses at line 117
protected bool isProviderToolStep(array $step)

Determine if the given step was executed by Gemini rather than by us.

Parameters

array $step

Return Value

bool

in ParsesTextResponses at line 128
protected bool isThinkingStep(array $step)

Determine if a step carries the model's reasoning.

Parameters

array $step

Return Value

bool

in ParsesTextResponses at line 136
protected string extractReasoning(array $steps)

Extract the reasoning text from the response steps.

Parameters

array $steps

Return Value

string

in ParsesTextResponses at line 147
protected string extractText(array $steps)

Extract the answer text from the model output steps.

Parameters

array $steps

Return Value

string

in ParsesTextResponses at line 158
protected string textOf(array $step)

Concatenate the text blocks of the given step, which thought steps carry as a summary.

Parameters

array $step

Return Value

string

in ParsesTextResponses at line 172
protected array extractFunctionCallSteps(array $steps)

Extract the steps carrying function calls.

Parameters

array $steps

Return Value

array

in ParsesTextResponses at line 184
protected array mapToolCalls(array $functionCallSteps, string|null $thoughtSignature = null)

Map function call steps to ToolCall DTOs.

Parameters

array $functionCallSteps
string|null $thoughtSignature

Return Value

array

in ParsesTextResponses at line 202
protected string|null thoughtSignature(array $steps)

Get the signature of the turn's last thought step, which the next request must replay beside its calls.

Parameters

array $steps

Return Value

string|null

in ParsesTextResponses at line 215
protected array decodeArguments(mixed $arguments)

Normalize function call arguments, which stream as a partial JSON string.

Parameters

mixed $arguments

Return Value

array

in ParsesTextResponses at line 229
protected Collection extractCitations(array $steps)

Extract citations from the annotations Gemini attaches to its text blocks.

Parameters

array $steps

Return Value

Collection

in ParsesTextResponses at line 256
protected TextUsage extractUsage(array $data)

Extract usage data from the response.

Parameters

array $data

Return Value

TextUsage

in ParsesTextResponses at line 274
protected ImageUsage extractImageUsage(array $data)

Extract usage data from an image generation response.

Parameters

array $data

Return Value

ImageUsage

in ParsesTextResponses at line 294
protected int|null modalityTokens(array $details, string $modality)

Get the token count Gemini reported for the given modality.

Parameters

array $details
string $modality

Return Value

int|null

in ParsesTextResponses at line 308
protected FinishReason extractFinishReason(array $data, array $functionCallSteps)

Extract and map the finish reason from the Gemini response.

Parameters

array $data
array $functionCallSteps

Return Value

FinishReason

in ParsesTextResponses at line 332
protected bool wasBlocked(array $errors)

Determine if the interaction failed because Gemini withheld the content.

Parameters

array $errors

Return Value

bool

protected mixed withErrorHandling(string $providerName, Closure $callback)

Execute a callback with failoverable error handling.

Parameters

string $providerName
Closure $callback

Return Value

mixed

protected int|null retryAfterSeconds(Throwable $exception)

Get the short Retry-After delay of a rate limited or overloaded response, if it has one.

Parameters

Throwable $exception

Return Value

int|null

protected bool isInsufficientCredits(RequestException $exception)

Determine if the response is a 402, or a 429 insufficient credits or quota error rather than a rate limit.

Parameters

RequestException $exception

Return Value

bool

protected array overloadedStatusCodes()

Get the status codes that indicate a provider is transiently unavailable and the request should fail over.

Return Value

array

protected array insufficientCreditPatterns()

Get the patterns used to detect insufficient credits or quota errors.

Return Value

array

protected array insufficientCreditCodes()

Get the error codes or types that indicate insufficient credits or quota on a 429 response.

Return Value

array

protected Generator parseServerSentEvents(StreamInterface $streamBody)

Parse an SSE stream body into decoded JSON data objects.

Parameters

StreamInterface $streamBody

Return Value

Generator

protected string readLine(StreamInterface $streamBody)

Read one line without waiting for a larger body buffer to fill.

Parameters

StreamInterface $streamBody

Return Value

string

in WrapsPcmAudio at line 12
protected string pcmToWav(string $pcm, int $sampleRate = 24000, int $channels = 1, int $bitsPerSample = 16)

Wrap PCM audio in a WAV container.

Parameters

string $pcm
int $sampleRate
int $channels
int $bitsPerSample

Return Value

string

at line 55
__construct(Dispatcher $events)

Create a Gemini gateway.

Parameters

Dispatcher $events

at line 62
StepResponse generateTextStep(TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Generate text for a single Gemini step.

Parameters

TextProvider $provider
string $model
string|null $instructions
array $messages
array $tools
array|null $schema
TextGenerationOptions|null $options
int|null $timeout
StepContext $stepContext

Return Value

StepResponse

at line 91
Generator generateStreamStep(string $invocationId, TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Stream text for a single Gemini step.

Parameters

string $invocationId
TextProvider $provider
string $model
string|null $instructions
array $messages
array $tools
array|null $schema
TextGenerationOptions|null $options
int|null $timeout
StepContext $stepContext

Return Value

Generator

at line 124
ImageResponse generateImage(ImageProvider $provider, string $model, string $prompt, array $attachments = [], string|null $size = null, string|null $quality = null, int|null $timeout = null, array $providerOptions = [])

Generate an image.

Parameters

ImageProvider $provider
string $model
string $prompt
array $attachments
string|null $size
string|null $quality
int|null $timeout
array $providerOptions

Return Value

ImageResponse

at line 178
protected array outputBlocks(array $data, string $type)

Get the content blocks of the given type from an interaction response.

Parameters

array $data
string $type

Return Value

array

at line 190
EmbeddingsResponse generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])

Generate embeddings for the given inputs.

Parameters

EmbeddingProvider $provider
string $model
array $inputs
int $dimensions
int $timeout
array $providerOptions

Return Value

EmbeddingsResponse

at line 230
AudioResponse generateAudio(AudioProvider $provider, string $model, string $text, string $voice, string|null $instructions = null, int $timeout = 30, array $providerOptions = [])

Generate audio from the given text.

Parameters

AudioProvider $provider
string $model
string $text
string $voice
string|null $instructions
int $timeout
array $providerOptions

Return Value

AudioResponse

Exceptions

RuntimeException

at line 293
TranscriptionResponse generateTranscription(TranscriptionProvider $provider, string $model, TranscribableAudio $audio, string|null $language = null, bool $diarize = false, int $timeout = 30, array $providerOptions = [])

Generate text from the given audio.

Parameters

TranscriptionProvider $provider
string $model
TranscribableAudio $audio
string|null $language
bool $diarize
int $timeout
array $providerOptions

Return Value

TranscriptionResponse

at line 319
protected TranscriptionResponse transcribeWithConfig(TranscriptionProvider $provider, string $model, array $audioBlock, string|null $language, bool $diarize, int $timeout, array $providerOptions)

Transcribe the given audio using the Gemini transcription config.

Parameters

TranscriptionProvider $provider
string $model
array $audioBlock
string|null $language
bool $diarize
int $timeout
array $providerOptions

Return Value

TranscriptionResponse

at line 373
protected Collection speakerSegments(array $steps)

Group the word annotations Gemini returns into one segment per speaker turn.

Parameters

array $steps

Return Value

Collection

at line 403
protected array wordAnnotations(array $steps)

Get the word annotations Gemini attached to the transcribed text.

Parameters

array $steps

Return Value

array

at line 415
protected float offsetToSeconds(string $offset)

Convert a Gemini duration offset, such as "1.500s", to seconds.

Parameters

string $offset

Return Value

float

at line 425
protected TranscriptionResponse transcribeWithPrompt(TranscriptionProvider $provider, string $model, array $audioBlock, string|null $language, bool $diarize, int $timeout, array $providerOptions)

Transcribe the given audio by asking a general purpose model for the text.

Parameters

TranscriptionProvider $provider
string $model
array $audioBlock
string|null $language
bool $diarize
int $timeout
array $providerOptions

Return Value

TranscriptionResponse

at line 518
protected float timestampToSeconds(string $timestamp)

Convert a timestamp string to seconds.

Parameters

string $timestamp

Return Value

float