Sub topic 1
Why Free Text Is a Poor Interface for Code
Prerequisites
Assume you know basic Python, classes, exceptions, and JSON. You should also have called an LLM API at least once.
Why Free Text Is a Poor Interface for Code
An LLM normally returns text. Text is flexible for people but fragile for programs. A reply might include a Markdown code fence, extra commentary, a missing field, or a value with the wrong type.
For example, code expecting priority to be an integer can fail when the model returns "high". Parsing JSON only checks syntax. It does not prove that the data has the fields or values your application requires.
Describing the Shape You Want with JSON Schema
JSON Schema is a standard description of JSON data. It can specify property names, types, required fields, allowed values, and limits.
{
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "bug", "other"]
},
"priority": {
"type": "integer",
"minimum": 1,
"maximum": 3
}
},
"required": ["category", "priority"],
"additionalProperties": false
}This schema defines a JSON object with exactly the fields needed for ticket triage. The schema is a contract for validation and, when supported by the provider, for constrained generation.
Defining the Schema as a Pydantic Model
Pydantic is a Python library that validates data using typed models. It can also generate JSON Schema.
from typing import Literal
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "other"]
priority: int = Field(ge=1, le=3)
print(TicketTriage.model_json_schema())The model makes the contract executable. After receiving a response, call TicketTriage.model_validate_json(raw) before passing the result to application code.
Asking for a Format in the Prompt
Prompting alone is the most portable approach:
prompt = """Return one JSON object only.
Use the keys "category" and "priority".
category must be billing, bug, or other.
priority must be an integer from 1 through 3."""This improves consistency, but it does not guarantee compliance. Prefer provider-supported JSON mode or schema-constrained output when available, and always validate the result yourself.
Exercise
Why is valid JSON not enough for this ticket-triage example?
Show answer
Valid JSON can still omit required fields or contain invalid values, such as a priority of 9.