Sub topic 5
JSON mode: valid JSON, not necessarily your schema
This chapter assumes you can write basic Python with classes and exceptions, read JSON, and have called an LLM API before. It also assumes you have met the TicketTriage Pydantic model from the earlier chapter on schema models.
What JSON mode does
JSON mode is a provider setting that forces the model's reply to be syntactically valid JSON. In OpenAI-style APIs you enable it with response_format={"type": "json_object"}. Other providers use different names for the same idea.
This removes one common failure from prompt-only formatting. You no longer get a reply like "Sure! Here is your JSON:" followed by the object, or a Markdown code fence around it. You can call json.loads on the reply and expect it to parse.
JSON mode does not know your schema. It guarantees that the text is JSON, nothing more. The model can still:
- use different key names than you asked for
- leave out required fields or add extra ones
- return
"high"where you wanted an integer - return a value outside your limits, such as a priority of 5
- return an array or a bare string instead of an object, depending on the provider
Using it
Most providers also require the prompt to contain the word "JSON". Without it, some APIs reject the request or let the model emit endless whitespace. Describe the keys and allowed values in the prompt yourself, because the API will not do that for you.
from openai import OpenAI
client = OpenAI()
SYSTEM_PROMPT = (
"Triage the support ticket. Reply with a JSON object with exactly these keys: "
"category (one of billing, bug, feature_request, other), "
"priority (integer 1 to 3, where 1 is most urgent), "
"summary (one sentence, at most 200 characters)."
)
def triage_json_mode(ticket_text: str) -> str:
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": ticket_text},
],
)
choice = response.choices[0]
if choice. "length":
raise ValueError("Reply was cut off, so the JSON is probably incomplete")
return choice.message.contentThe `finish_re If the reply hits the token limit, the JSON can be cut off mid-object. Some providers document that the output may then be invalid despite JSON mode. Truncation is covered in more detail in the chapter on failure modes.
Why you still need validation
The next example runs without an API key. It shows three replies that all pass json.loads but only one that matches the schema.
import json
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
replies = [
'{"category": "billing", "priority": 1, "summary": "Customer was charged twice."}',
'{"type": "billing", "priority": "high", "summary": "Customer was charged twice."}',
'{"category": "bug", "priority": 5, "summary": "App crashes on login."}',
]
for raw in replies:
data = json.loads(raw) # succeeds for every reply
try:
ticket = TicketTriage.model_validate(data)
print("valid:", ticket)
except ValidationError as err:
print("invalid JSON for our schema:")
print(err)The second reply uses type instead of category and the string "high" instead of an integer. The third has a priority above the limit. Pydantic reports each problem with the field name, so you can log it or feed it back to the model.
When to choose JSON mode
JSON mode fits when your provider offers nothing stronger, or when the shape is loose, such as "a JSON object with any useful fields". It is also a cheap upgrade over prompt-only formatting, since you can drop the code-fence stripping step.
If you need the reply to match a specific schema, use schema-constrained structured outputs instead, which the next chapter covers. Constrained decoding enforces key names, types, and enums while the model generates. Either way, keep your validation step. Constrained outputs still do not guarantee the values are right.
Exercise
A teammate says, "We turned on JSON mode, so we can delete the Pydantic validation." Give two concrete reasons this is wrong, using the ticket triage example.
Show answer
JSON mode only guarantees syntactically valid JSON, not your schema. The model can still return wrong key names (such as "type" instead of "category"), wrong types (such as "high" instead of an integer), or values outside the limits (such as a priority of 5). Also, a reply cut off by the token limit may be incomplete JSON. Validation catches all of these before the data reaches the rest of the program.