"Validate, don't trust: handling structured LLM output in TypeScript and Python"
The model returned clean JSON every time in development, so you shipped. Then production sent it something weird. Structured-output modes guarantee the shape of a response, never the truth of it, here is the validation discipline that keeps model output from corrupting your system, in both TypeScript and Python.

There is a specific kind of bug that only appears after you ship an LLM feature. In development the model returned clean JSON every time, the demo worked, and the integration looked finished. Three weeks into production, an unusual input comes through, the model returns the amount as the string "twelve thousand" instead of a number, your parser throws, and the job dies quietly in a queue nobody is watching. Or worse, it doesn't throw, and the bad value lands in your database.
The mental shift that fixes this is simple to state, and it is the first rule I give the developers I mentor when they wire up their first model call: LLM output is user input. Not "output from my system", input from an untrusted source. You would never take a form submission from the public internet and write it straight into your database. A model response deserves exactly the same suspicion, because a model is a probabilistic text generator sitting outside your trust boundary. It will usually give you what you asked for. "Usually" is not an engineering guarantee.
The discipline starts with schema-first design. Before you write the prompt, define the shape of the data you need, field names, types, which fields are optional, what the enums are. The schema is the contract; the prompt is just one way of asking the model to fulfil it. In TypeScript I use Zod for this, and specifically safeParse rather than parse, because I want a result object I can branch on rather than an exception ambushing me somewhere up the stack. In Python I use Pydantic models and catch the ValidationError explicitly. I work in both stacks and the pattern is identical, the syntax changes, the discipline doesn't.

The obvious objection is that the platforms have already solved this. The major providers now offer structured-output modes built on constrained decoding: your JSON schema is compiled into a grammar and the model is prevented, token by token, from emitting anything that violates it. Use them, they eliminate the malformed-JSON class of failure outright, including my "twelve thousand" example. But they guarantee shape, not truth. A response can conform perfectly to your schema and still carry a fabricated value in every field. Constrained decoding moved the problem; it did not remove it.
This is where most integrations stop too early. A syntactically valid email address can still be plainly invented, the model helpfully supplying john.smith@example.com because the document didn't contain one. A date can parse cleanly and still sit in the wrong century, because the model read "03/04/25" with the wrong convention. Line items can each be valid numbers and still not sum to the stated total. These are semantic failures, and you catch them with custom validators layered onto the schema: refinements in Zod, field and model validators in Pydantic. Every one of these checks encodes a fact about your domain that the model does not reliably know.
When validation fails, you don't have to give up, you get to use the failure. The retry-on-invalid loop is the single most useful pattern here: take the validation error, show it to the model verbatim alongside its previous attempt, and ask it to correct the output. "Field 'invoice_date' failed: year 1925 is outside the accepted range" is remarkably effective feedback. Models are good at fixing specific, named mistakes; they are bad at being right first time on messy input. Libraries like Instructor have built their whole premise on this re-ask loop, and it is perhaps twenty lines to write by hand.
The critical word in that loop is bounded. Two or three attempts, then stop. An unbounded retry loop is a latency problem, a cost problem, and occasionally an infinite one, some inputs will simply never validate, because the information genuinely isn't there, and the model will keep confabulating new wrong answers for as long as you let it.
Which raises the question of what happens at the cap. The answer is: fail closed. The record goes to an error state or a human review queue with the raw output and the validation errors attached. What must never happen is the tempting fallback, "we tried three times, just take the last attempt". If it didn't validate, it isn't data. A visible failure that a person resolves in two minutes is vastly cheaper than a silent corruption you discover during an audit.
The last rule ties it together: unvalidated model output never touches downstream state. Not the database, not the next API call, not the message queue, not even a log line that another system parses. The validated, typed object is the only artefact the rest of your system is allowed to see. If you hold that line, the blast radius of a bad model response is one rejected record, not a cascade.
None of this is exotic. It is the same input-validation discipline the industry learned decades ago, applied to a new and unusually confident source of input. If you want a working reference for the Python side, my repo at github.com/afareed007/docextract implements the full pattern in a document-extraction service: Pydantic schemas, semantic validators, a bounded re-ask loop that feeds errors back to the model, and a fail-closed path to human review when the attempts run out. And if you're wiring a model into a system where the output actually matters, this is exactly the kind of work I do, designing LLM integrations that hold up in production, not just in the demo. Get in touch via the contact form.
Senior engineering roles — or production AI consulting?
I'm open to senior AI and software engineering roles and to selective consulting on agents, RAG, and LLM automation in production. If this post resonates — as a hiring manager or as someone shipping similar work — get in touch.
Get in touch