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.

Structured output instructs Grok to return a response that conforms to a JSON schema you define, rather than free-form prose. This makes it straightforward to extract typed data from unstructured text — parsing documents, populating data objects, or feeding model output directly into downstream PHP code without manual string parsing. The aisdk/xai provider handles the OpenAI-compatible response_format parameter automatically via ChatRequestBuilder.

How Structured Output Works

When you attach a schema to a Generate::text() call, ChatRequestBuilder sets the appropriate response_format in the request body and instructs the model to produce JSON that matches your schema. The parsed result is available on $result->structured as a PHP array. Structured output is declared as a supported capability for the following model families in resources/models.json:
  • grok-4*
  • grok-3*
  • grok-2*

Requesting Structured Output

Define your schema with Schema helpers from aisdk/core and pass it to the ->schema() builder method:
use AiSdk\Generate;
use AiSdk\Schema;
use AiSdk\XAI;

$result = Generate::text()
    ->model(XAI::model('grok-4'))
    ->prompt('Extract the key facts from: The Eiffel Tower is 330m tall and located in Paris.')
    ->schema(Schema::object([
        'name'     => Schema::string('Landmark name'),
        'height_m' => Schema::number('Height in metres'),
        'city'     => Schema::string('City name'),
    ]))
    ->run();

$data = $result->structured;
// $data => ['name' => 'Eiffel Tower', 'height_m' => 330, 'city' => 'Paris']
The model’s JSON response is decoded and returned as a PHP array on $result->structured. The raw text response remains available on $result->text if you need it.
The Schema builder API — including helpers for nested objects, arrays, enums, and required/optional fields — is provided by aisdk/core. Refer to the core SDK documentation for the full Schema reference. The xAI provider handles the OpenAI-compatible response_format parameter automatically; no additional provider configuration is required.

Supported Models

Model patternStructured output support
grok-4* (e.g. grok-4, grok-4.3)✅ Yes
grok-3* (e.g. grok-3, grok-3-mini)✅ Yes
grok-2* (e.g. grok-2-vision)✅ Yes

Build docs developers (and LLMs) love