Sub topic 2
JSON Mode: Valid JSON, Not Necessarily Your Schema
Assume you know basic Python, JSON, and how to call an LLM API. This chapter compares three output controls and shows where validation belongs.
JSON Mode
JSON mode asks the model to return syntactically valid JSON instead of ordinary prose. A JSON parser can read the result reliably:
import json
raw = '{"category": "billing", "priority": 1}'
data = json.loads(raw)
print(data["category"])However, JSON mode usually checks only the outer syntax. It does not guarantee the required keys, correct types, allowed values, or useful meaning. The model might return {"category": "unknown"}, omit priority, or put a string in a numeric field.
Schema-Constrained Structured Outputs
Schema-constrained output gives the provider a JSON Schema and asks it to restrict generation to that shape. A schema can define properties, required fields, types, enums, and limits.
This approach reduces structural errors because the decoder rejects many invalid token choices during generation. It still does not prove that the extracted facts are true. A correctly shaped "priority": 1 can still be wrong.
Function and Tool Calling
Function calling represents the requested data as arguments to a declared function or tool. The model selects the tool and supplies arguments matching its declared schema. Your program then decides whether to execute the tool or merely use the arguments as extracted data.
This is useful when structured output represents an action, such as create_ticket(category, summary). Treat tool calls as untrusted input. Do not execute a consequential action without authorization and validation.
| Method | Main guarantee | Remaining risk |
|---|---|---|
| JSON mode | Valid JSON syntax | Wrong shape or values |
| Schema-constrained output | Usually valid target shape | Semantic errors or refusal |
| Function calling | Named action and arguments | Unsafe or incorrect arguments |
Validate Before Use
Validate at the boundary, before storing data or invoking a tool. A Pydantic model checks both structure and constraints:
from typing import Literal
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: Literal["billing", "bug", "other"]
priority: int = Field(ge=1, le=3)
summary: str = Field(max_length=200)
candidate = '{"category":"bug","priority":1,"summary":"Login fails"}'
ticket = Ticket.model_validate_json(candidate)
print(ticket.model_dump())Catch validation errors, record the failure, and use a bounded retry or safe fallback. Never silently accept invalid output.
Exercise
Why is validation still required when schema-constrained output is enabled?
Show answer
The result can have the right shape while containing incorrect facts, unsafe arguments, or a refusal.