Sub topic 1
Why free text is a poor interface for code
Prerequisites
This chapter assumes you know basic Python, including classes and exceptions. You should also be comfortable reading JSON and have called an LLM API at least once. No other setup is needed.
The problem: programs need a known shape
A language model produces text. A program needs data in a known shape, such as a dictionary with certain keys, each holding a value of a certain type. Between those two sits a gap, and most of the work in this tutorial is about closing it.
Suppose you build a support tool. It reads a ticket and must route it to a team. Your code expects a category and a priority number. You ask the model to triage the ticket, and you get replies like these on different runs:
This looks like a billing issue. I'd call it priority 2.Category: Billing | Priority: MediumSure! Here is the JSON you asked for:followed by a JSON object.- A JSON object wrapped in a Markdown code fence.
Each reply is reasonable to a human reader. Each one breaks a different line of code.
How parsing free text fails
A first attempt often uses string matching or a regular expression. Here is a version that works on one phrasing.
import re
def parse_reply(reply: str) -> dict:
category = re.search(r"category:\s*(\w+)", reply, re.IGNORECASE).group(1)
priority = int(re.search(r"priority:\s*(\d)", reply, re.IGNORECASE).group(1))
return {"category": category, "priority": priority}
print(parse_reply("Category: billing\nPriority: 2"))This prints {'category': 'billing', 'priority': 2}. Now try the reply Category: billing\nPriority: Medium. The second re.search returns None, and calling .group(1) raises AttributeError. A different reply, This is a billing issue., fails on the first line.
The failures fall into a few kinds:
| Failure | Example | What your code sees |
|---|---|---|
| Wrong format | `Priority: Medium` instead of a number | A value that cannot be converted |
| Extra text | `Sure! Here is the JSON:` before the data | A parse error on the first character |
| Wrapper | The JSON inside a code fence | A parse error on the backticks |
| Wrong name | `type` instead of `category` | A missing key |
| Wrong value | `Billing`, `payments`, `bill` | A string your routing table does not know |
Notice that the last row is not a parsing problem. The reply is valid text in the right place, but the value is not one your program can use.
Why the model varies
A model generates text one token at a time. A token is a small piece of text, often a word or part of a word. At each step it picks the next token from a probability distribution. Unless you set the sampling temperature to zero, two runs on the same input can differ. Even at temperature zero, different model versions and providers may phrase things differently.
The model is also trained to be a helpful conversational partner. That is why it adds greetings, explanations, and formatting you never asked for. Your instruction "reply with JSON" is a request the model usually honors. It is not a rule the model is forced to follow.
This gives the core idea of the tutorial: a prompt is a suggestion, and a schema is a contract. You will move from the first to the second step by step.
What a reliable interface needs
A reliable interface between a model and a program has three properties.
- A fixed structure. The same keys and types appear on every reply.
- Restricted values. Fields such as
categoryaccept only values from a known list, and numbers stay in a known range. - A way to detect failure. When a reply breaks the contract, your code finds out immediately and can retry or stop, instead of passing bad data downstream.
The third property matters most. A crash is better than a silent error. If priority quietly becomes 0 because of a bad parse, a ticket might be filed under the wrong urgency and nobody notices for weeks.
The path through this tutorial
The rest of the tutorial adds one layer at a time. The diagram shows where each technique sits between the model and your code.
You will first describe the shape you want with a schema. Then you will compare ways of asking the model to follow it: the prompt alone, JSON mode, schema-constrained decoding, and function calling. Last, you will validate every reply and handle failures in a bounded loop.
Summary of the idea
Free text is written for people, who forgive variation. Code does not. The fix is not a cleverer regular expression. It is a defined shape, a way to ask the model for that shape, and a check that runs before any data reaches the rest of your program.
Exercise
A reply contains {"category": "Billing", "priority": 2, "summary": "Charged twice"}. It parses as JSON, but your router accepts only the lowercase value billing. Which of the three properties of a reliable interface is missing, and what kind of failure is this?
Show answer
Restricted values is missing. The structure is correct and the reply parses, so this is a wrong-value failure, not a parsing failure. A schema that lists the allowed categories as an enum would reject Billing and let your code retry or stop.
Exercise
Why is a regular expression a weak long-term fix for model output that varies between runs?
Show answer
A regular expression matches only the phrasings you thought of. The model can produce new phrasings, extra text, or wrappers on any run, and the match then fails or returns the wrong part. A schema defines the allowed output once and checks every reply against it.