class OpenRouterGateway implements Gateway, RerankingGateway, 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 Chat Completions API.

array
buildResponseFormat(array $schema, bool $strict)

Build the response format options for structured output.

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 OpenRouter API.

string
baseUrl(Provider $provider)

Get the base URL for the OpenRouter API.

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

Process a streaming response for a single text generation step.

array
mergeReasoningDetails(array $merged, array $details)

Merge consecutive reasoning fragments while preserving separate blocks.

string
reasoningTextIn(array $details)

Get the human readable reasoning carried by a delta's reasoning details.

string
generateEventId()

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

string
fallbackFilename(string|null $mimeType)

Derive a filename for a nameless document from its MIME type.

array
mapAttachments(Collection $attachments)

Map the given Hypervel attachments to Chat Completions content parts.

bool
isImage(UploadedFile $attachment)

Determine if the given uploaded file is an image.

bool
isAudio(UploadedFile $attachment)

Determine if the given uploaded file is an audio file.

array
mapMessagesToChat(array $messages, string|null $instructions = null)

Map the given Hypervel messages to Chat Completions messages format.

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

Map a user message to Chat Completions format.

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

Map an assistant message to Chat Completions format.

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

Map a tool result message to Chat Completions format.

array
serializeToolCallToChat(ToolCall $toolCall)

Serialize a tool call DTO to Chat Completions array format.

string
mapToolCallId(string $id)

Map a tool call or result ID to the provider's wire format.

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 OpenRouter response data.

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

Parse the OpenRouter response data into a single step response.

string
extractReasoning(array $message)

Extract the reasoning text from an assistant message.

array
extractReasoningDetails(array $message)

Extract the reasoning details to replay with the message's tool calls.

extractCitations(array $message)

Extract URL citations from the message annotations array.

extractUsage(array $data)

Extract usage data from the response.

FinishReason
extractFinishReason(array $choice)

Extract and map the finish reason from the response.

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.

array
mapTools(array $tools, Provider $provider)

Map the given tools to Chat Completions function definitions.

array
mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to an OpenRouter tool definition.

array
mapTool(Tool $tool)

Map a regular tool to a Chat Completions function definition.

string|array
mapToolChoice(ToolChoice $choice)

Map a tool choice to the Chat Completions tool_choice shape.

array
parseIndexedEmbeddings(array $records, int $expectedCount, string $providerName)

Return embedding values in input order without accepting ambiguous indices.

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.

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 Chat Completions 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 Chat Completions step.

array|null
streamOptions(Provider $provider)

Get the stream options sent with a streaming Chat Completions request.

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

Wrap PCM audio in a WAV container.

__construct(Dispatcher $events)

Create an OpenRouter gateway instance.

array
mapWebFetchTool(WebFetch $tool, Provider $provider)

Map a web fetch tool to an OpenRouter server tool definition.

array
mapWebSearchTool(WebSearch $tool, Provider $provider)

Map a web search tool to an OpenRouter server tool definition.

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

Generate images from the given prompt.

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

Generate audio from the given text.

string
resolveVoice(string $model, string $voice)

Resolve the alias voice for the given model.

string
audioResponseFormat(string $model)

Resolve the response_format the model accepts. Gemini TTS only accepts pcm.

string
audioResponseMimeType(string $format)

Map a response_format value to the HTTP audio MIME type.

bool
isGeminiTtsModel(string $model)

Determine whether the model uses Gemini text-to-speech.

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.

string
audioFormat(string $mimeType)

Map an audio MIME type to OpenRouter's input_audio.format value.

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

Generate embeddings for the given inputs.

rerank(RerankingProvider $provider, string $model, array $documents, string $query, int|null $limit = null, int $timeout = 30, array $providerOptions = [])

Rerank the given documents by relevance to a query.

Details

in BuildsTextRequests at line 20
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 36
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 Chat Completions 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 86
protected array buildResponseFormat(array $schema, bool $strict)

Build the response format options for structured output.

Parameters

array $schema
bool $strict

Return Value

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 OpenRouter API.

Parameters

Provider $provider
int|null $timeout

Return Value

PendingRequest

protected string baseUrl(Provider $provider)

Get the base URL for the OpenRouter API.

Parameters

Provider $provider

Return Value

string

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

Process a streaming response for a single text generation step.

Parameters

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

Return Value

Generator

in HandlesTextStreaming at line 276
protected array mergeReasoningDetails(array $merged, array $details)

Merge consecutive reasoning fragments while preserving separate blocks.

Parameters

array $merged
array $details

Return Value

array

in HandlesTextStreaming at line 309
protected string reasoningTextIn(array $details)

Get the human readable reasoning carried by a delta's reasoning details.

Parameters

array $details

Return Value

string

in HandlesTextStreaming at line 320
protected string generateEventId()

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

Return Value

string

protected string fallbackFilename(string|null $mimeType)

Derive a filename for a nameless document from its MIME type.

Parameters

string|null $mimeType

Return Value

string

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

Map the given Hypervel attachments to Chat Completions content parts.

Parameters

Collection $attachments

Return Value

array

in MapsAttachments at line 136
protected bool isImage(UploadedFile $attachment)

Determine if the given uploaded file is an image.

Parameters

UploadedFile $attachment

Return Value

bool

in MapsAttachments at line 153
protected bool isAudio(UploadedFile $attachment)

Determine if the given uploaded file is an audio file.

Parameters

UploadedFile $attachment

Return Value

bool

protected array mapMessagesToChat(array $messages, string|null $instructions = null)

Map the given Hypervel messages to Chat Completions messages format.

Parameters

array $messages
string|null $instructions

Return Value

array

protected void mapUserMessage(UserMessage|Message $message, array $chatMessages)

Map a user message to Chat Completions format.

Parameters

UserMessage|Message $message
array $chatMessages

Return Value

void

protected void mapAssistantMessage(AssistantMessage|Message $message, array $chatMessages)

Map an assistant message to Chat Completions format.

Parameters

AssistantMessage|Message $message
array $chatMessages

Return Value

void

protected void mapToolResultMessage(ToolResultMessage|Message $message, array $chatMessages)

Map a tool result message to Chat Completions format.

Parameters

ToolResultMessage|Message $message
array $chatMessages

Return Value

void

protected array serializeToolCallToChat(ToolCall $toolCall)

Serialize a tool call DTO to Chat Completions array format.

Parameters

ToolCall $toolCall

Return Value

array

protected string mapToolCallId(string $id)

Map a tool call or result ID to the provider's wire format.

Parameters

string $id

Return Value

string

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 OpenRouter response data.

Parameters

array $data

Return Value

void

Exceptions

AiException

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

Parse the OpenRouter response data into a single step response.

Parameters

array $data
Provider $provider
bool $structured

Return Value

StepResponse

protected string extractReasoning(array $message)

Extract the reasoning text from an assistant message.

Parameters

array $message

Return Value

string

in ParsesTextResponses at line 116
protected array extractReasoningDetails(array $message)

Extract the reasoning details to replay with the message's tool calls.

Parameters

array $message

Return Value

array

in ParsesTextResponses at line 126
protected Collection extractCitations(array $message)

Extract URL citations from the message annotations array.

Parameters

array $message

Return Value

Collection

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

Extract usage data from the response.

Parameters

array $data

Return Value

TextUsage

in ParsesTextResponses at line 165
protected FinishReason extractFinishReason(array $choice)

Extract and map the finish reason from the response.

Parameters

array $choice

Return Value

FinishReason

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 array mapTools(array $tools, Provider $provider)

Map the given tools to Chat Completions function definitions.

Parameters

array $tools
Provider $provider

Return Value

array

at line 78
protected array mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to an OpenRouter tool definition.

Parameters

ProviderTool $tool
Provider $provider

Return Value

array

protected array mapTool(Tool $tool)

Map a regular tool to a Chat Completions function definition.

Parameters

Tool $tool

Return Value

array

protected string|array mapToolChoice(ToolChoice $choice)

Map a tool choice to the Chat Completions tool_choice shape.

Parameters

ToolChoice $choice

Return Value

string|array

protected array parseIndexedEmbeddings(array $records, int $expectedCount, string $providerName)

Return embedding values in input order without accepting ambiguous indices.

Parameters

array $records
int $expectedCount
string $providerName

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

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 Chat Completions 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

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 Chat Completions 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

protected array|null streamOptions(Provider $provider)

Get the stream options sent with a streaming Chat Completions request.

Parameters

Provider $provider

Return Value

array|null

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 71
__construct(Dispatcher $events)

Create an OpenRouter gateway instance.

Parameters

Dispatcher $events

at line 90
protected array mapWebFetchTool(WebFetch $tool, Provider $provider)

Map a web fetch tool to an OpenRouter server tool definition.

Parameters

WebFetch $tool
Provider $provider

Return Value

array

at line 105
protected array mapWebSearchTool(WebSearch $tool, Provider $provider)

Map a web search tool to an OpenRouter server tool definition.

Parameters

WebSearch $tool
Provider $provider

Return Value

array

at line 120
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 images from the given prompt.

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 166
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

at line 200
protected string resolveVoice(string $model, string $voice)

Resolve the alias voice for the given model.

Parameters

string $model
string $voice

Return Value

string

at line 220
protected string audioResponseFormat(string $model)

Resolve the response_format the model accepts. Gemini TTS only accepts pcm.

Parameters

string $model

Return Value

string

at line 228
protected string audioResponseMimeType(string $format)

Map a response_format value to the HTTP audio MIME type.

Parameters

string $format

Return Value

string

at line 244
protected bool isGeminiTtsModel(string $model)

Determine whether the model uses Gemini text-to-speech.

Parameters

string $model

Return Value

bool

at line 256
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

Exceptions

LogicException

at line 309
protected string audioFormat(string $mimeType)

Map an audio MIME type to OpenRouter's input_audio.format value.

Parameters

string $mimeType

Return Value

string

at line 329
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 363
RerankingResponse rerank(RerankingProvider $provider, string $model, array $documents, string $query, int|null $limit = null, int $timeout = 30, array $providerOptions = [])

Rerank the given documents by relevance to a query.

Parameters

RerankingProvider $provider
string $model
array $documents
string $query
int|null $limit
int $timeout
array $providerOptions

Return Value

RerankingResponse