Many apps need a model's answer in a fixed shape: a JSON object with specific fields, not a paragraph of text. Asking nicely in the prompt ("reply in JSON") usually works, but not always: the model can add a sentence before the JSON, wrap it in a markdown code block, or leave out a field. There are three levels of reliability, from weakest to strongest.
Level 1: Ask in the prompt
Works most of the time, fails occasionally. Use it only for low-stakes cases, or combine it with one of the stronger options below.
messages = [{"role": "user", "content":
'Extract the name and age from this text as JSON with keys "name" and "age": '
'"Maria is 34 years old."'}]
Level 2: JSON mode
Setting response_format={"type": "json_object"} forces the output to be syntactically valid JSON. It does not enforce which fields are present, so mention the exact field names in the prompt.
from openai import OpenAI
import json
client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])
resp = client.chat.completions.create(
model="gpt-6-luna",
response_format={"type": "json_object"},
messages=[{"role": "user", "content":
'Extract the name and age as JSON with keys "name" and "age": "Maria is 34 years old."'}],
)
data = json.loads(resp.choices[0].message.content)
print(data["name"], data["age"])
JSON mode requires the word "JSON" to appear somewhere in the conversation, usually in the system or user message; some models return an error otherwise.
Level 3: JSON Schema (recommended)
Setting response_format to a JSON Schema constrains both the syntax and the shape: required fields, types, and enums are enforced during generation, not just checked afterward.
schema = {
"type": "json_schema",
"json_schema": {
"name": "person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
"additionalProperties": False,
},
"strict": True,
},
}
resp = client.chat.completions.create(
model="gpt-6-luna",
response_format=schema,
messages=[{"role": "user", "content": "Maria is 34 years old."}],
)
data = json.loads(resp.choices[0].message.content)
Keep the schema as small as the task needs. A schema with many optional fields and nested objects is harder for a model to fill in correctly than a flat schema with a few required fields.
Anthropic Messages format
The Messages API does not have a dedicated JSON mode; the reliable way is to describe the schema in the system prompt and ask the model to call a tool, since tool-call arguments already follow a JSON Schema strictly.
import anthropic
client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
tools = [{
"name": "extract_person",
"description": "Record the extracted person",
"input_schema": {
"type": "object",
"properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
"required": ["name", "age"],
},
}]
resp = client.messages.create(
model="claude-opus-4-8", max_tokens=256,
tool_choice={"type": "tool", "name": "extract_person"},
tools=tools,
messages=[{"role": "user", "content": "Maria is 34 years old."}],
)
data = next(b.input for b in resp.content if b.type == "tool_use")
A fallback for when parsing still fails
Even with a schema, treat the response as untrusted input: a long context, a weird edge case, or a model limitation can still produce broken output. Wrap the parse in a retry:
import json
def extract(prompt, retries=2):
last_err = None
for _ in range(retries + 1):
resp = client.chat.completions.create(model="gpt-6-luna", response_format=schema,
messages=[{"role": "user", "content": prompt}])
try:
return json.loads(resp.choices[0].message.content)
except json.JSONDecodeError as e:
last_err = e
raise last_err
Also validate the parsed object against your schema in code (with a library such as pydantic or jsonschema) before using it, even when the API enforced the schema server-side. Treat any field the model fills in as untrusted input, the same as user input, before it reaches a database query, a shell command, or a file path.
Model support
JSON Schema support varies by model; check the capabilities list on a model's page in the marketplace before relying on strict: true. A few models with structured output support:
| Model | Input / 1M tokens | Output / 1M tokens | vs. official price |
|---|---|---|---|
GPT-6 Lunagpt-6-luna | $0.05 | $0.30 | 40% off |
Claude Opus 4.8claude-opus-4-8 | $0.375 | $1.875 | 92.5% off |
DeepSeek V4 Prodeepseek-v4-pro | $0.3857 | $1.1571 | 41.6% off |
Create a free accountRead the API docs