Structured JSON Output from LLMs: A Practical Guide
Get reliable JSON from LLM APIs: response_format json_object and json_schema, Pydantic and Zod validation, a repair retry and a safe fallback.
Sooner or later every LLM feature needs data, not prose: a category, a list of entities, a set of fields for a form. Language models produce text, so getting machine-readable output takes three things working together — a clear prompt, JSON mode, and validation in your own code.
This guide builds a small support-ticket classifier step by step. The examples use the OpenAI SDKs pointed at FreeModel and the free model gpt-6-luna.
Three levels of strictness
| Approach | How | What it gives you |
|---|---|---|
| Prompt only | "Reply with JSON only" in the system message | Usually JSON, sometimes wrapped in prose or code fences |
| JSON mode | response_format: {"type": "json_object"} | The model is asked to emit a JSON object only |
| Schema | response_format: {"type": "json_schema", ...} | The model also receives the exact schema |
On FreeModel, response_format with type json_object or json_schema is passed through to the model on /v1/chat/completions; other values are ignored. Models that support it show the json_mode capability on the models page. How strictly a schema is enforced depends on the model, which is why step 3 below is not optional.
Step 1: describe the shape in the prompt
JSON mode tells the model that it must answer in JSON, not which JSON. Put the shape in the system message, use the word "JSON" (some providers require it when JSON mode is on), and list allowed values explicitly:
You classify support messages. Reply with JSON only, no prose, matching:
{"category": "billing|bug|question|other", "priority": 1-3, "summary": "<one sentence>"}
Set temperature to 0 for extraction and classification. You want the same answer for the same input.
Step 2: turn on JSON mode
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["FREEMODEL_API_KEY"],
base_url="https://freemodel.in/v1")
r = client.chat.completions.create(
model="gpt-6-luna",
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": "I was charged twice for the Pro plan."},
],
response_format={"type": "json_object"},
temperature=0,
)
print(r.choices[0].message.content)
# {"category": "billing", "priority": 1, "summary": "..."}
Step 3: validate with Pydantic
Never pass model output straight into your database. Parse it into a typed model so wrong types, missing fields and out-of-range values fail loudly:
from typing import Literal
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: Literal["billing", "bug", "question", "other"]
priority: int = Field(ge=1, le=3)
summary: str = Field(max_length=200)
Ticket.model_validate_json(text) raises ValidationError both for broken JSON and for JSON that does not match the model.
Step 4: repair once, then fall back
When validation fails, send the error back to the model once and ask for a corrected object. If that also fails, return a safe default rather than crashing. Here is the full classifier:
import os
import re
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
client = OpenAI(api_key=os.environ["FREEMODEL_API_KEY"],
base_url="https://freemodel.in/v1")
SYSTEM = (
"You classify support messages. Reply with JSON only, no prose, matching: "
'{"category": "billing|bug|question|other", "priority": 1-3, "summary": "<one sentence>"}'
)
class Ticket(BaseModel):
category: Literal["billing", "bug", "question", "other"]
priority: int = Field(ge=1, le=3)
summary: str = Field(max_length=200)
def extract_json(text):
"""Strip code fences or stray prose around a JSON object."""
fenced = re.search(r"```(?:json)?\s*(.*?)```", text, re.S)
if fenced:
text = fenced.group(1)
start, end = text.find("{"), text.rfind("}")
return text[start:end + 1] if start != -1 and end > start else text
def classify(message, model="gpt-6-luna", attempts=2):
messages = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": message}]
for _ in range(attempts):
r = client.chat.completions.create(
model=model, messages=messages,
response_format={"type": "json_object"}, temperature=0)
choice = r.choices[0]
raw = choice.message.content or ""
if choice.finish_reason == "length":
break # cut off: a repair will not help
try:
return Ticket.model_validate_json(extract_json(raw))
except ValidationError as err:
messages += [
{"role": "assistant", "content": raw},
{"role": "user", "content":
f"That JSON was invalid: {err.errors()[:3]}. "
"Reply with only the corrected JSON object."},
]
# safe fallback: route to a human instead of failing the request
return Ticket(category="other", priority=2, summary=message[:200])
print(classify("The export button crashes the app on Android."))
Using json_schema
If you already have a Pydantic model, you can send its schema so the model sees the exact field names and types:
r = client.chat.completions.create(
model="gpt-6-luna",
messages=messages,
response_format={
"type": "json_schema",
"json_schema": {"name": "ticket", "schema": Ticket.model_json_schema()},
},
temperature=0,
)
Keep the same validation and fallback around it. A schema improves the odds; it does not replace checking.
The same in Node with Zod
import OpenAI from "openai";
import { z } from "zod";
const client = new OpenAI({
apiKey: process.env.FREEMODEL_API_KEY,
baseURL: "https://freemodel.in/v1",
});
const Ticket = z.object({
category: z.enum(["billing", "bug", "question", "other"]),
priority: z.number().int().min(1).max(3),
summary: z.string().max(200),
});
export async function classify(text, system) {
const r = await client.chat.completions.create({
model: "gpt-6-luna",
messages: [{ role: "system", content: system }, { role: "user", content: text }],
response_format: { type: "json_object" },
temperature: 0,
});
let parsed;
try {
parsed = Ticket.safeParse(JSON.parse(r.choices[0].message.content ?? ""));
} catch {
parsed = { success: false };
}
return parsed.success
? parsed.data
: { category: "other", priority: 2, summary: text.slice(0, 200) };
}
Common failure modes
- Cut-off JSON.
finish_reasonislength. Raisemax_tokens; reasoning models spend part of the budget thinking (see reasoning docs). - Code fences. Some models wrap JSON in
```jsonblocks even in JSON mode.extract_jsonhandles it. - Numbers as strings.
"priority": "1". Pydantic's default (lax) mode converts it; Zod does not unless you usez.coerce.number(). - Invented categories. The
Literal/enumcheck catches values outside your list. - Huge arrays. Ask for a maximum count in the prompt and enforce it with
max_length.
For calling your own functions with structured arguments, tool calling is often a better fit than JSON mode — see building a function-calling agent.
FAQ
Does JSON mode guarantee valid JSON?
It makes valid JSON much more likely, but output can still be cut off by max_tokens or miss a field. Always parse and validate before you use it.
Which FreeModel models support JSON mode?
Models with the json_mode capability on the models page. The free model gpt-6-luna has it, as do the Claude and GPT-6 models (Claude Haiku 5.5 on the free plan, the others on paid plans).
Should I use json_object or json_schema?
Start with json_object plus a clear description of the shape in the prompt. Add json_schema when you want the model to see the exact schema. Keep your own validation either way.
Do repair retries cost tokens?
Yes. A repair is a new successful request, so its input and output tokens count. Keep the number of repairs low, one is usually enough.
Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.