class XaiGateway implements Gateway, StepTextGateway

Traits

Methods

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 xAI Responses API.

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
buildContinuationBody(string $previousResponseId, string $model, array $messages, array $tools, Provider $provider, array|null $schema, TextGenerationOptions|null $options = null)

Build a lightweight continuation body using previous_response_id.

array
mergeSharedResponsesRequestOptions(array $body, array $tools, array|null $schema, TextGenerationOptions|null $options, Provider $provider)

Apply options shared by full requests and previous_response_id continuations.

string|array
mapToolChoice(ToolChoice $choice)

Map a tool choice to the xAI Responses tool_choice shape.

array
extractToolResultsInput(array $messages)

Extract tool result items from the trailing ToolResultMessage for a continuation request.

array
buildSchemaFormat(array $schema, bool $strict)

Build the text 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 xAI API.

string
baseUrl(Provider $provider)

Get the base URL for the xAI API.

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

Process an xAI streaming response for a single turn and yield Hypervel stream events.

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 xAI content parts.

bool
isImage(UploadedFile $attachment)

Determine if the given uploaded file is an image.

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

Map the given Hypervel messages to xAI Responses API input format.

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

Map a user message to xAI format.

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

Map an assistant message to xAI format.

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

Map a tool result message to xAI format.

array
mapTools(array $tools, Provider $provider)

Map the given tools to xAI function definitions.

array
mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to an xAI provider tool definition.

array
mapCodeExecutionTool(CodeExecution $tool, Provider $provider)

Map a code execution tool to an xAI code interpreter definition.

array
mapFileSearchTool(FileSearch $tool, Provider $provider)

Map a file search tool to an xAI file search definition.

array
mapWebSearchTool(WebSearch $tool, Provider $provider)

Map a web search tool to an xAI web search definition.

array
mapTool(Tool $tool)

Map a regular tool to an xAI function 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 xAI response data.

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

Parse a single xAI response into a StepResponse.

string
extractText(array $output)

Extract the text content from the output array.

extractCitations(array $output)

Extract citations from the output array.

array
extractProviderToolCalls(array $output)

Extract the provider-hosted tool items from the output array.

extractUsage(array $data)

Extract usage data from the response.

FinishReason
extractFinishReason(array $data)

Extract and map the finish reason from the xAI response.

string
extractReasoning(array $output)

Extract the reasoning text from the output array.

array
mapToolCallsWithReasoning(array $output)

Map tool calls with their associated reasoning blocks.

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.

__construct(Dispatcher $events)

Create a new xAI 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 a single text 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 a single text step.

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

Reject image generation through the text gateway.

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

Reject unsupported audio generation.

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

Reject unsupported transcription generation.

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

Reject unsupported embedding generation.

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 xAI Responses 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 40
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 60
protected array buildContinuationBody(string $previousResponseId, string $model, array $messages, array $tools, Provider $provider, array|null $schema, TextGenerationOptions|null $options = null)

Build a lightweight continuation body using previous_response_id.

Only sends tool results as input instead of replaying the full conversation.

Parameters

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

Return Value

array

in BuildsTextRequests at line 81
protected array mergeSharedResponsesRequestOptions(array $body, array $tools, array|null $schema, TextGenerationOptions|null $options, Provider $provider)

Apply options shared by full requests and previous_response_id continuations.

Parameters

array $body
array $tools
array|null $schema
TextGenerationOptions|null $options
Provider $provider

Return Value

array

in BuildsTextRequests at line 122
protected string|array mapToolChoice(ToolChoice $choice)

Map a tool choice to the xAI Responses tool_choice shape.

Parameters

ToolChoice $choice

Return Value

string|array

in BuildsTextRequests at line 136
protected array extractToolResultsInput(array $messages)

Extract tool result items from the trailing ToolResultMessage for a continuation request.

Parameters

array $messages

Return Value

array

in BuildsTextRequests at line 158
protected array buildSchemaFormat(array $schema, bool $strict)

Build the text 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

in CreatesXaiClient at line 18
protected PendingRequest client(Provider $provider, int|null $timeout = null)

Get an HTTP client for the xAI API.

Parameters

Provider $provider
int|null $timeout

Return Value

PendingRequest

in CreatesXaiClient at line 31
protected string baseUrl(Provider $provider)

Get the base URL for the xAI API.

Parameters

Provider $provider

Return Value

string

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

Process an xAI streaming response for a single turn and yield Hypervel stream events.

Parameters

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

Return Value

Generator

in HandlesTextStreaming at line 321
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 30
protected array mapAttachments(Collection $attachments)

Map the given Hypervel attachments to xAI content parts.

Parameters

Collection $attachments

Return Value

array

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

Determine if the given uploaded file is an image.

Parameters

UploadedFile $attachment

Return Value

bool

in MapsMessages at line 19
protected array mapMessagesToInput(array $messages, string|null $instructions = null)

Map the given Hypervel messages to xAI Responses API input format.

Parameters

array $messages
string|null $instructions

Return Value

array

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

Map a user message to xAI format.

Parameters

UserMessage|Message $message
array $input

Return Value

void

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

Map an assistant message to xAI format.

Parameters

AssistantMessage|Message $message
array $input

Return Value

void

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

Map a tool result message to xAI format.

Parameters

ToolResultMessage|Message $message
array $input

Return Value

void

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

Map the given tools to xAI function definitions.

Parameters

array $tools
Provider $provider

Return Value

array

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

Map a provider tool to an xAI provider tool definition.

Parameters

ProviderTool $tool
Provider $provider

Return Value

array

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

Map a code execution tool to an xAI code interpreter definition.

Parameters

CodeExecution $tool
Provider $provider

Return Value

array

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

Map a file search tool to an xAI file search definition.

Parameters

FileSearch $tool
Provider $provider

Return Value

array

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

Map a web search tool to an xAI web search definition.

Parameters

WebSearch $tool
Provider $provider

Return Value

array

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

Map a regular tool to an xAI function definition.

Parameters

Tool $tool

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

Parameters

array $data

Return Value

void

Exceptions

AiException

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

Parse a single xAI response into a StepResponse.

Parameters

array $data
Provider $provider
bool $structured

Return Value

StepResponse

protected string extractText(array $output)

Extract the text content from the output array.

Parameters

array $output

Return Value

string

in ParsesTextResponses at line 107
protected Collection extractCitations(array $output)

Extract citations from the output array.

Parameters

array $output

Return Value

Collection

in ParsesTextResponses at line 138
protected array extractProviderToolCalls(array $output)

Extract the provider-hosted tool items from the output array.

Parameters

array $output

Return Value

array

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

Extract usage data from the response.

Parameters

array $data

Return Value

TextUsage

in ParsesTextResponses at line 167
protected FinishReason extractFinishReason(array $data)

Extract and map the finish reason from the xAI response.

Parameters

array $data

Return Value

FinishReason

in ParsesTextResponses at line 196
protected string extractReasoning(array $output)

Extract the reasoning text from the output array.

Parameters

array $output

Return Value

string

in ParsesTextResponses at line 213
protected array mapToolCallsWithReasoning(array $output)

Map tool calls with their associated reasoning blocks.

Parameters

array $output

Return Value

array

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

at line 45
__construct(Dispatcher $events)

Create a new xAI gateway.

Parameters

Dispatcher $events

at line 52
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 a single text 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 81
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 a single text 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 118
ImageResponse generateImage(ImageProvider $provider, string $model, string $prompt, array $attachments = [], string|null $size = null, string|null $quality = null, int|null $timeout = null, array $providerOptions = [])

Reject image generation through the text gateway.

Parameters

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

Return Value

ImageResponse

Exceptions

LogicException

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

Reject unsupported audio generation.

Parameters

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

Return Value

AudioResponse

Exceptions

LogicException

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

Reject unsupported transcription generation.

Parameters

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

Return Value

TranscriptionResponse

Exceptions

LogicException

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

Reject unsupported embedding generation.

Parameters

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

Return Value

EmbeddingsResponse

Exceptions

LogicException