Skip to main content

Documentation 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.

This quickstart gets you from zero to a working Grok API call in under five minutes. You will install the package, configure your API key, generate a text completion with grok-4.3, and create an image — all using the same fluent builder API.
1

Install the package

Add aisdk/xai to your project with Composer. This also installs aisdk/core and aisdk/openai-compatible automatically as required dependencies:
composer require aisdk/xai
2

Set your API key

Export your xAI API key as an environment variable. The provider reads XAI_API_KEY automatically, so you will not need to hard-code the key in your source files:
export XAI_API_KEY=xai-...
3

Generate text

Use Generate::text() with XAI::model() to send a prompt to Grok and print the response. The ->instructions() call sets a system-level message, and ->run() executes the request synchronously:
use AiSdk\Generate;
use AiSdk\XAI;

$result = Generate::text()
    ->model(XAI::model('grok-4'))
    ->instructions('Write short, clear answers.')
    ->prompt('Explain closures in PHP.')
    ->run();

echo $result->text;
4

Generate an image

Use Generate::image() with XAI::image() to create an image from a text prompt. The ->aspectRatio() method controls the output dimensions, and ->run() returns a result object whose output property can be saved to disk:
use AiSdk\Generate;
use AiSdk\XAI;

$result = Generate::image()
    ->model(XAI::image('grok-imagine-image-quality'))
    ->prompt('A clean app icon for a PHP AI SDK')
    ->aspectRatio('1:1')
    ->run();

$result->output->save(__DIR__.'/icon.png');

What’s Next

Now that your first Grok calls are working, explore these guides to go further:

Text Generation

Learn how to use system instructions, control temperature and token limits, and work with the full text result object.

Streaming

Stream tokens back to the client as they are generated, with support for partial results and cancellation.

Image Generation

Control image count, aspect ratio, resolution, and provider-specific options when generating images with Grok.

Reasoning

Use Reasoning::effort() to let Grok models think before answering, improving accuracy on complex or multi-step tasks.

Build docs developers (and LLMs) love