Close Menu
AI News TodayAI News Today

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Best AI Tools Review 2027: The Ones I’d Actually Pay For

    What Is AGI? The Plain-English Answer Behind the Hype

    Artificial Intelligence Classes: What You’ll Actually Learn, Hour by Hour

    Facebook X (Twitter) Instagram
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram Pinterest Vimeo
    AI News TodayAI News Today
    • Home
    • AI News
    • AI Reviews
    • AI Tools
    • AI Tutorials
    • Chatbots
    • AGI
    • Artificial Intelligence
    AI News TodayAI News Today
    Home»AI Tools»Your LLM Can Return Perfect JSON and Still Be Wrong
    AI Tools

    Your LLM Can Return Perfect JSON and Still Be Wrong

    By No Comments9 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Your LLM Can Return Perfect JSON and Still Be Wrong
    Share
    Facebook Twitter LinkedIn Pinterest Email

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

    import loggingfrom datetime import datefrom pydantic import BaseModelfrom openai import OpenAIlogger = logging.getLogger(__name__)client = OpenAI()class Transaction(BaseModel):    sender: str    amount: float    transaction_id: str    transaction_date: datedocument = """Payment received from Chinedu.Amount: ₦45,000Reference: TXN-82K91Date: 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.parsedlogger.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:

    document = """Payment received from Chinedu.Amount: ₦45,000Reference: 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:

    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:

    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.

    from pydantic import Fieldclass 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:

    from pydantic import model_validator, ValidationErrorclass 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:

    MAX_RETRIES = 2def 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.

    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.

    JSON LLM perfect return Wrong
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleDebian won’t ban AI code from its Linux distribution
    Next Article Think twice before installing this device promising free movies
    • Website

    Related Posts

    AI Tools

    New AI Tools: What Survived a Month of Real Use (And What Didn’t)

    AI Tools

    The Top AI Tools in 2026: What’s Actually Worth Paying For

    AI Tools

    AI Tools Online: How to Build a Stack That Actually Saves You Time

    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Best AI Tools Review 2027: The Ones I’d Actually Pay For

    1 Views

    What Is AGI? The Plain-English Answer Behind the Hype

    1 Views

    Artificial Intelligence Classes: What You’ll Actually Learn, Hour by Hour

    1 Views
    Stay In Touch
    • Facebook
    • YouTube
    • TikTok
    • WhatsApp
    • Twitter
    • Instagram
    Latest Reviews
    AI Tutorials

    Quantization from the ground up

    AI Tools

    David Sacks is done as AI czar — here’s what he’s doing instead

    AI Reviews

    Judge sides with Anthropic to temporarily block the Pentagon’s ban

    Subscribe to Updates

    Get the latest tech news from FooBar about tech, design and biz.

    Most Popular

    Best AI Tools Review 2027: The Ones I’d Actually Pay For

    1 Views

    What Is AGI? The Plain-English Answer Behind the Hype

    1 Views

    Artificial Intelligence Classes: What You’ll Actually Learn, Hour by Hour

    1 Views
    Our Picks

    Quantization from the ground up

    David Sacks is done as AI czar — here’s what he’s doing instead

    Judge sides with Anthropic to temporarily block the Pentagon’s ban

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    Facebook X (Twitter) Instagram Pinterest
    • About Us
    • Contact Us
    • Terms & Conditions
    • Privacy Policy
    • Disclaimer

    © 2026 ainewstoday.co. All rights reserved. Designed by DD.

    Type above and press Enter to search. Press Esc to cancel.