DEV Community

BigOSlate
BigOSlate

Posted on Originally published at bigoslate.com

JSON Mode vs Constrained Decoding: How Pydantic & Zod Make Invalid LLM JSON Impossible

Every engineer building an AI feature hits the same wall on week one: you prompt the model "Respond ONLY in valid JSON matching this schema", and 98% of calls succeed—until the 2% in production outputs:

  • Markdown fences (json ...) around the payload
  • A hallucinated enum value ("severity": "super_urgent" instead of "critical")
  • A truncated JSON object when max_tokens cuts off mid-string

Here is the difference between Prompted JSON, Legacy JSON Mode, and Constrained Decoding (Structured Outputs).


Why Legacy "JSON Mode" Still Breaks Your Backend

Legacy JSON mode (response_format={"type": "json_object"}) only guarantees syntactically parseable JSON—json.loads() won't crash, but none of your field names, types, or enums are enforced! The model can legally return {"oops": "wrong keys"} and JSON mode considers that a success.


How Constrained Decoding Works at the Logit Level

Modern Structured Outputs compile your Pydantic (Python) or Zod (TypeScript) schema into a Finite-State Automaton / Context-Free Grammar (CFG).

At every single token generation step, the inference engine checks which tokens in the 200,000-token vocabulary are legal next characters at the current cursor position—and sets the logit of every illegal token to -∞ (probability = 0.0) before sampling!

Partial Output So Far:  {"severity": "
Schema Enum Allowed:    ["low", "medium", "high", "critical"]

Token Vocabulary Mask at This Step:
  ✅ 'high"'     -> kept (76.4%)
  ✅ 'critical"' -> kept (19.1%)
  ❌ 'urgent"'   -> logit = -∞ (0.0% — mathematically impossible!)
  ❌ 'Sure!'     -> logit = -∞ (0.0%)
Enter fullscreen mode Exit fullscreen mode

Production Pattern: Put reasoning BEFORE verdict Fields!

Because LLMs generate tokens strictly left-to-right, field order in your Pydantic model directly affects accuracy! If verdict is the first key in your schema, the model is forced to guess on token #4 and spend the rest of the JSON rationalizing its guess.

from typing import Literal
from pydantic import BaseModel
from openai import OpenAI

class TicketTriage(BaseModel):
    # 1. Generate reasoning FIRST so attention attends to it!
    step_by_step_reasoning: str
    # 2. Commit to enum & boolean AFTER reasoning
    severity: Literal["low", "medium", "high", "critical"]
    requires_human_escalation: bool

client = OpenAI()
resp = client.responses.parse(
    model="gpt-4o-mini",
    input=" Prod DB CPU is at 99% and checkout 504s started 3 mins ago.",
    text_format=TicketTriage,
)
triage: TicketTriage = resp.output_parsed
Enter fullscreen mode Exit fullscreen mode

Explore a Live Grammar Token-Mask Simulator

Want to click through each decode step and watch illegal vocabulary tokens get masked to -∞ in real time?

👉 Try the Interactive Constrained Decoding Lab (with OpenAI, Gemini & Claude SDK tabs) on BigOSlate

Top comments (0)