Schema-Guaranteed JSON
On this page
Why structured outputs change everything
When you use a language model in production, you need responses code can use. Not free text, not approximate JSON—JSON guaranteed compliant with a schema you define. That’s exactly what Grok API structured outputs offer you.
The principle is simple: you provide a JSON schema to the model, and the API guarantees that the response will follow this structure exactly. No haphazard parsing, no fragile regex, no try/catch to handle cases where the model invents a format.
How it works
Structured outputs rely on a constraint mechanism applied during generation of the text. At each token produced, the model is constrained to generate only tokens compatible with the provided schema. The result: JSON that is always valid, always compliant.
Let’s look at a concrete example. You want to extract contact information from an email:
from pydantic import BaseModel
class Contact(BaseModel):
nom: str
email: str
entreprise: str
telephone: str | None
# The response will ALWAYS be a valid Contact object
Without structured outputs, the model might return the phone as "tel", "phone", or "numéro". With a schema, the field will always be called telephone, and its value will always be a string or null.
Availability
Structured outputs are supported on all xAI language models: Grok 4.5, Grok 4.3, grok-4.20 variants, and later versions. Whichever model you use, the feature is available without extra cost or additional configuration.
Without vs. With Structured Outputs
Here’s what you get without and with this feature:
Without structured outputs:
- The model may return free text, partial JSON, or an unexpected format
- You must parse manually and handle errors
- Field names may vary from one request to another
- Your pipeline breaks as soon as the model changes format
With structured outputs:
- The JSON is always syntactically valid
- The structure matches the provided schema exactly
- Types are respected (string, number, boolean, etc.)
- Your code can consume the response directly
Two available approaches
The Grok API offers two methods to use structured outputs:
parse(): Automatic method that returns a typed object directly. Ideal for most cases.response_format: Manual method that returns a JSON string. More control, but parsing is on you.
You will discover these two methods in detail in the upcoming lessons.
Key takeaways
- Structured outputs guarantee JSON compliant with your schema on every call
- The constraint is applied during generation, not after
- All xAI language models support this feature
- Two methods are available:
parse()(automatic) andresponse_format(manual) - This is the foundation of any reliable production pipeline with the Grok API