# Structured Outputs

Structured Outputs is a feature that lets the API return responses in a specific, organized format, like JSON or other schemas you define. Instead of getting free-form text, you receive data that's consistent and easy to parse.

Ideal for tasks like document parsing, entity extraction, or report generation, it lets you define schemas using tools like [Pydantic](https://pydantic.dev/) or [Zod](https://zod.dev/) to enforce data types, constraints, and structure.

When using structured outputs, the LLM's response is **guaranteed** to match your input schema.

## [Supported models](https://docs.x.ai/docs/guides/structured-outputs#supported-models)

Structured outputs is supported for the following models:

- `grok-3`
- `grok-3-fast`
- `grok-3-mini`
- `grok-3-mini-fast`
- `grok-2-vision-1212`
- `grok-2-1212` (deprecated)

## [Example: Invoice Parsing](https://docs.x.ai/docs/guides/structured-outputs#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 ensure 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](https://docs.x.ai/docs/guides/structured-outputs#step-1-defining-the-schema)

You can use [Pydantic](https://pydantic.dev/) or [Zod](https://zod.dev/) to define your schema.

```python
from pydantic import BaseModel, Field
from datetime import date
from enum import Enum
from typing import List

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](https://docs.x.ai/docs/guides/structured-outputs#step-2-prepare-the-prompts)

### [System Prompt](https://docs.x.ai/docs/guides/structured-outputs#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](https://docs.x.ai/docs/guides/structured-outputs#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](https://docs.x.ai/docs/guides/structured-outputs#step-3-the-final-code)

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

```python
from openai import OpenAI

from pydantic import BaseModel, Field
from datetime import date
from enum import Enum
from typing import List

# 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 = OpenAI(
    api_key="<YOUR_XAI_API_KEY_HERE>",
    base_url="https://api.x.ai/v1",
)

completion = client.beta.chat.completions.parse(
    model="grok-3",
    messages=[
        {"role": "system", "content": "Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format."},
        {"role": "user", "content": """
            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
        """}
    ],
    response_format=Invoice,
)

invoice = completion.choices[0].message.parsed
print(invoice)
```

### [Step 4: Type-safe Output](https://docs.x.ai/docs/guides/structured-outputs#step-4-type-safe-output)

The output will **always** 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"
}
```
