Model capabilities

Structured outputs

Structured Outputs lets the API return responses in a specific format, for example, a JSON object matching a schema you define instead of free-form text. This feature is especially useful for tasks like document parsing, entity extraction, and report generation.

When using supported schema features, the response is guaranteed to match your schema.

There are two ways to request structured outputs from the model.

The primary and most flexible method is the text.format parameter of the Responses API. Set it to {"type": "json_schema", "name": "...", "schema": {...}} to define exactly what structured output the model should return. It also accepts {"type": "json_object"} for any well-formed JSON when you don't need a specific structure, and {"type": "text"} (the default) for free-form text.

The second way is through tool calling. When you define tools, SpaceXSI models will always generate tool call arguments that strictly conform to the tool’s input JSON Schema (the strict flag is implicitly always true).

Tool schemas follow the same JSON Schema support rules described on this page. See the Function Calling documentation for full details.

You can define schemas using libraries like Pydantic or Zod.

JSON schema support

We support a practical subset of JSON Schema. Schemas authored against Draft 2020-12 work best; Draft-07 schemas are also accepted.

Keywords

Keywords in the last column are accepted, but the output is not guaranteed to satisfy them.

EnforcedAccepted but not enforced
Any valuetype, enum, const
CombininganyOf, oneOf, allOfnot, if / then / else
References$ref / $defs, including recursive references$ref to an external URL
StringsminLength, maxLength, pattern, format (listed values)Other format values
Numbersminimum, maximum, exclusiveMinimum, exclusiveMaximummultipleOf
Objectsproperties, required, additionalProperties, patternProperties, propertyNames, unevaluatedProperties, minProperties, maxPropertiesdependentRequired, dependentSchemas
Arraysitems, prefixItems, unevaluatedItems, minItems, maxItemsuniqueItems, contains, minContains, maxContains

additionalProperties defaults to false for objects that declare properties, and a prefixItems tuple takes no extra items unless items allows them. For a free-form object, use {"type": "object"}.

oneOf may accept a value that matches more than one of its alternatives.

String formats

The format keyword is enforced for these values:

date · time · date-time · duration · email · hostname · ipv4 · ipv6 · uuid · uri · uri-reference · uri-template · json-pointer · relative-json-pointer

Formats check syntax only: 2024-02-30 passes as a date.

Rejected schemas

The following will return a 400 error:

  • enum, anyOf, oneOf, or allOf with zero entries
  • Properties with a schema of false
  • items as an array (use prefixItems)
  • A recursive $ref through definitions in text.format (use $defs)
  • A pattern that is not a valid regular expression, or that uses backreferences, Unicode property escapes, or word boundaries (see Regex support)
  • Tool parameters whose root is nullable or not an object

Regex support (pattern)

The pattern keyword supports a practical subset of ECMAScript Regular Expressions (ECMA-262). Write each pattern to match the entire string, with ^, $, and .* for any part you leave open: ^https://.*$, not ^https://.

Supported:

  • Literals and character classes ([abc], [a-z], [^abc]) and .
  • Alternation |, grouping (...), non-capturing groups (?:...), and named groups (?<name>...)
  • Quantifiers *, +, ?, repetition ranges {n}, {n,}, {n,m}, and their lazy forms (*?, +?, ??)
  • Anchors ^ and $
  • Lookahead (?=...) and negative lookahead (?!...)
  • Case-insensitive matching with (?i) or (?i:...)
  • Shorthand classes \d, \w, \s (and their negations \D, \W, \S)
  • Common escapes: \n, \t, \r, \f, \xHH, \uHHHH, \u{HHHHHH}

Rejected with a 400 error:

  • Backreferences (\1, \k<name>, etc.)
  • Unicode property escapes (\p{L}, \P{Letter})
  • Word boundaries (\b, \B)

Accepted, but the whole pattern is not enforced:

  • Lookbehind ((?<=...), (?<!...))
  • Inline modifiers other than i ((?m), (?s), etc.)
  • Python-style named groups ((?P<name>...))
  • Some complex patterns, such as ^.+@.{1,30}$

Example: Invoice parsing

A common use case for Structured Outputs is parsing raw documents. For example, invoices contain structured data like vendor details, amounts, and dates, but extracting this data from raw text can be error-prone. Structured Outputs ensures the extracted data matches a predefined schema.

Let's say you want to extract the following data from an invoice:

  • Vendor name and address
  • Invoice number and date
  • Line items (description, quantity, price)
  • Total amount and currency

We'll use structured outputs to have Grok generate a strongly typed JSON for this.


Step 1: Defining the schema

You can use Pydantic or Zod to define your schema.

from datetime import date
from enum import Enum

from pydantic import BaseModel, Field

class Currency(str, Enum):
    USD = "USD"
    EUR = "EUR"
    GBP = "GBP"

class LineItem(BaseModel):
    description: str = Field(description="Description of the item or service")
    quantity: int = Field(description="Number of units", ge=1)
    unit_price: float = Field(description="Price per unit", ge=0)

class Address(BaseModel):
    street: str = Field(description="Street address")
    city: str = Field(description="City")
    postal_code: str = Field(description="Postal/ZIP code")
    country: str = Field(description="Country")

class Invoice(BaseModel):
    vendor_name: str = Field(description="Name of the vendor")
    vendor_address: Address = Field(description="Vendor's address")
    invoice_number: str = Field(description="Unique invoice identifier")
    invoice_date: date = Field(description="Date the invoice was issued")
    line_items: list[LineItem] = Field(description="List of purchased items/services")
    total_amount: float = Field(description="Total amount due", ge=0)
    currency: Currency = Field(description="Currency of the invoice")

Step 2: Prepare the prompts

System prompt

The system prompt instructs the model to extract invoice data from text. Since the schema is defined separately, the prompt can focus on the task without explicitly specifying the required fields in the output JSON.

Text

Given a raw invoice, carefully analyze the text and extract the relevant invoice data into JSON format.

Example invoice text

Text

Vendor: Acme Corp, 123 Main St, Springfield, IL 62704
Invoice Number: INV-2025-001
Date: 2025-02-10
Items:
- Widget A, 5 units, $10.00 each
- Widget B, 2 units, $15.00 each
Total: $80.00 USD

Step 3: The final code

Use the structured outputs feature of the SDK to parse the invoice.

import { xai } from '@ai-sdk/xai';
import { generateText, Output } from 'ai';
import { z } from 'zod';

const CurrencyEnum = z.enum(['USD', 'EUR', 'GBP']);

const LineItemSchema = z.object({
  description: z.string().describe('Description of the item or service'),
  quantity: z.number().int().min(1).describe('Number of units'),
  unit_price: z.number().min(0).describe('Price per unit'),
});

const AddressSchema = z.object({
  street: z.string().describe('Street address'),
  city: z.string().describe('City'),
  postal_code: z.string().describe('Postal/ZIP code'),
  country: z.string().describe('Country'),
});

const InvoiceSchema = z.object({
  vendor_name: z.string().describe('Name of the vendor'),
  vendor_address: AddressSchema.describe("Vendor's address"),
  invoice_number: z.string().describe('Unique invoice identifier'),
  invoice_date: z.string().date().describe('Date the invoice was issued'),
  line_items: z
    .array(LineItemSchema)
    .describe('List of purchased items/services'),
  total_amount: z.number().min(0).describe('Total amount due'),
  currency: CurrencyEnum.describe('Currency of the invoice'),
});

const result = await generateText({
  model: xai.responses('grok-4.7'),
  output: Output.object({ schema: InvoiceSchema }),
  system:
    'Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format.',
  prompt: `
  Vendor: Acme Corp, 123 Main St, Springfield, IL 62704
  Invoice Number: INV-2025-001
  Date: 2025-02-10
  Items:

  - Widget A, 5 units, $10.00 each
  - Widget B, 2 units, $15.00 each
    Total: $80.00 USD
    `,
});

console.log(result.output);

Step 4: Type-safe output

When using supported schema features, the output will be type-safe and respect the input schema.

JSON

{
  "vendor_name": "Acme Corp",
  "vendor_address": {
    "street": "123 Main St",
    "city": "Springfield",
    "postal_code": "62704",
    "country": "IL"
  },
  "invoice_number": "INV-2025-001",
  "invoice_date": "2025-02-10",
  "line_items": [
    { "description": "Widget A", "quantity": 5, "unit_price": 10.0 },
    { "description": "Widget B", "quantity": 2, "unit_price": 15.0 }
  ],
  "total_amount": 80.0,
  "currency": "USD"
}

Structured outputs with tools

You can combine structured outputs with tool calling to get type-safe responses from tool-augmented queries. This works with both:

  • Agentic tool calling: Server-side tools like web search, X search, and code execution that the model orchestrates autonomously.
  • Function calling: User-supplied tools where you define custom functions and handle tool execution yourself.

This combination enables workflows where the model can use tools to gather information and return results in a predictable, strongly typed format.

Example: Agentic tools with structured output

This example uses web search to find the latest research on a topic and extracts structured data into a schema:

from pydantic import BaseModel, Field

class ProofInfo(BaseModel):
    name: str = Field(description="Name of the proof or paper")
    authors: str = Field(description="Authors of the proof")
    year: str = Field(description="Year published")
    summary: str = Field(description="Brief summary of the approach")
import os
from openai import OpenAI
from pydantic import BaseModel, Field

# ProofInfo schema defined above

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

response = client.responses.parse(
    model="grok-4.7",
    input="Find the latest machine-checked proof of the four color theorem.",
    tools=[
        {"type": "web_search"}
    ],
    text_format=ProofInfo,
)

proof = response.output_parsed
print(f"Name: {proof.name}")
print(f"Authors: {proof.authors}")
print(f"Year: {proof.year}")
print(f"Summary: {proof.summary}")

Example: Client-side tools with structured output

This example uses a client-side function tool to compute Collatz sequence steps and returns the result in a structured format:

from pydantic import BaseModel, Field

class CollatzResult(BaseModel):
    starting_number: int = Field(description="The input number")
    steps: int = Field(description="Number of steps to reach 1")
import os
import json
from openai import OpenAI
from pydantic import BaseModel, Field

# CollatzResult schema defined above

def collatz_steps(n: int) -> int:
    """Returns the number of steps for n to reach 1 in the Collatz sequence."""
    steps = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        steps += 1
    return steps

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

tools = [
    {
        "type": "function",
        "name": "collatz_steps",
        "description": "Compute the number of steps for a number to reach 1 in the Collatz sequence",
        "parameters": {
            "type": "object",
            "properties": {
                "n": {"type": "integer", "description": "The starting number"},
            },
            "required": ["n"],
        },
    }
]

response = client.responses.parse(
    model="grok-4.7",
    input=[{"role": "user", "content": "Use the collatz_steps tool to find how many steps it takes for 20250709 to reach 1."}],
    tools=tools,
    text_format=CollatzResult,
)

# Handle tool calls until the model returns the structured result
while True:
    outputs = []
    for item in response.output:
        if item.type == "function_call":
            args = json.loads(item.arguments)
            outputs.append({
                "type": "function_call_output",
                "call_id": item.call_id,
                "output": str(collatz_steps(args["n"])),
            })

    if not outputs:
        break

    response = client.responses.parse(
        model="grok-4.7",
        input=outputs,
        tools=tools,
        text_format=CollatzResult,
        previous_response_id=response.id,
    )

result = response.output_parsed
print(f"Starting number: {result.starting_number}")
print(f"Steps to reach 1: {result.steps}")

Alternative: Using response_format with sample() or stream()

When using the xAI Python SDK, there's an alternative way to retrieve structured outputs. Instead of using the parse() method, you can pass your Pydantic model directly to the response_format parameter when creating a chat, and then use sample() or stream() to get the response.

How it works

When you pass a Pydantic model to response_format, the SDK automatically:

  1. Converts your Pydantic model to a JSON schema
  2. Constrains the model's output to conform to that schema
  3. Returns the response as a JSON string, that is conforming to the Pydantic model, in response.content

You then manually parse the JSON string into your Pydantic model instance.

Key differences

ApproachMethodReturnsParsing
Using parse()chat.parse(Model)Tuple of (Response, Model)Automatic - SDK parses for you
Using response_formatchat.sample() or chat.stream()Response with JSON stringManual - You parse response.content

When to use each approach

  • Use parse() when you want the simplest, most convenient experience with automatic parsing
  • Use response_format + sample() or stream() when you:
    • Want more control over the parsing process
    • Need to handle the raw JSON string before parsing
    • Want to use streaming with structured outputs
    • Are integrating with existing code that expects to work with sample() or stream()

Example using response_format

Python

import os
from datetime import date
from enum import Enum

from pydantic import BaseModel, Field
from xai_sdk import Client
from xai_sdk.chat import system, user

# Pydantic schemas
class Currency(str, Enum):
    USD = "USD"
    EUR = "EUR"
    GBP = "GBP"


class LineItem(BaseModel):
    description: str = Field(description="Description of the item or service")
    quantity: int = Field(description="Number of units", ge=1)
    unit_price: float = Field(description="Price per unit", ge=0)


class Address(BaseModel):
    street: str = Field(description="Street address")
    city: str = Field(description="City")
    postal_code: str = Field(description="Postal/ZIP code")
    country: str = Field(description="Country")


class Invoice(BaseModel):
    vendor_name: str = Field(description="Name of the vendor")
    vendor_address: Address = Field(description="Vendor's address")
    invoice_number: str = Field(description="Unique invoice identifier")
    invoice_date: date = Field(description="Date the invoice was issued")
    line_items: list[LineItem] = Field(description="List of purchased items/services")
    total_amount: float = Field(description="Total amount due", ge=0)
    currency: Currency = Field(description="Currency of the invoice")


client = Client(api_key=os.getenv("XAI_API_KEY"))

# Pass the Pydantic model to response_format instead of using parse()
chat = client.chat.create(
    model="grok-4.7",
    response_format=Invoice,  # Pass the Pydantic model here
)

chat.append(system("Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format."))
chat.append(
    user("""
Vendor: Acme Corp, 123 Main St, Springfield, IL 62704
Invoice Number: INV-2025-001
Date: 2025-02-10
Items: - Widget A, 5 units, $10.00 each - Widget B, 2 units, $15.00 each
Total: $80.00 USD
""")
)

# Use sample() instead of parse() - returns response object
response = chat.sample()

# The response.content is a valid JSON string conforming to your schema
print(response.content)
# Output: {"vendor_name": "Acme Corp", "vendor_address": {...}, ...}

# Manually parse the JSON string into your Pydantic model
invoice = Invoice.model_validate_json(response.content)
assert isinstance(invoice, Invoice)

# Access fields of the parsed invoice object
print(invoice.vendor_name)
print(invoice.invoice_number)
print(invoice.total_amount)

Streaming with structured outputs

You can also use stream() with response_format to get streaming structured output. The chunks will progressively build up the JSON string:

Python

import os

from pydantic import BaseModel, Field
from xai_sdk import Client
from xai_sdk.chat import system, user


class Summary(BaseModel):
    title: str = Field(description="A brief title")
    key_points: list[str] = Field(description="Main points from the text")
    sentiment: str = Field(description="Overall sentiment: positive, negative, or neutral")


client = Client(api_key=os.getenv("XAI_API_KEY"))

chat = client.chat.create(
    model="grok-4.7",
    response_format=Summary,  # Pass the Pydantic model here
)

chat.append(system("Analyze the following text and provide a structured summary."))
chat.append(user("The new product launch exceeded expectations with record sales..."))


# Stream the response - chunks contain partial JSON
for response, chunk in chat.stream():
    print(chunk.content, end="", flush=True)


# Parse the complete JSON string into your model
summary = Summary.model_validate_json(response.content)
print(f"Title: {summary.title}")
print(f"Sentiment: {summary.sentiment}")

Last updated: November 25, 2026