OpenAiGateway
class OpenAiGateway implements Gateway, StepTextGateway
Traits
Methods
Build the request body for the OpenAI Responses API.
Build the request body for a stateful Responses API continuation.
Extract the latest tool results for a stateful continuation request.
Merge shared Responses API options onto the given request body.
Determine if OpenAI should receive full stateless conversation history.
Determine if the model supports encrypted reasoning content.
Build the text format options for structured output.
Create an HTTP client with the provider's request options.
Select a boot-registered connection without retaining dynamic provider names.
Process streamed response events and return the completed step.
Generate a lowercase UUID v7 for use as a stream event ID.
Generate text for a single Responses API step.
Stream text for a single Responses API step.
Build the request body for the current text generation step.
Derive a filename for a nameless document from its MIME type.
Map the given Hypervel attachments to OpenAI content parts.
Map the given Hypervel messages to OpenAI Responses API input format.
Map a user message to OpenAI format.
Map an assistant message to OpenAI format.
Remove file_search_call items, which the API resolves by id and so rejects when store is false.
Map a tool call to a function_call input item, keeping the item id only when OpenAI issued it and its reasoning survived.
Map a tool result message to OpenAI format.
Map the given tools to OpenAI function definitions.
Ensure hosted tool search is not used while response storage is disabled.
Map a provider tool to an OpenAI provider tool definition.
Map a code execution tool to an OpenAI code interpreter definition.
Map a file search tool to an OpenAI file search definition.
Map a web search tool to an OpenAI web search definition.
Decode a structured output payload, tolerating markdown code fences.
Join reasoning blocks, separating each block with a blank line.
Parse the OpenAI response data into a single step response.
Extract the text content from the output array.
Extract the reasoning text from the output array.
Extract citations from the output array.
Extract the ordered response output for full-history replay.
Extract the provider-hosted tool items from the output array.
Extract usage data from an image generation response.
Extract and map the finish reason from the response.
Map tool calls with their associated reasoning blocks.
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.
Return embedding values in input order without accepting ambiguous indices.
Parse an SSE stream body into decoded JSON data objects.
Read one line without waiting for a larger body buffer to fill.
Determine the appropriate filename for the audio file based on its MIME type.
Generate an image.
Send an image generation request.
Send an image edit request with attachments.
Generate audio from the given text.
Generate text from the given audio.
Generate embeddings for the given inputs.
Details
in
BuildsTextRequests at line 21
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 OpenAI Responses API.
in
BuildsTextRequests at line 41
protected array
buildContinuationBody(Provider $provider, string $model, string $continuationToken, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options = null)
Build the request body for a stateful Responses API continuation.
in
BuildsTextRequests at line 62
protected array
extractToolResultsInput(array $messages)
Extract the latest tool results for a stateful continuation request.
in
BuildsTextRequests at line 82
protected array
mergeSharedResponsesRequestOptions(array $body, array $tools, array|null $schema, TextGenerationOptions|null $options, Provider $provider)
Merge shared Responses API options onto the given request body.
in
BuildsTextRequests at line 142
protected string|array
mapToolChoice(ToolChoice $choice)
Map a tool choice to the OpenAI Responses tool_choice shape.
in
BuildsTextRequests at line 156
protected bool
isStateless(Provider $provider)
Determine if OpenAI should receive full stateless conversation history.
in
BuildsTextRequests at line 168
protected bool
isReasoningModel(string $model)
Determine if the model supports encrypted reasoning content.
in
BuildsTextRequests at line 180
protected array
buildSchemaFormat(array $schema, bool $strict)
Build the text format options for structured output.
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
CreatesOpenAiClient at line 18
protected PendingRequest
client(Provider $provider, int|null $timeout = null)
Get an HTTP client for the OpenAI API.
in
CreatesOpenAiClient at line 31
protected string
baseUrl(Provider $provider)
Get the base URL for the OpenAI-compatible API.
in
HandlesTextGeneration at line 36
protected Generator
processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody)
Process streamed response events and return the completed step.
in
HandlesTextGeneration at line 335
protected string
generateEventId()
Generate a lowercase UUID v7 for use as a stream event ID.
in
HandlesTextSteps at line 19
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 Responses API step.
in
HandlesTextSteps at line 48
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 Responses API step.
in
HandlesTextSteps at line 77
protected array
buildStepBody(TextProvider $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
ResolvesDocumentFilenames at line 12
protected string
fallbackFilename(string|null $mimeType)
Derive a filename for a nameless document from its MIME type.
in
MapsAttachments at line 34
protected array
mapAttachments(Collection $attachments, Provider $provider)
Map the given Hypervel attachments to OpenAI content parts.
in
MapsAttachments at line 115
protected bool
isImage(UploadedFile $attachment)
Determine if the given uploaded file is an image.
in
MapsMessages at line 21
protected array
mapMessagesToInput(array $messages, string|null $instructions, Provider $provider)
Map the given Hypervel messages to OpenAI Responses API input format.
in
MapsMessages at line 48
protected void
mapUserMessage(UserMessage|Message $message, array $input, Provider $provider)
Map a user message to OpenAI format.
in
MapsMessages at line 67
protected void
mapAssistantMessage(AssistantMessage|Message $message, array $input, Provider $provider)
Map an assistant message to OpenAI format.
in
MapsMessages at line 126
protected array
withoutStoredOnlyItems(array $blocks)
Remove file_search_call items, which the API resolves by id and so rejects when store is false.
in
MapsMessages at line 139
protected array
functionCallItem(ToolCall $toolCall)
Map a tool call to a function_call input item, keeping the item id only when OpenAI issued it and its reasoning survived.
in
MapsMessages at line 154
protected void
mapToolResultMessage(ToolResultMessage|Message $message, array $input)
Map a tool result message to OpenAI format.
in
MapsTools at line 30
protected array
mapTools(array $tools, Provider $provider, bool $stateless = false)
Map the given tools to OpenAI function definitions.
in
MapsTools at line 63
protected void
guardStatelessToolSearch(Provider $provider, bool $stateless)
Ensure hosted tool search is not used while response storage is disabled.
in
MapsTools at line 75
protected array
mapTool(Tool $tool, bool $defer = false)
Map a regular tool to an OpenAI function definition.
in
MapsTools at line 108
protected array
mapProviderTool(ProviderTool $tool, Provider $provider)
Map a provider tool to an OpenAI provider tool definition.
in
MapsTools at line 121
protected array
mapCodeExecutionTool(CodeExecution $tool, Provider $provider)
Map a code execution tool to an OpenAI code interpreter definition.
in
MapsTools at line 136
protected array
mapFileSearchTool(FileSearch $tool, Provider $provider)
Map a file search tool to an OpenAI file search definition.
in
MapsTools at line 151
protected array
mapWebSearchTool(WebSearch $tool, Provider $provider)
Map a web search tool to an OpenAI web 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 31
protected void
validateTextResponse(array $data)
Validate the OpenAI response data.
in
ParsesTextResponses at line 55
protected StepResponse
parseTextResponse(array $data, Provider $provider, bool $structured)
Parse the OpenAI response data into a single step response.
in
ParsesTextResponses at line 80
protected string
extractText(array $output)
Extract the text content from the output array.
in
ParsesTextResponses at line 102
protected string
extractReasoning(array $output)
Extract the reasoning text from the output array.
in
ParsesTextResponses at line 117
protected Collection
extractCitations(array $output)
Extract citations from the output array.
in
ParsesTextResponses at line 150
protected array
extractReplayBlocks(array $output)
Extract the ordered response output for full-history replay.
in
ParsesTextResponses at line 160
protected array
extractProviderToolCalls(array $output)
Extract the provider-hosted tool items from the output array.
in
ParsesTextResponses at line 173
protected TextUsage
extractUsage(array $data)
Extract usage data from the response.
in
ParsesTextResponses at line 189
protected ImageUsage
extractImageUsage(array $data)
Extract usage data from an image generation response.
in
ParsesTextResponses at line 205
protected FinishReason
extractFinishReason(array $data)
Extract and map the finish reason from the response.
in
ParsesTextResponses at line 237
protected array
mapToolCallsWithReasoning(array $output)
Map tool calls with their associated reasoning blocks.
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
ParsesIndexedEmbeddings at line 17
protected array
parseIndexedEmbeddings(array $records, int $expectedCount, string $providerName)
Return embedding values in input order without accepting ambiguous indices.
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
ResolvesAudioFilenames at line 15
protected string
audioFilename(TranscribableAudio $audio)
Determine the appropriate filename for the audio file based on its MIME type.
at line 63
__construct(Dispatcher $events)
Create an OpenAI gateway instance.
at line 75
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 111
protected Response
sendImageGenerationRequest(ImageProvider $provider, string $model, string $prompt, string|null $size, string|null $quality, int|null $timeout, array $providerOptions = [])
Send an image generation request.
at line 137
protected Response
sendImageEditRequest(ImageProvider $provider, string $model, string $prompt, array $attachments, string|null $size, string|null $quality, int|null $timeout, array $providerOptions = [])
Send an image edit request with attachments.
at line 178
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 220
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 271
EmbeddingsResponse
generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])
Generate embeddings for the given inputs.