Agentic AI System Design / Chapter 1: Inference: Decoding, Structured Outputs & Serving
Scenario 1.2Structured Extraction · Customer Support
Return ONLY Valid JSON

1The Setup & Tipping Point
You have just joined Vespera Air, a European airline handling about 50,000 customer messages a day, as Senior AI Engineer on Customer Operations. Six months ago, the first step of every message was automated:
- Extraction: a self-hosted QwenX-32B, sharing the website chatbot’s serving configuration, turns each message into a ticket: booking reference, category (one of six), priority, flights and dates, refund amount and currency, a one-line summary, and a special-assistance flag. Every field is required. The prompt includes one example pair (a delayed-bag complaint) and ends with “Return ONLY valid JSON matching this schema. No markdown, no commentary.”
- Automation: the ticketing system parses the JSON, checks it against the schema (required fields and their types), routes each ticket, alerts the airport desk to assistance requests, and auto-processes refunds under €250.
In production, responses that fail to parse or violate the schema are retried up to three times, and a lenient fallback parser, added last month, keeps whatever fields it can read and fills in the rest with defaults (false for yes/no fields, 0 for amounts).
| Breaks the parser | |
|---|---|
| 1Fail to parse · parse, but violate the schema | 2.1% · 3.4% |
| Typical failures: unparseable · schema-breaking | “Sure! Here is the…” · "refund": "fifty euros" |
| 2Parse failures: 1–2 flights · 3+ flights | 0.9% · 38% |
| 3Still failing after 3 retries · patched by the fallback | ≈ 380/day · ≈ 300/day |
| Parses, but wrong (audit of 500 valid tickets) | |
| 4Tickets categorized baggage: model · humans | 41% · 18% |
| 5No booking reference in the message, but one on the ticket | 64% |
| Dates wrong when the message said “yesterday” · refund amounts wrong | 71% · 7% |
Last week a default false from the fallback nearly left a wheelchair passenger without assistance. The fallback is now off, the manual queue is growing, and storm season, at four times the volume, is six weeks away.
2Digest & Disarm
The questions worth asking
Were the generation settings tuned for extraction?
No. They are the chatbot’s: temperature 0.7 and a 256-token output limit.
Can we change how the model generates, or only the prompt?
Anything. The model runs on a standard open-source inference server that we operate.
Can we verify what the model extracts against our own records?
Yes. The booking database answers a lookup by reference in about 20 ms and holds the passengers, fares paid, and assistance requests on each booking.
What does a wrong ticket cost compared with a late one?
A late ticket waits a few hours in the manual queue. A wrong refund under €250 is paid automatically and rarely recovered, and a missed assistance flag is a passenger-safety incident.
The instinctive trap
Harden the prompt and add safety nets. A couple of the more advanced-sounding answers are simply wrong. The rest help, so they are not wrong, but they are not enough, and trying them reveals the second layer.
“Send broken JSON to a second model to repair it.” — A repair is one more request to a larger probabilistic model: it doubles the cost of each failure and guarantees nothing. It can also change values while fixing the syntax, and a response cut off mid-object has lost fields a repair can only invent.
“Fine-tune the model until it always returns valid JSON.” — Weeks of work to make failures rarer, not impossible, and no amount of training fixes a 256-token limit or a field the message never contained.
A louder prompt. Stronger wording and more worked examples make preambles rarer, never zero: the model was post-trained to talk to people, and instructions and examples only shift probabilities. The one example already there, a baggage complaint, is also why baggage is predicted at more than twice the human rate.
More attempts. At temperature 0.7, each retry is a fresh roll of the dice, so random failures go away. A three-flight itinerary that needs more than 256 tokens fails identically every time, which is why about 14% of failures survive three retries.
A safety net. Switching the fallback back on drains the queue, but only by converting every ticket it cannot fully read into one with silent defaults, which is how the wheelchair request was missed.
What this really is
It is a guarantee problem at three levels: that the output is JSON, that it fits the schema, and that it is true. Every fix above aims at the first two; none of them even aims at the third, and no retry, repair, or prompt supplies a booking reference the message never contained, or a date for “yesterday” the model was never given.
It is not a model problem. The model already knows JSON and understands the messages; a bigger one fails in the same places.
Root-cause map
"refund": "fifty euros"false3The Pro Architecture
Decision 1Enforce the format in the decoder, not the prompt
Fixes: preambles, wrong types, truncation, retries
Turn on schema-constrained generation. You already know top-k and top-p, which narrow the distribution at each step; this goes one step further and zeroes out every token the schema forbids. After "refund":, only digit tokens remain: “fifty” is not unlikely, it is impossible. A preamble, a code fence, an unescaped quote, or an invalid enum value cannot be sampled at all. Better still, let the engine write the structure itself (braces, keys, commas), with the model generating only the values. Set temperature to 0, because extraction has one right answer and nothing to gain from variety. Size the output limit from the schema rather than the chatbot (a ticket is about 150 tokens before any flights, and each flight adds about 50), cap the summary’s length so the object always closes inside it, and treat a response that stops on the length limit as a failure to log, never one to retry. Retries now exist only for infrastructure errors.
Decision 2Extract with the model; compute and check with code
Fixes: silent defaults, invented references, wrong dates and amounts
Delete the fallback parser: a missing field is a failure, never a default. Instead, make every field a message might not contain nullable, so the model is never forced to invent a booking reference. A default such as false or 0 looks exactly like a real answer; only a null says the message didn’t contain one. Have the model extract rather than compute: the date as written (“yesterday”), the amount and currency as written, and, new to the schema, the passenger count, with a short quote from the message placed before each high-stakes value. The model generates left to right, so a value written after its evidence is grounded in it, and the quote gives the model room to think that a grammar forcing answers from the first token would not. Code then does the arithmetic, resolving “yesterday” against the message’s sent-at timestamp. Finally, check every ticket against Vespera Air’s own systems: the booking reference must exist and belong to the sender, a refund cannot exceed the fare paid, and an assistance request on the booking overrides a false in the ticket. Each failure gets a type, and goes to a human with the source sentence highlighted.
Decision 3Treat the examples as data, not decoration
Fixes: the baggage skew
The prompt’s only worked example is a baggage complaint, so the model has learned that a typical message is about baggage. Replace it with a handful of examples that cover the categories and the hard cases: a multi-flight itinerary, a message with no booking reference (and a null in the output), a relative date, an assistance request, and a non-English message. Even diverse examples bias the labels through their order and balance, so they are a starting point, not a control. Give each category a one-line definition in the prompt, and monitor the predicted category distribution daily against a small, rolling human-labeled sample, so the next skew shows up in a chart instead of an audit.
4Beyond: The Signal Ladder and Stretch Round
That was 1 of 18
The Complete Edition has all 18, published progressively on Leanpub. The free Core Edition has 6 scenarios, one from every chapter, plus the framework behind them.