GeminiGateway
class GeminiGateway implements Gateway, StepTextGateway
Traits
Methods
Build the request body for the current text generation step.
Build the request body for the Gemini Interactions API.
Build function result steps from tool results for the Gemini API.
Build the response schema for structured output.
Create an HTTP client with the provider's request options.
Select a boot-registered connection without retaining dynamic provider names.
Process a Gemini streaming response and yield Hypervel stream events.
Append streamed text to the step being accumulated at the given index.
Generate a lowercase UUID v7 for use as a stream event ID.
Map the given Hypervel attachments to Gemini content blocks.
Map a Hypervel attachment to a Gemini content block.
Resolve the Gemini content block type for the given MIME type.
Determine if the given URL is a YouTube URL, which Gemini accepts as a file URI.
Normalize model names accepted by the Gemini API.
Map a Hypervel embeddings input to a Gemini content part.
Map the given Hypervel messages to Gemini interaction input steps.
Map a user message to a Gemini user input step.
Map an assistant message to the Gemini steps that produced it.
Map a tool result message to Gemini function result steps.
Recursively convert JSON Schema nullable types to OpenAPI-style for Gemini.
Map a provider tool to a Gemini provider tool definition.
Map a code execution tool to a Gemini code execution definition.
Map a file search tool to a Gemini file search definition.
Map a web fetch tool to a Gemini URL context definition.
Map a web search tool to a Gemini Google Search definition.
Decode a structured output payload, tolerating markdown code fences.
Join reasoning blocks, separating each block with a blank line.
Parse the Gemini response data into a single step response.
Get the steps that must be replayed verbatim on the next request.
Extract the provider-executed tool steps, such as search and code execution.
Determine if the given step was executed by Gemini rather than by us.
Determine if a step carries the model's reasoning.
Extract the reasoning text from the response steps.
Extract the answer text from the model output steps.
Concatenate the text blocks of the given step, which thought steps carry as a summary.
Extract the steps carrying function calls.
Map function call steps to ToolCall DTOs.
Get the signature of the turn's last thought step, which the next request must replay beside its calls.
Normalize function call arguments, which stream as a partial JSON string.
Extract citations from the annotations Gemini attaches to its text blocks.
Extract usage data from an image generation response.
Get the token count Gemini reported for the given modality.
Extract and map the finish reason from the Gemini response.
Determine if the interaction failed because Gemini withheld the content.
Execute a callback with failoverable error handling.
Get the short Retry-After delay of a rate limited or overloaded response, if it has one.
Determine if the response is a 402, or a 429 insufficient credits or quota error rather than a rate limit.
Get the status codes that indicate a provider is transiently unavailable and the request should fail over.
Get the patterns used to detect insufficient credits or quota errors.
Get the error codes or types that indicate insufficient credits or quota on a 429 response.
Parse an SSE stream body into decoded JSON data objects.
Read one line without waiting for a larger body buffer to fill.
Wrap PCM audio in a WAV container.
Generate text for a single Gemini step.
Stream text for a single Gemini step.
Generate an image.
Get the content blocks of the given type from an interaction response.
Generate embeddings for the given inputs.
Generate audio from the given text.
Generate text from the given audio.
Transcribe the given audio using the Gemini transcription config.
Group the word annotations Gemini returns into one segment per speaker turn.
Get the word annotations Gemini attached to the transcribed text.
Convert a Gemini duration offset, such as "1.500s", to seconds.
Transcribe the given audio by asking a general purpose model for the text.
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.
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.
in
BuildsTextRequests at line 141
protected array
buildFunctionResultSteps(array $toolResults)
Build function result steps from tool results for the Gemini API.
in
BuildsTextRequests at line 154
protected array
buildResponseSchema(array $schema)
Build the response schema for structured output.
in
BuildsTextRequests at line 162
protected string|array
toolChoiceConfig(ToolChoice $choice)
Map a tool choice to the Gemini tool choice configuration.
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.
in
CreatesClient at line 43
protected string
httpConnection(Provider $provider)
Select a boot-registered connection without retaining dynamic provider names.
in
CreatesGeminiClient at line 18
protected PendingRequest
client(Provider $provider, int|null $timeout = null)
Get an HTTP client for the Gemini API.
in
CreatesGeminiClient at line 31
protected string
baseUrl(Provider $provider)
Get the base URL for the Gemini API.
in
HandlesTextStreaming at line 34
protected Generator
processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody)
Process a Gemini streaming response and yield Hypervel stream events.
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.
in
HandlesTextStreaming at line 272
protected string
generateEventId()
Generate a lowercase UUID v7 for use as a stream event ID.
in
MapsAttachments at line 36
protected array
mapAttachments(Collection $attachments)
Map the given Hypervel attachments to Gemini content blocks.
in
MapsAttachments at line 44
protected array
mapAttachment(mixed $attachment)
Map a Hypervel attachment to a Gemini content block.
in
MapsAttachments at line 165
protected string
contentTypeFor(string|null $mime)
Resolve the Gemini content block type for the given MIME type.
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.
in
MapsEmbeddingInputs at line 12
protected string
normalizeEmbeddingModel(string $model)
Normalize model names accepted by the Gemini API.
in
MapsEmbeddingInputs at line 20
protected array
mapEmbeddingInput(mixed $input)
Map a Hypervel embeddings input to a Gemini content part.
in
MapsMessages at line 18
protected array
mapMessagesToInput(array $messages)
Map the given Hypervel messages to Gemini interaction input steps.
in
MapsMessages at line 38
protected void
mapUserMessage(UserMessage|Message $message, array $input)
Map a user message to a Gemini user input step.
in
MapsMessages at line 56
protected void
mapAssistantMessage(AssistantMessage|Message $message, array $input)
Map an assistant message to the Gemini steps that produced it.
in
MapsMessages at line 97
protected void
mapToolResultMessage(ToolResultMessage|Message $message, array $input)
Map a tool result message to Gemini function result steps.
in
MapsTools at line 29
protected array
mapTools(array $tools, Provider $provider)
Map the given tools to Gemini tool definitions.
in
MapsTools at line 47
protected array
mapTool(Tool $tool)
Map a regular tool to a Gemini function declaration.
in
MapsTools at line 76
protected array
convertNullableTypes(array $schema)
Recursively convert JSON Schema nullable types to OpenAPI-style for Gemini.
in
MapsTools at line 106
protected array
mapProviderTool(ProviderTool $tool, Provider $provider)
Map a provider tool to a Gemini provider tool definition.
in
MapsTools at line 120
protected array
mapCodeExecutionTool(CodeExecution $tool, Provider $provider)
Map a code execution tool to a Gemini code execution definition.
in
MapsTools at line 132
protected array
mapFileSearchTool(FileSearch $tool, Provider $provider)
Map a file search tool to a Gemini file search definition.
in
MapsTools at line 144
protected array
mapWebFetchTool(WebFetch $tool, Provider $provider)
Map a web fetch tool to a Gemini URL context definition.
in
MapsTools at line 156
protected array
mapWebSearchTool(WebSearch $tool, Provider $provider)
Map a web search tool to a Gemini Google Search definition.
in
DecodesStructuredOutput at line 12
protected array
decodeStructuredOutput(string|null $text)
Decode a structured output payload, tolerating markdown code fences.
in
JoinsReasoning at line 16
static protected string
joinReasoning(iterable $blocks)
Join reasoning blocks, separating each block with a blank line.
in
ParsesTextResponses at line 37
protected void
validateTextResponse(array $data)
Validate the Gemini response data.
in
ParsesTextResponses at line 62
protected StepResponse
parseTextResponse(array $data, Provider $provider, string $model, bool $structured)
Parse the Gemini response data into a single step response.
in
ParsesTextResponses at line 89
protected array
replayableSteps(array $steps)
Get the steps that must be replayed verbatim on the next request.
in
ParsesTextResponses at line 102
protected array
extractProviderToolCalls(array $steps)
Extract the provider-executed tool steps, such as search and code execution.
in
ParsesTextResponses at line 117
protected bool
isProviderToolStep(array $step)
Determine if the given step was executed by Gemini rather than by us.
in
ParsesTextResponses at line 128
protected bool
isThinkingStep(array $step)
Determine if a step carries the model's reasoning.
in
ParsesTextResponses at line 136
protected string
extractReasoning(array $steps)
Extract the reasoning text from the response steps.
in
ParsesTextResponses at line 147
protected string
extractText(array $steps)
Extract the answer text from the model output steps.
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.
in
ParsesTextResponses at line 172
protected array
extractFunctionCallSteps(array $steps)
Extract the steps carrying function calls.
in
ParsesTextResponses at line 184
protected array
mapToolCalls(array $functionCallSteps, string|null $thoughtSignature = null)
Map function call steps to ToolCall DTOs.
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.
in
ParsesTextResponses at line 215
protected array
decodeArguments(mixed $arguments)
Normalize function call arguments, which stream as a partial JSON string.
in
ParsesTextResponses at line 229
protected Collection
extractCitations(array $steps)
Extract citations from the annotations Gemini attaches to its text blocks.
in
ParsesTextResponses at line 256
protected TextUsage
extractUsage(array $data)
Extract usage data from the response.
in
ParsesTextResponses at line 274
protected ImageUsage
extractImageUsage(array $data)
Extract usage data from an image generation response.
in
ParsesTextResponses at line 294
protected int|null
modalityTokens(array $details, string $modality)
Get the token count Gemini reported for the given modality.
in
ParsesTextResponses at line 308
protected FinishReason
extractFinishReason(array $data, array $functionCallSteps)
Extract and map the finish reason from the Gemini response.
in
ParsesTextResponses at line 332
protected bool
wasBlocked(array $errors)
Determine if the interaction failed because Gemini withheld the content.
in
HandlesFailoverErrors at line 26
protected mixed
withErrorHandling(string $providerName, Closure $callback)
Execute a callback with failoverable error handling.
in
HandlesFailoverErrors at line 91
protected int|null
retryAfterSeconds(Throwable $exception)
Get the short Retry-After delay of a rate limited or overloaded response, if it has one.
in
HandlesFailoverErrors at line 115
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.
in
HandlesFailoverErrors at line 138
protected array
overloadedStatusCodes()
Get the status codes that indicate a provider is transiently unavailable and the request should fail over.
in
HandlesFailoverErrors at line 148
protected array
insufficientCreditPatterns()
Get the patterns used to detect insufficient credits or quota errors.
in
HandlesFailoverErrors at line 158
protected array
insufficientCreditCodes()
Get the error codes or types that indicate insufficient credits or quota on a 429 response.
in
ParsesServerSentEvents at line 24
protected Generator
parseServerSentEvents(StreamInterface $streamBody)
Parse an SSE stream body into decoded JSON data objects.
in
ParsesServerSentEvents at line 52
protected string
readLine(StreamInterface $streamBody)
Read one line without waiting for a larger body buffer to fill.
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.
at line 55
__construct(Dispatcher $events)
Create a Gemini gateway.
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.
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.
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.
at line 178
protected array
outputBlocks(array $data, string $type)
Get the content blocks of the given type from an interaction response.
at line 190
EmbeddingsResponse
generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])
Generate embeddings for the given inputs.
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.
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.
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.
at line 373
protected Collection
speakerSegments(array $steps)
Group the word annotations Gemini returns into one segment per speaker turn.
at line 403
protected array
wordAnnotations(array $steps)
Get the word annotations Gemini attached to the transcribed text.
at line 415
protected float
offsetToSeconds(string $offset)
Convert a Gemini duration offset, such as "1.500s", to seconds.
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.
at line 518
protected float
timestampToSeconds(string $timestamp)
Convert a timestamp string to seconds.