Sub topic 1
Why free text is a poor interface for code
Language models write text. Programs need data in a known shape. This chapter explains where the two collide, what breaks when you ignore the gap, and what the rest of this tutorial does about it.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including classes and exceptions.
- Familiarity with JSON: objects, arrays, strings, numbers, booleans, and
null. - Experience calling an LLM API at least once, so you know what a prompt and a text reply look like.
You do not need any structured-output feature yet. Later chapters introduce JSON Schema, Pydantic, JSON mode, constrained decoding, and function calling.
The gap between text and data
A model's reply is a string. When a person reads it, small variations in wording, order, and formatting do not matter. When a program reads it, they matter a great deal.
Suppose you build a support tool that triages tickets. You want to route each ticket to a queue and set an urgency. You ask the model:
Triage this support ticket: "I was charged twice for my subscription this month and nobody has answered my email."On three runs you might get these replies:
This looks like a billing issue. I'd say it's high priority.Category: Billing
Priority: 1 (urgent)
Summary: Customer was double charged and has had no reply.Sure! Here's the triage:
{"category": "billing", "priority": 1, "summary": "Double charge, no reply"}
Let me know if you'd like anything else.All three are reasonable answers. A person can act on any of them. Your code cannot, because each one needs a different parser. The third one contains JSON, but it is surrounded by text, so a call to json.loads on the whole reply fails.
What the program actually needs
Code consumes values through a contract. A function that routes a ticket needs to know:
- Which fields exist, and what they are called.
- What type each field has (string, integer, list).
- Which values are allowed (for example, only four categories).
- Which fields are always present, and which may be missing.
- What happens when the reply does not fit.
Free text gives you none of these guarantees. The model may follow the contract most of the time, but "most of the time" is a different thing from "always". A parsing step that works on 97 of 100 inputs will fail in production, because production sends thousands of inputs.
Common ways free-text parsing fails
The table lists failures you will see when you parse model replies with string operations or regular expressions.
| Failure | Example | What your code does |
|---|---|---|
| Extra prose around the data | `Here is the JSON: {...}` | `json.loads` raises `JSONDecodeError` |
| Code fence around the data | A reply that starts with three backticks and `json` | Parsing fails on the first character |
| Field name drift | `Priority`, `priority_level`, `urgency` | `KeyError`, or a silent `None` |
| Wrong type | `"priority": "high"` instead of `1` | Comparison raises `TypeError`, or sorts wrongly |
| Value outside the allowed set | `"category": "Billing issue"` | Routing table lookup fails |
| Missing field | No `summary` key | `KeyError` later, far from the cause |
| Extra field | `"confidence": "very high"` | Ignored, or rejected by a strict consumer |
| Truncated output | JSON cut off at the token limit | Parse error, or a half-built object |
| Invented value | A plausible but wrong order ID | No error at all |
The last row is the most dangerous. Every other failure raises an error you can catch. A wrong value that has the right shape passes silently into your database. Later chapters return to this under semantic errors.
A fragile parser, step by step
Here is the kind of code people write first. It asks for JSON in the prompt and parses the reply with json.loads.
import json
def triage_naive(ticket_text, call_llm):
"""call_llm(prompt) -> str is any function that returns the model's text reply."""
prompt = (
"Triage this support ticket and reply with JSON containing "
"category, priority and summary.\n\n" + ticket_text
)
reply = call_llm(prompt)
data = json.loads(reply)
return data["category"], data["priority"], data["summary"]This function has at least five ways to fail, and none of them is handled:
json.loads(reply)raisesJSONDecodeErrorif the reply has any text before or after the object.data["category"]raisesKeyErrorif the model used a different key name.data["priority"]may be the string"high", and the function returns it without complaint.data["category"]may be"Billing"with a capital letter, which your routing table does not know.- Any exception propagates to the caller, so one bad reply can stop a batch job.
You can see the problem by feeding the function canned replies instead of calling a real model. The following program is complete and runs as shown.
import json
def triage_naive(ticket_text, call_llm):
prompt = (
"Triage this support ticket and reply with JSON containing "
"category, priority and summary.\n\n" + ticket_text
)
reply = call_llm(prompt)
data = json.loads(reply)
return data["category"], data["priority"], data["summary"]
replies = [
'{"category": "billing", "priority": 1, "summary": "Double charge"}',
'Here you go:\n{"category": "billing", "priority": 1, "summary": "Double charge"}',
'{"category": "Billing", "priority": "high", "summary": "Double charge"}',
'{"type": "billing", "priority": 1, "summary": "Double charge"}',
]
for reply in replies:
try:
result = triage_naive("I was charged twice.", lambda prompt: reply)
print("returned:", result)
except Exception as err:
print("failed:", type(err).__name__, err)Running it prints:
returned: ('billing', 1, 'Double charge')
returned: ...The exact output is easier to predict than to quote, so here is what each case does:
- Reply 1 returns
('billing', 1, 'Double charge'). - Reply 2 raises
JSONDecodeError, because of the leadingHere you go:. - Reply 3 returns
('Billing', 'high', 'Double charge'). No error is raised, but the values are wrong for any code that expects a lowercase category and an integer priority. - Reply 4 raises
KeyError: 'category'.
Case 3 shows the core issue. Parsing succeeded, yet the data is unusable. A parser can only check syntax. Checking that the data has the right shape and values is a separate job called validation, which a later chapter covers.
Why models drift
Models are not being careless. Free-text variation comes from how they work.
- Sampling. A model picks each next token from a probability distribution. Unless you set the temperature to zero, the same prompt can yield different text on different runs. Even at temperature zero, providers do not always promise identical output across calls.
- Training for chat. Chat models are tuned to be helpful and conversational. Adding an introduction or a closing offer is often what they learned to do.
- Instructions compete. "Reply with JSON only" competes with everything else in the prompt. Long inputs, unusual tickets, and ticket text that contains its own instructions can all pull the reply off format.
- No built-in schema. A prompt describes a format in words. The model has no mechanism that forces its tokens to obey those words, unless you use a feature that does (covered in later chapters).
- Output limits. A reply that hits the maximum token count stops mid-sentence, even if it is in the middle of a JSON string.
Where the failures show up
A failure at the model boundary is cheap if you catch it there and expensive if it travels. The diagram shows the same bad reply at two points.
With a check at the boundary, a bad reply becomes an error you can log, count, and retry. Without it, the bad value travels into other systems and surfaces later as a wrong report or a failed job, far from the model call that caused it.
The idea behind structured output
Structured output means asking the model for data that matches a declared shape, then checking that it does. The approach has three parts:
- Declare the shape. Describe the fields, types, and allowed values once, in a form both humans and tools can read. JSON Schema is the standard format for this.
- Steer the model. Use the strongest technique your provider supports to get replies in that shape: a prompt, JSON mode, schema-constrained decoding, or function calling.
- Validate before use. Parse the reply into a typed object and reject it if it does not fit. Handle rejection deliberately, for example by retrying.
The techniques in step 2 differ in how much they guarantee. The following table previews them. Each gets its own chapter.
| Technique | What it improves | What it does not guarantee |
|---|---|---|
| Prompt only | Costs nothing to try | Any format at all |
| JSON mode | Reply is syntactically valid JSON | That the JSON matches your schema |
| Schema-constrained decoding | Reply matches the schema | That the values are true or sensible |
| Function or tool calling | Arguments follow a declared schema | That the model picks the right tool or values |
No row in the table promises correct values. Even the strongest option controls shape, not truth. That is why validation and testing remain part of every pipeline.
A target to aim for
The rest of the tutorial builds toward one running example: the TicketTriage extraction. Here is the shape we want, written as a Python class that the next chapters explain.
from typing import Literal
from pydantic import BaseModel, Field
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")Read it as a contract. category must be one of four strings. priority must be an integer from 1 to 3. summary must be a string of at most 200 characters. Reply 3 from the earlier experiment ("Billing" and "high") would be rejected by this class, and the error would name both fields. You will see how in the chapters on schema models and validation.
When free text is still fine
Not every call needs structure. If a person reads the output, such as a chat answer, a draft email, or a summary shown on a screen, free text is the right interface. Add structure when a program consumes the result:
- Routing or classification, where the next step depends on a label.
- Extraction of fields into a database or form.
- Calls to other services, where arguments must have exact types.
- Evaluation and logging, where you count and compare results.
A mixed design is common. Ask for a structured object that contains one free-text field, such as summary, and let the model write prose only inside that field.
Key points
- Model replies are strings, and the wording, order, and format of those strings vary between runs.
- Parsers that depend on text patterns fail on prose around the data, renamed keys, wrong types, and out-of-range values.
- The worst failures raise no error, because the data has the right shape but the wrong content.
- Structured output has three parts: declare the shape, steer the model toward it, and validate the result.
- Techniques differ in how much they guarantee. None of them guarantees that values are true.
Exercise
Look at this reply to a request for a ticket triage: Sure! {"category": "bug", "priority": 2, "summary": "App crashes on login"}. Name two things that could go wrong when a program handles it, and say which kind of failure is harder to detect.
Show answer
First, json.loads fails with JSONDecodeError because of the leading Sure! , which is a loud, easy-to-detect failure. Second, even after the prose is removed, the program has no check that priority is in the allowed range or that category is an allowed value, so a wrong but well-formed value would pass silently. The silent failure (a valid shape with a wrong value) is harder to detect, since no exception is raised.
Exercise
The triage_naive function returned ('Billing', 'high', 'Double charge') without raising an error. Which of the three parts of structured output (declare the shape, steer the model, validate before use) would have caught this, and why?
Show answer
Validating before use would catch it, provided the shape was declared. A declared shape says category must be one of billing, bug, feature_request, other, and priority must be an integer from 1 to 3. Validation compares the parsed data to that shape and rejects 'Billing' and 'high'. Steering the model reduces how often such replies occur, but only validation detects the ones that still happen.
Exercise
A teammate says: "We use a feature that forces the model to return valid JSON, so we don't need validation." Give one reason this is not enough.
Show answer
Valid JSON only means the syntax is correct. The JSON can still have the wrong keys, wrong types, or values outside the allowed set unless a schema is enforced. Even when a schema is enforced, the values can be wrong in content (for example, the wrong category for the ticket), and the output can be cut off at the token limit. Validation and testing are still needed.