Rana Maninder Singh
Lesson 4 of 8Generative AI

Structured Outputs — JSON the App Can Parse

Lesson opener

In one line: Why free-form prose breaks product code.

Why it matters: Programs need stable fields, not vibes.

Before this lesson: Calling an LLM API

Before you start

ResourceLink
PreviousCalling an LLM API
NextEmbeddings for search
PrerequisitesCalling an LLM API
Time~50 minutes

What you will learn

  • Why free-form prose breaks product code
  • Asking for JSON and validating it with json + a schema mindset
  • Runnable local validators and repair checks you can reuse before calling any API

Pinned libraries

pip install -r docs/genai/requirements.txt

Pinned in docs/genai/requirements.txt:

openai>=1.40.0,<2
scikit-learn==1.5.2
numpy==2.1.3

Offline validators use the standard library only. Optional JSON-mode API calls need openai>=1.40.0,<2 and # requires: api-key. Model names below are as of September 2026, check the pricing page / model docs.


The problem with free text

A Pune ops bot asks the model: "Is this ticket urgent?"

Model replies: "I'd say it's fairly urgent, yes 🙂"

Your if response == "urgent" check fails. The UI shows nothing.

WHY Programs need stable fields, not vibes.

WHEN Routing, tagging, extracting amounts, filling forms.

Indian workplace tickets often mix English and local context ("UPI", "GSTIN", city names). Free prose drifts; a JSON contract stays testable in CI.

WHY Downstream routers, dashboards, and CRM fields need booleans and enums — not emoji.

WHEN Ticket triage, amount extraction, GST category tags, and any form the app must fill without a human retyping.

A Noida payments lead once wired if "urgent" in reply.lower() and celebrated for a day. Then the model wrote "Not urgent — customer already refunded." The substring still matched. Contracts beat substring hope.


Contract first

Define the shape before calling the model:

import json

SCHEMA_KEYS = {"urgent", "category", "reason"}


def validate_ticket_label(raw: str) -> dict:
    data = json.loads(raw)
    missing = SCHEMA_KEYS - set(data)
    if missing:
        raise ValueError(f"missing keys: {sorted(missing)}")
    extra = set(data) - SCHEMA_KEYS
    if extra:
        raise ValueError(f"unexpected keys: {sorted(extra)}")
    if not isinstance(data["urgent"], bool):
        raise TypeError("urgent must be bool")
    if not isinstance(data["category"], str) or not data["category"]:
        raise TypeError("category must be non-empty str")
    if not isinstance(data["reason"], str) or not data["reason"]:
        raise TypeError("reason must be non-empty str")
    return data


sample = '{"urgent": true, "category": "payments", "reason": "UPI debit no credit"}'
print(validate_ticket_label(sample))

Reject unexpected keys early. Models love inventing priority_score or emoji fields that your router never reads.

Keep the validator in the same repo as the prompt. When a Bengaluru PM asks for a new city field, change schema, prompt, and golden fixtures in one PR — otherwise staging looks green while production silently drops the city into a log line nobody queries.


Prompt pattern

Tell the model the exact JSON keys and forbid markdown fences:

Return ONLY a JSON object with keys:
  urgent (boolean), category (string), reason (string).
No markdown. No commentary.
Ticket: "Amount deducted via UPI but order still unpaid — Bangalore customer"

With the OpenAI SDK you can also use structured / JSON mode features documented for your model — always validate on receipt.

# requires: api-key
import os
import sys
import json
from openai import OpenAI

api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
    print("Set OPENAI_API_KEY; never hard-code keys.", file=sys.stderr)
    sys.exit(1)

client = OpenAI(api_key=api_key)
try:
    resp = client.chat.completions.create(
        # Model as of September 2026, check the pricing page / model list
        model="gpt-4o-mini",
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": "Return JSON keys: urgent, category, reason."},
            {"role": "user", "content": "Ticket: UPI deducted, order unpaid, Bangalore."},
        ],
        temperature=0,
    )
except Exception as exc:
    print(f"API call failed: {type(exc).__name__}: {exc}", file=sys.stderr)
    sys.exit(1)

data = json.loads(resp.choices[0].message.content)
print(data.get("category"), data.get("urgent"))

[!important] json_object mode still needs your schema check — models can omit keys or invent types.


Offline demo — strip markdown fences before parse

Models often wrap JSON in markdown code fences (a json info string on the opening fence) even when you forbid them. Strip those fences locally before json.loads.

# Offline demo: strip markdown fences then parse JSON
import json
import re

fence = chr(96) * 3  # backticks, so this lesson fence stays intact
FENCE_RE = re.compile(rf"^{re.escape(fence)}(?:json)?\s*|\s*{re.escape(fence)}$", re.I)


def loads_maybe_fenced(raw: str) -> dict:
    text = raw.strip()
    if text.startswith(fence):
        text = FENCE_RE.sub("", text).strip()
    return json.loads(text)


messy = (
    fence
    + "json\n"
    + '{"urgent": false, "category": "it", "reason": "VPN down in Noida"}\n'
    + fence
)
print(loads_maybe_fenced(messy))

Offline demo — batch-validate a golden fixture file shape

Keep a few hand-written JSON strings in CI. Fail the build if any fixture breaks the contract.

# Offline demo: score a small golden set of model-shaped JSON strings
import json

SCHEMA_KEYS = {"urgent", "category", "reason"}


def ok(raw: str) -> bool:
    try:
        data = json.loads(raw)
    except json.JSONDecodeError:
        return False
    if set(data) != SCHEMA_KEYS:
        return False
    return isinstance(data["urgent"], bool) and isinstance(data["category"], str)


fixtures = [
    '{"urgent": true, "category": "payments", "reason": "UPI mismatch"}',
    '{"urgent": "yes", "category": "payments", "reason": "bad type"}',
    '{"urgent": false, "category": "it"}',
]
results = [ok(f) for f in fixtures]
print(results, "pass_rate", sum(results) / len(results))
assert results == [True, False, False]

Wire this checker after every prompt or model change. Structured outputs without tests are just hopeful prose with braces.


Workplace patterns that break parsers

Support routers in Pune and Bengaluru fail in predictable ways. The model adds a trailing period inside a string. It returns an array when you asked for an object. It lowercases true as the string "true". It wraps the object in a sentence: Sure! {"urgent": true, ...}. Each failure is cheap to catch with json.loads plus your schema check, and expensive to debug if you only log the raw chat reply.

Keep temperature at 0 for labelling jobs. Keep the system message short and contractual. Prefer JSON mode / structured outputs when your model documents them, then still run validate_ticket_label. Provider features reduce formatting drift; they do not replace type checks. When you add a new field (city, channel), update the schema, the prompt, and the golden fixtures in the same pull request so CI fails if any layer drifts.

If the model keeps emitting fences, strip them with the offline helper above before parse. If it keeps inventing keys, reject extras. If it keeps wrong types, fail the job and escalate to a human label — do not silently coerce "yes" into True unless product explicitly owns that mapping and tests it.

Cost note: retries on bad JSON spend tokens twice. Measure how often validation fails after a prompt change. Example model ids and rates remain as of September 2026, check the pricing page before you turn retry storms into a budget line.

Failure modes — structured labelling in Indian ops

Failure modeTypical symptomFix
Substring routing"not urgent" still matches "urgent"Require JSON + bool field
Invented keysRouter ignores priority_scoreReject extras in the validator
Stringly bools"true" / "yes" slip throughType-check; fail loud
Leading chatterSure! { ... }Strip fences; require object-only prompt
Schema driftPrompt has city, CI fixtures do notOne PR for prompt + schema + goldens

WHY Ops dashboards and CRM updates are code paths — they cannot wait for a human to interpret vibes.

WHEN Any auto-tag, auto-route, or auto-fill job that touches payments, GST, or refund queues.

If validation fails more than a few percent after a model or prompt change, stop widening retries. Fix the contract. Silent coercion of "yes" → True belongs only in product-owned adapters with tests — never as a hidden default in the shared validator.

Offline demo — coerce only with an explicit adapter

Product may own a narrow "yes"/"no" → bool map. Keep it outside the strict validator and unit-test both paths.

# Offline demo: explicit yes/no adapter separate from strict schema validation
def coerce_yes_no(value: object) -> bool:
    if isinstance(value, bool):
        return value
    if isinstance(value, str) and value.strip().lower() in {"yes", "y", "true"}:
        return True
    if isinstance(value, str) and value.strip().lower() in {"no", "n", "false"}:
        return False
    raise TypeError(f"cannot coerce {value!r} to bool")


assert coerce_yes_no(True) is True
assert coerce_yes_no("yes") is True
assert coerce_yes_no("NO") is False
try:
    coerce_yes_no("urgent")
    raise AssertionError("expected TypeError")
except TypeError:
    pass
print("adapter ok")

Offline demo — extract the first JSON object from chatter

When the model prefixes Sure!, slice from the first { to the last } before json.loads.

# Offline demo: extract a JSON object buried in leading chatter
import json


def extract_json_object(raw: str) -> dict:
    start = raw.find("{")
    end = raw.rfind("}")
    if start < 0 or end <= start:
        raise ValueError("no JSON object found")
    return json.loads(raw[start : end + 1])


messy = 'Sure! {"urgent": true, "category": "payments", "reason": "UPI mismatch"} Thanks.'
data = extract_json_object(messy)
assert data["urgent"] is True
assert data["category"] == "payments"
print(data)

Verified against openai 1.40.0,<2, scikit-learn 1.5.2, numpy 2.1.3 documentation, September 2026.

Test yourself

  1. Why does comparing to the string "urgent" fail on conversational answers?
  2. What does validate_ticket_label raise on missing keys?
  3. Name three keys in the sample schema.
  4. What does response_format={"type": "json_object"} request?
  5. True or false: JSON mode removes the need to validate.
  6. Why set temperature=0 for labelling?
  7. What should the prompt say about markdown fences?
  8. Which Python type should urgent be?
  9. Where is validation done — before or after json.loads for type checks?
  10. True or false: structured outputs are only useful for chat UIs.