Picture the ticket. It says "bedrooms showing 1450 on a listing". One listing, one field, a Thursday afternoon. The kind of bug you fix with an UPDATE statement and forget.
Except that the field had not been typed by anyone. It had been extracted by a model, from a free-text property description, by an extraction feature of the kind I have shipped and been quietly proud of. The description mentioned a built-up area of 1,450 square feet. The model, asked for an integer called bedrooms, had found an integer and used it. The JSON was valid. The type was right. The shape matched the schema I had put in the prompt, exactly as requested.
Whoever shipped that feature asked for the right shape and got it. They did not ask for the right answer, because they did not know there was a difference. I have been that person.
That is the whole post, really. The rest is what I do about it now.
A schema in the prompt is a request
There are three ways to ask a large language model for JSON, and they promise different things.
Putting the schema in the prompt and saying "respond only with JSON" promises nothing. You will get a code fence around it sometimes. You will get a sentence before it ("Here is the extracted data:") when the input is unusual. You will get a trailing comma once a month. This was the only option two years ago and I still see it in new code, which is a shame, because it fails in the most ways.
Provider JSON modes and structured outputs promise syntax. The response parses. With a JSON Schema attached, the keys and types match it. That removes a whole class of failure and I turn it on everywhere it exists.
Tool-call mode promises the same thing with a different framing: you define a function with typed parameters, the model "calls" it, and the arguments arrive as a parsed object. For extraction and classification I prefer this, because a tool definition reads as a contract and the model treats it like one.
None of the three promise the values are right. That is the lesson of the 1,450-bedroom listing. A status field typed as an enum of four strings will contain one of the four. Whether it is the correct one is the model's judgement, and the model's judgement is what you were paying for. A publishedAt typed as string will be a string. It may be "last Tuesday".
So the guarantee you get is shape. Correctness still has to be checked by you, at the point where the response lands, and the model has to be treated the way you would treat a form post from the internet: useful, probably fine, not trusted.
Validate at the boundary
The first defence is to write the schema properly. One schema, defined once, in Zod:
import { z } from "zod";
export const Listing = z.object({
title: z.string().min(3).max(200),
price: z.number().int().positive(),
currency: z.enum(["INR", "USD"]),
bedrooms: z.number().int().min(0).max(20).nullable(),
furnished: z.enum(["full", "semi", "none"]),
publishedAt: z.string().datetime({ offset: true }),
summary: z.string().max(400),
});
export type Listing = z.infer<typeof Listing>;Look at bedrooms. The max(20) is not there because I expect a 21-bedroom flat. It is there because 1,450 is a number the model will offer again, and the schema is the place to say no.
The type comes from the schema. I never write the interface by hand and then a validator beside it, because within a month somebody adds a field to one and not the other, and the compiler is happy while production is not.
The same schema generates the JSON Schema that goes in the request, so the prompt, the runtime check and the static type are a single definition:
import { zodToJsonSchema } from "zod-to-json-schema";
const tool = {
name: "record_listing",
description: "Record the structured fields of a property listing. bedrooms is a count of rooms, never an area.",
input_schema: zodToJsonSchema(Listing),
};That one sentence in the description, "never an area", did more for the bedrooms field than any amount of validation. Validation catches the wrong answer. The description stops the model from giving it.
And then the only line that matters:
const raw = extractToolInput(response, "record_listing");
const parsed = Listing.safeParse(raw);
if (!parsed.success) {
throw new ModelOutputError(parsed.error, raw);
}
return parsed.data; // Listing, and nothing downstream sees anything elsesafeParse rather than parse, because I want the failure as a value I can inspect, log and send back to the model, not an exception that bubbles up from somewhere inside the request handler with the raw output lost.
Every constraint in that schema is a wrong answer I have seen or can picture. The datetime({ offset: true }) is there because "2026-11-03" is a string and so is "Tuesday". Each one is cheaper than the bug it prevents, and each one is a line of code rather than a Thursday afternoon.
Retry, but only so many times
When validation fails, the model usually knows how to fix it, if you tell it what was wrong.
async function extract(input: string, attempt = 1, lastError?: string): Promise<Listing> {
const response = await callModel(buildMessages(input, lastError));
const parsed = Listing.safeParse(extractToolInput(response, "record_listing"));
if (parsed.success) return parsed.data;
if (attempt >= MAX_ATTEMPTS) {
throw new ModelOutputError(parsed.error, response, attempt);
}
// The error travels with the call, not in module state: two concurrent requests
// must never see each other's validation failures.
const issues = formatZodIssues(parsed.error); // "bedrooms: must be <= 20, got 1450"
return extract(input, attempt + 1, issues);
}MAX_ATTEMPTS is 2. I have tried 3 and it bought nothing. A model that has failed the same schema twice on the same input is almost always failing because the input does not contain what the schema wants, and no number of retries puts it there.
The retry is a full call at full price. Input tokens, the schema, the system prompt, all billed again, plus the error message. If your validation fails five percent of the time and you retry once, your cost per answer is up five percent before you have shipped anything. I worked through that arithmetic for a different feature in what a RAG answer costs, and the retry line was one of the ones nobody had budgeted.
Log the retry rate per field. When one field dominates the failures, the fix is in the prompt or the schema, not in retrying harder. Put a sentence like "never an area" into the tool description and, in my experience, the retry rate for that field drops to zero and stays there.
When to fail loudly
This is the part I think most code gets wrong, and it gets it wrong in the quiet direction.
The temptation when a field fails validation is to default it. Bedrooms came back wrong, store null, move on. The request succeeds, the user sees a listing, nobody is paged. It feels robust.
It is robust in the sense that a smoke detector with the battery out is quiet.
Think about how the 1,450 bug would have gone with a silent default. No ticket, because the listing would have shown no bedroom count at all, which is common enough that nobody files a bug about it. The extraction would have reported success. The field would have been quietly null on every listing where the description led with its area, which is a lot of listings, and the first person to notice would have been whoever ran the quarterly report on bedroom distribution and found a hole in it.
My rule is per field, decided when the schema is written. A field is either optional with a default, or required and fatal. There is no third category where a required field silently becomes a default because the model had a bad day.
Fields that may default: the summary, a tag list, anything a human will read and shrug at if it is missing. Mark them .optional() or .catch(fallback) in the schema, visibly, so the decision is in the code and not in somebody's head.
Fields that must fail: price, currency, the enum that drives business logic, anything that gets written to a database and read by code that trusts it. For these, a validation failure after retries is a failed request. Return an error, log the raw model output alongside the Zod issues, and let the caller decide. The one thing it must not do is succeed with a value nobody checked.
If I had to pick one side for a whole feature, I would pick loud. A feature that fails visibly one time in two hundred gets fixed. A feature that corrupts one record in two hundred gets discovered in a quarter's time, and by then there are four hundred bad rows and no raw outputs to explain them.
The part I am still not sure about
Everything above treats the model as untrusted input. That stance has held up, and it is the same stance I take in the production RAG chatbot, where the retrieval side has its own version of this problem.
What I do not have a good answer for yet is drift. A model version changes, the retry rate on one field goes from zero to three percent, and nothing is broken, exactly. The schema still catches it. The retries still fix it. The bill is three percent higher and the latency on that feature has a longer tail, and no alert fires because no request failed.
The thing I am leaning towards is treating validation-failure rate per field as a metric with a threshold, the same as error rate, so a model change that degrades the output quietly shows up as a line going the wrong way. I have not run that long enough to say whether the thresholds are tunable or just noise.
A ticket like the bedrooms one gets closed with an UPDATE statement, as these things are. The feature behind it keeps running. With the schema above in place it does not ship a 1,450 again, and when it tries, you get an error instead of a ticket, which is the only kind of progress this work offers.