保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Large Language Models

Your LLM Can Return Perfect JSON and Still Be Wrong

What I learned after thinking more carefully about Structured Outputs on messy, incomplete data Benjamin Nweke August 31, 20268 min read Photo by Şahin Sezer Dinçer via Pexels 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. Learn this step by step with the interactive AI Engineer roadmap.

The trap of the perfect schema

Structured 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: python

import logging
from datetime import date
from pydantic import BaseModel
from openai import OpenAI

logger = logging.getLogger(__name__)
client = OpenAI()

class Transaction(BaseModel):
    sender: str
    amount: float
    transaction_id: str
    transaction_date: date

document = """
Payment received from Chinedu.
Amount: ₦45,000
Reference: TXN-82K91
Date: 11 August 2026
"""

# gpt-4o-mini kept merging the amount and reference into one field on
# messages with unusual formatting, so this stays on the full model
# despite the cost. Worth revisiting once mini catches up.
completion = client.beta.chat.completions.parse(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "Extract the transaction details."},
        {"role": "user", "content": document},
    ],
    response_format=Transaction,
)

txn = completion.choices[0].message.parsed
logger.info("parsed txn %s", txn.transaction_id)

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: python

document = """
Payment received from Chinedu.
Amount: ₦45,000
Reference: TXN-82K91
"""
# No date in 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 uncertainty

The 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: python

class Transaction(BaseModel):
    sender: str | None
    amount: float | None
    transaction_id: str | None
    transaction_date: date | None

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: python

if transaction.transaction_date is None:
    request_missing_info(transaction_id=transaction.transaction_id)

Evidence and provenance

Nullable 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. python

from pydantic import Field

class Extracted(BaseModel):
    """Generic wrapper so I'm not writing a near-identical class per field type."""
    value: float | date | str | None
    evidence: str | None = Field(description="exact quote backing this value, empty if not found")

class Transaction(BaseModel):
    sender: str | None
    amount: Extracted
    transaction_id: str | None
    transaction_date: Extracted

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 validation

By 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: python

from pydantic import model_validator, ValidationError

class Transaction(BaseModel):
    sender: str | None
    amount: float | None
    transaction_id: str | None
    transaction_date: date | None

    @model_validator(mode="after")
    def check_sane_values(self) -> "Transaction":
        # negative amounts have shown up exactly twice, both times because
        # the source message described a refund, not a payment
        if self.amount is not None and self.amount <= 0:
            raise ValueError(f"amount must be positive, got {self.amount}")
        if self.transaction_date is not None and self.transaction_date > date.today():
            raise ValueError(f"transaction_date {self.transaction_date} is in the future")
        return self

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: python

MAX_RETRIES = 2

def extract_with_retry(document: str) -> Transaction:
    history = [
        {"role": "system", "content": "Extract the transaction details."},
        {"role": "user", "content": document},
    ]
    for attempt in range(MAX_RETRIES + 1):
        completion = client.beta.chat.completions.parse(
            model="gpt-4o", messages=history, response_format=Transaction
        )
        raw = completion.choices[0].message.content
        try:
            return Transaction.model_validate_json(raw)
        except ValidationError as e:
            if attempt == MAX_RETRIES:
                raise  # give up, let the caller route this to a human
            logger.warning("validation failed on attempt %d: %s", attempt, e)
            history += [
                {"role": "assistant", "content": raw},
                {"role": "user", "content": f"That failed validation: {e}. Fix only the bad field."},
            ]

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.

Rethinking the goal of extraction

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.

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Benjamin Nweke

Benjamin Nweke is a Computer Science graduate and technical writer exploring AI, machine learning, and data science. He writes about building reliable AI systems, model evaluation, agentic architectures, and the practical challenges that appear when machine learning moves beyond experiments. His work focuses on making technically complex ideas clear, useful, and grounded in real implementation. See all from Benjamin Nweke Data EngineeringJsonPydanticPythonStructured Output Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

A New Method to Detect "Confabulations" Hallucinated by Large Language Models

Artificial Intelligence By calculating semantic entropy with a second LLM, we can better flag answers as unreliable due to lack of knowledge Luciano Abriata June 25, 202410 min read

A Quick Way to Build Applications in Python

Artificial Intelligence Build MVPs with a few lines of code Naser Tamimi February 8, 20216 min read

How to Find the Best Multilingual Embedding Model for Your RAG

Artificial Intelligence Optimize the Embedding Space for Improving RAG Iulia Brezeanu January 27, 20248 min read

Hands-On Attention Mechanism for Time Series Classification, with Python

Machine Learning This is how to use the attention mechanism in a time series classification framework Piero Paialunga May 30, 20258 min read

Python Module for easy data pre-processing for beginners

Machine Learning There is a need to process these data quickly and create an initial model to better understand your dataset or the problem at hand. Benjamin Lau January 31, 20194 min read

Data Analytics with Python by Web scraping: Illustration with CIA World Factbook

Artificial Intelligence In this article, we show how to use Python libraries and HTML parsing to extract useful information from a website and build analytics. Tirthajyoti Sarkar March 4, 20189 min read

Time Series Are Not That Different for LLMs

Artificial Intelligence Harnessing the power of LLMs for time series modeling Henry Lai July 12, 20247 min read

Function Wrappers in Python

Programming Putting a Wrapper Around a Function Sadrach Pierre, Ph.D. May 5, 20205 min read

Chinese Postman in Python

Programming Detailed Implementation & Explanation, with special emphasis on unique approach to generate Odd Vertex Pairings using Recursion Araz Sharma November 9, 20201 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close