API / return-structured-json-from-grok-api

API

Return structured JSON from the Grok API

Return structured JSON from the Grok API

Set response_format.type to "json_schema" and put the schema under response_format.json_schema. The same field also accepts "json_object" for any well-formed JSON, or "text" (the default) for free-form output.

SDK parse

The xAI Python SDK parses into a Pydantic model with chat.parse(Model):

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

class Bug(BaseModel):
    file: str = Field(description="Path to the file")
    line: int = Field(description="Line number")
    summary: str = Field(description="What is wrong")

client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(model="grok-4.6")
chat.append(user("Find the bug: function median(a){a.sort();return a[a.length/2]}"))
response, bug = chat.parse(Bug)
print(bug.file, bug.line, bug.summary)

chat.parse returns (Response, Model). You can also pass the Pydantic class as response_format and call sample() or stream(); then parse response.content yourself.

Schema rules the API enforces

  • additionalProperties defaults to false. Set it true only when you need extra keys.
  • Combining tools with structured output works on supported Grok 4 family models.
  • These schemas return 400: empty enum or anyOf, a property schema of true or false, maxContains / minContains, and items as an array (use prefixItems for tuples).

Pitfalls

  • Draft 2020-12 schemas work best; Draft-07 is accepted.
  • Keywords such as not and multi-schema allOf are accepted but not structurally enforced. Validate if you need a hard guarantee.
  • A key with no Console balance fails even if grok.com still works. Console API credits are a separate bill from SuperGrok's weekly pool.