XaiGateway
class XaiGateway implements Gateway, StepTextGateway
Traits
Methods
Build the request body for the xAI Responses API.
Build the request body for the current text generation step.
Build a lightweight continuation body using previous_response_id.
Apply options shared by full requests and previous_response_id continuations.
Extract tool result items from the trailing ToolResultMessage for a continuation request.
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 an xAI streaming response for a single turn and yield Hypervel stream events.
Generate a lowercase UUID v7 for use as a stream event ID.
Derive a filename for a nameless document from its MIME type.
Map the given Hypervel messages to xAI Responses API input format.
Map an assistant message to xAI format.
Map a tool result message to xAI format.
Map a provider tool to an xAI provider tool definition.
Map a code execution tool to an xAI code interpreter definition.
Map a file search tool to an xAI file search definition.
Map a web search tool to an xAI web search definition.
Decode a structured output payload, tolerating markdown code fences.
Join reasoning blocks, separating each block with a blank line.
Parse a single xAI response into a StepResponse.
Extract the text content from the output array.
Extract citations from the output array.
Extract the provider-hosted tool items from the output array.
Extract and map the finish reason from the xAI response.
Extract the reasoning text from the output array.
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.
Parse an SSE stream body into decoded JSON data objects.
Read one line without waiting for a larger body buffer to fill.
Generate a single text step.
Stream a single text step.
Reject image generation through the text gateway.
Reject unsupported audio generation.
Reject unsupported transcription generation.
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.
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.
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.
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.
in
BuildsTextRequests at line 122
protected string|array
mapToolChoice(ToolChoice $choice)
Map a tool choice to the xAI Responses tool_choice shape.
in
BuildsTextRequests at line 136
protected array
extractToolResultsInput(array $messages)
Extract tool result items from the trailing ToolResultMessage for a continuation request.
in
BuildsTextRequests at line 158
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
CreatesXaiClient at line 18
protected PendingRequest
client(Provider $provider, int|null $timeout = null)
Get an HTTP client for the xAI API.
in
CreatesXaiClient at line 31
protected string
baseUrl(Provider $provider)
Get the base URL for the xAI API.
in
HandlesTextStreaming at line 35
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.
in
HandlesTextStreaming at line 321
protected string
generateEventId()
Generate a lowercase UUID v7 for use as a stream event ID.
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 30
protected array
mapAttachments(Collection $attachments)
Map the given Hypervel attachments to xAI content parts.
in
MapsAttachments at line 102
protected bool
isImage(UploadedFile $attachment)
Determine if the given uploaded file is an image.
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.
in
MapsMessages at line 46
protected void
mapUserMessage(UserMessage|Message $message, array $input)
Map a user message to xAI format.
in
MapsMessages at line 65
protected void
mapAssistantMessage(AssistantMessage|Message $message, array $input)
Map an assistant message to xAI format.
in
MapsMessages at line 120
protected void
mapToolResultMessage(ToolResultMessage|Message $message, array $input)
Map a tool result message to xAI format.
in
MapsTools at line 27
protected array
mapTools(array $tools, Provider $provider)
Map the given tools to xAI function definitions.
in
MapsTools at line 45
protected array
mapProviderTool(ProviderTool $tool, Provider $provider)
Map a provider tool to an xAI provider tool definition.
in
MapsTools at line 58
protected array
mapCodeExecutionTool(CodeExecution $tool, Provider $provider)
Map a code execution tool to an xAI code interpreter definition.
in
MapsTools at line 73
protected array
mapFileSearchTool(FileSearch $tool, Provider $provider)
Map a file search tool to an xAI file search definition.
in
MapsTools at line 88
protected array
mapWebSearchTool(WebSearch $tool, Provider $provider)
Map a web search tool to an xAI web search definition.
in
MapsTools at line 103
protected array
mapTool(Tool $tool)
Map a regular tool to an xAI function 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 30
protected void
validateTextResponse(array $data)
Validate the xAI response data.
in
ParsesTextResponses at line 54
protected StepResponse
parseTextResponse(array $data, Provider $provider, bool $structured)
Parse a single xAI response into a StepResponse.
in
ParsesTextResponses at line 85
protected string
extractText(array $output)
Extract the text content from the output array.
in
ParsesTextResponses at line 107
protected Collection
extractCitations(array $output)
Extract citations from the output array.
in
ParsesTextResponses at line 138
protected array
extractProviderToolCalls(array $output)
Extract the provider-hosted tool items from the output array.
in
ParsesTextResponses at line 151
protected TextUsage
extractUsage(array $data)
Extract usage data from the response.
in
ParsesTextResponses at line 167
protected FinishReason
extractFinishReason(array $data)
Extract and map the finish reason from the xAI response.
in
ParsesTextResponses at line 196
protected string
extractReasoning(array $output)
Extract the reasoning text from the output array.
in
ParsesTextResponses at line 213
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
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.
at line 45
__construct(Dispatcher $events)
Create a new xAI gateway.
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.
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.
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.
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.
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.
at line 173
EmbeddingsResponse
generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])
Reject unsupported embedding generation.