AI Foundations for Developers COURSE·LESSON 26 OF 410 completed

Structured Output and Validation

Syntax and meaning are separate contracts

A model can return syntactically valid JSON with the wrong values. Structured-output or constrained-decoding features can improve format compliance, but your application must still validate types, ranges, allowed values, and relationships.

Suppose a request extractor should return a category, an urgency flag, and source text. A schema can require known categories and boolean urgency. It cannot by itself establish whether the ticket actually describes an emergency.

json
{
  "category": "billing",
  "urgent": false,
  "evidence": "My payment was charged twice."
}

A small runnable validation boundary

python
import json

def validate(raw):
    obj = json.loads(raw)
    if not isinstance(obj, dict):
        raise ValueError("Expected an object")
    if set(obj) != {"category", "urgent", "evidence"}:
        raise ValueError("Unexpected or missing keys")
    if obj["category"] not in {"billing", "account", "bug"}:
        raise ValueError("Unknown category")
    if not isinstance(obj["urgent"], bool):
        raise ValueError("Urgent must be boolean")
    if not isinstance(obj["evidence"], str) or not obj["evidence"].strip():
        raise ValueError("Evidence is required")
    return obj

print(validate('{"category":"billing","urgent":false,"evidence":"charged twice"}'))

Run this in the Python compiler. Change false to "false": the JSON remains valid, but the type contract fails.

Handle failures deliberately

Distinguish invalid JSON, schema mismatch, truncation, refusal, unsupported claims, and transport errors. A bounded repair attempt may fix formatting; it should not fabricate missing business facts. After a small retry budget, abstain or send the case for review.

Preserve the raw candidate for controlled diagnosis when permitted, but never treat it as executable code. Escape text for its display context; parameterize database queries; avoid interpolating model strings into shell commands. A validated string is still untrusted content.

Enums, length limits, nullable fields, and explicit unknown states improve contracts. Avoid forcing a guessed date merely because a schema requires a date. Use a nullable value plus a reason when the input does not contain the fact.

Checkpoint with answers

Does JSON mode prove semantic correctness? No. It concerns format behavior, not truth.

Exercise: A schema-valid object says urgency is false for “my account was stolen.” What failed? Answer: semantic classification, not parsing. Add such examples to evaluation and review routing.

Why reject unknown fields? To keep the output contract predictable and prevent downstream consumers from accidentally acting on unexpected model-generated instructions.

Learn at your own pace0 / 41 lessons complete