Your LLM Can Return Perfect JSON and Still Be Wrong

Your LLM Can Return Perfect JSON and Still Be Wrong

Three weeks after I turned on Structured Outputs for a pipeline that parsed payment confirmation messages into transaction records, I noticed that our reconciliation job started flagging a small, steady stream of mismatches.They were not crashes, and not malformed rows either. Just transactions where the amount and sender matched perfectly but the date was off. Something like 2 to 3% of a given week's volume, enough to notice, not enough to be obvious right away.At first I assumed that it was a timezone bug. But it wasn't. When I pulled the raw source messages next to the extracted records, a pattern showed up: every mismatched transaction came from a message that never mentioned a date at all. Something like "Payment received from Chinedu, ₦45,000, ref TXN-82K91." No date anywhere in the text. And the model had filled transaction_date in anyway, almost always the date the extraction job ran, off by less than an hour.The schema said transaction_date: date, required. The model couldn't return nothing. So it didn't.I'd been treating "the JSON is valid" as the finish line for this pipeline, and for weeks it looked like one. It isn't. It's the point where a quieter kind of failure becomes possible, one that never throws an error or fails a type check, and doesn't show up until something downstream depends on the value being real. Most of what gets written about Structured Outputs stops at "it can't return broken JSON anymore," as if that settles the reliability question. It settles one version of it.The trap of the perfect schemaStructured Outputs solve a real problem. Before native schema enforcement, getting reliable JSON out of an LLM meant regex parsers, retry loops, and prompts that basically begged the model: "ONLY output JSON, no markdown, no preamble." With the modern OpenAI Python SDK and a Pydantic model, most of that category of pain just goes away:Run it against a clean message and it works exactly as advertised. Every key present, every type correct, no try/except needed just to catch a stray markdown fence around the JSON.Then someone forwards you a message like this one:but the schema doesn't care that the date isn't there. It's still marked required, so something has to fill that slot, and it's never going to be the schema that bends. The model reaches for whatever gets it to a valid value instead: the current date, the training cutoff, a plausible-looking guess. What comes back type-checks perfectly. It's also completely made up, and there's nothing in the response itself that tells you which fields are which.Designing schemas for uncertaintyThe fix is a mental shift more than a code change. An empty field isn't an error in extraction, it's often just the truth. Making fields nullable takes the pressure off the model to invent something:Now if the date's missing, the model can just say so. This also brings a distinction that's easy to blur, which is extraction versus inference. Extraction is "tell me exactly what's in the text." While inference is "tell me what it implies." A message that says "paid on Tuesday" and a schema demanding an ISO date, that's inference, whether you meant to ask for it or not. Sometimes inference is exactly what you want, but the decision should be yours, not something the model makes for you by default. A nullable field hands that decision back to your own code:Evidence and provenanceNullable fields fix the "inventing values from nothing" problem. They don't fix the other one, which is honestly worse: the model gives you a value, and you have no way to tell if it actually read that value off the page or pattern-matched its way there.With a normal chat response you can at least watch it reason its way to an answer. Structured Outputs skip straight to the final form. So I started asking for a second field alongside every value, the exact chunk of source text that supposedly backs it up.The generic Extracted wrapper is a shortcut, not a best practice. value is now a union type instead of a clean float, which costs some of the type safety the original schema had. That trade is worth it once a schema has more than a couple of field types, writing ExtractedFloat, ExtractedDate, ExtractedString separately is just busywork at that point. For one or two fields, keep the specific classes, they're usually cleaner.The pattern earns its keep two ways. Ordering evidence before value matters because keys generate in sequence, so the model has to write down what it's looking at before committing to an answer, a small forced show-your-work. And it gives a reviewer something concrete to check without re-reading the source. If value is filled in but evidence is empty, or contains text that isn't in the source anywhere, that mismatch is the hallucination showing up in the data itself.It doesn't come free. On a batch of a few hundred transaction messages, adding evidence fields across the schema pushed output tokens up by roughly a third, and latency rose enough to matter at pipeline scale.Not worth it for a five-digit zip code. But for a financial figure someone's going to act on, it's definitely worth it.The boundary between generation and validationBy this point the schema is carrying a lot: nullable types so it doesn't invent things, evidence fields so I can catch it when it does anyway. But there's a whole category of wrongness neither of those touches, which is whether the value makes any sense as a fact about the world.The schema guarantees amount is a float. It says nothing about whether that float is negative, or whether transaction_date is somehow three days from now. Early on I tried fixing this in the prompt, with instructions like "the amount must be greater than zero," which in hindsight was a strange thing to ask a language model to enforce. It's not a calculator. A validator does this exactly right, every single time, for free:So now the API is guaranteeing structure the moment it generates the response, and Pydantic is guaranteeing the data makes sense the moment it's parsed into the object, the same way every time, no LLM involved in that second check at all. When the validator throws, you've got options: kick the record to a human, or hand the exact error back to the model and let it try again. I went with the second one, capped hard at two retries:The MAX_RETRIES cap actually matters more than it looks. My first instinct was to let it keep trying, which is a mistake. Two failed attempts almost always means the source document is the actual problem, not the prompt, and a third automated pass just burns API calls on something a human clears in ten seconds.None of this is OpenAI-specific either, even though every code block here is. Swap in Anthropic's tool use or a self-hosted setup with vLLM and Outlines and the Pydantic model doesn't move an inch, it's just the API call around it that changes.When I first got this working, my bar for success was embarrassingly low: did the model fill out the object without breaking my parser. Looking back, that bar rewards the wrong thing entirely, because a model that eagerly fills every field regardless of what's actually in front of it isn't reliable. It's just confident, which is a different and more dangerous thing.Structured Outputs are genuinely good at what they do. They just don't do the thing I originally thought they did. They guarantee shape, not truth, and once you stop worrying about brackets and quote escaping, the real question is still sitting there waiting: does every value in this object have an actual reason to exist?That question was always the hard part. The schema just used to hide it from me.

Original Source

Read the full article at Towardsdatascience →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.