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 or Zod to enforce data types, constraints, and structure.When using structured outputs, the LLM's response is guaranteed to match your input schema.Structured outputs is supported for the following models: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:Line items (description, quantity, price)
Total amount and currency
We'll use structured outputs to have Grok generate a strongly-typed JSON for this.
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.Given a raw invoice, carefully analyze the text and extract the relevant invoice data into JSON format.
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 the structured outputs feature of the the SDK to parse the invoice.The output will always be type-safe and respect the input schema.{
"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"
}
Modified at 2025-04-10 09:15:40