TheDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/phpaisdk/xai/llms.txt
Use this file to discover all available pages before exploring further.
aisdk/xai package is the official xAI provider for the PHP AI SDK. It wraps xAI’s OpenAI-compatible chat completions API so you can generate text from any Grok model using the same fluent builder interface you use with every other provider in the SDK.
Basic usage
Install the package, configure your API key, then callGenerate::text() to build a request and ->run() to execute it:
XAI::create() reads XAI_API_KEY and XAI_BASE_URL from your environment when no explicit values are passed, so in most applications you only need to call it once at bootstrap time — or skip it entirely if you export those environment variables.
Choosing a model
XAI::model(string $modelId) returns a TextModelInterface instance backed by the XAITextModel class. Pass any concrete model ID that matches one of the wildcard patterns registered in the model catalog:
| Pattern | Generation | Notable capabilities |
|---|---|---|
grok-4* | Grok 4 | text generation, streaming, tool calling, structured output, reasoning, image input |
grok-3* | Grok 3 | text generation, streaming, tool calling, structured output, reasoning, image input |
grok-2* | Grok 2 | text generation, streaming, tool calling, structured output, image input |
grok-4.3, grok-3-mini, or grok-2-vision are all valid. If you pass an ID that does not match any catalog entry, the SDK falls back to assuming basic text generation support so newly released models work without a catalog update.
The response object
->run() returns a TextModelResponse object with the following fields:
| Field | Type | Description |
|---|---|---|
$result->text | string | The generated text returned by the model. |
$result->usage->inputTokens | int | Number of tokens in the prompt sent to the API. |
$result->usage->outputTokens | int | Number of tokens in the completion returned by the API. |
$result->providerMetadata['xai']['id'] | string | The completion ID assigned by the xAI API (e.g. chatcmpl_xai). |
$result->providerMetadata['xai']['model'] | string | The model identifier echoed back by the API response. |
Setting a system prompt
Pass a system prompt with->instructions(). The SDK maps this to the system role message in the chat completions request:
Passing the prompt directly
When you only need a user prompt and no system instructions, you can pass it straight toGenerate::text() as a shorthand:
->prompt() separately and keeps simple one-shot requests compact.