Validate AI JSON Output in Python: Schema, Business Rules and Safe Retries
Generative AI course · Build with Gen AI (APIs, RAG) · Estimated reading time: 18 minutes, plus the lab
Annapurna Tiffins gets about 300 customer messages every day. The owner wants each message tagged as late, quality, price, praise or other, so that urgent refund requests reach a person quickly. A developer asks an AI model to reply in JSON. On day one it works perfectly. On day three one reply starts with “Sure! Here is your JSON,” another says the urgency is “URGENT,” and a third contains an order number that the customer never wrote. The program either crashes or, worse, quietly saves wrong data. Today we will make the program check every reply before it trusts it.
In the structured output chapter we asked a chat app for JSON and tested it by hand. In the first API call chapter we sent a request from Python. This lesson connects the two. We will parse each reply strictly, check its shape against a schema, check the business rules that a schema cannot express, and retry a small, fixed number of times before handing the message to a person.
What you will learn in this chapter
- You will separate four kinds of failure: reply status, JSON syntax, schema shape and business meaning.
- You will write a small JSON Schema with required fields, allowed values and no extra fields.
- You will parse replies strictly in Python, rejecting prose, duplicate keys and non-finite numbers.
- You will add business rules, such as “the order number must appear in the customer's message.”
- You will build a bounded retry loop that does not retry refusals and ends in a human review queue.
Everything in this chapter is made up for learning
Synthetic classroom data only. Annapurna Tiffins, its customers, order numbers and every “model reply” on this page are fictional and hand typed. No AI model produced them. The offline lab uses only Python's standard library. It needs no API key, no downloads, no internet and no real customer data. A reply that passes every check can still be wrong in meaning, and this chapter shows you where that limit is.
1. Four different ways a JSON reply can fail
When a program asks a model for JSON, people often say “the JSON broke.” That sentence hides four separate questions. Each question needs its own check, and passing one does not mean passing the next.
| Layer | Question we ask | Example of a failure |
|---|---|---|
| Reply status | Did the model finish normally, or did it refuse or stop early? | The reply was cut off at the output limit, so the text ends in the middle of a word. |
| JSON syntax | Can a strict JSON parser read the text as one object? | The reply starts with “Sure! Here is your JSON,” or uses single quotes instead of double quotes. |
| Schema shape | Does the object have exactly the required fields, with the right types and allowed values? | The urgency is “URGENT” instead of low, medium or high, or refund_requested is the text "true" instead of the boolean true. |
| Business meaning | Does the data make sense for this message and for our rules? | The reply contains order number AT-9999, but the customer actually wrote AT-1042. |
Even after all four layers pass, one honest limit remains. The reply could tag a late-delivery complaint as a price complaint and still be perfectly valid. Checks catch broken and contradictory data. They do not prove that the model understood the customer. That is why we still test with an evaluation set and review samples, as shown in the evaluation chapter.
2. What provider structured output features promise today
Several AI providers now offer a structured output mode where you send a JSON Schema with the request. We opened the official documentation on 16 November 2026 (IST) to check what each feature actually promises. These are interface facts, not a ranking of providers.
- OpenAI's Structured Outputs guide says the feature constrains completed, non-refusal output to your supplied schema. It also says your application still needs to handle refusals, incomplete responses and API errors, and must validate business rules that the schema does not express. The guide describes an older JSON mode that produces valid JSON without schema adherence, and recommends Structured Outputs instead when possible.
- Anthropic's structured outputs documentation describes schema-constrained JSON for Claude. Its “Invalid outputs” section says that a reply can still fail to match the schema when the model refuses for safety reasons or when the reply hits the output token limit. It also lists schema keywords that are not supported, such as numeric limits and string length limits.
- Google's Gemini structured output documentation says the feature supports a subset of JSON Schema. It advises you to always validate values in your application, because output can be syntactically correct but semantically wrong. It also says some keywords, such as minLength and maxLength, are not enforced and are stripped from the request.
| Check | Provider feature can help | Your code must still do it |
|---|---|---|
| Valid JSON syntax for a completed reply | Yes, for completed, non-refused replies. | Yes, because refused or cut-off replies can still break, and a provider or SDK can change. |
| Required fields and allowed values | Yes, for the schema keywords that the provider supports. | Yes, for any keyword the provider ignores or strips, such as some length limits. |
| Refusals and cut-off replies | The provider reports them in the response. | Yes. Your code must read that status and decide what to do. |
| Business rules | No. A schema cannot know your customers or your rules. | Yes. This is always your job. |
| Correct meaning | No. | Partly. Use an evaluation set and human review for important decisions. |
The safe habit is simple. Use the provider's structured output mode when it is available, because it removes most syntax and shape errors. Then validate in your own code anyway, because your code is the last gate before your database, your customer or your refund system.
3. Write the schema before you write the prompt
A JSON Schema is a description of the data that you will accept. The current version of the specification is called 2020-12, published at json-schema.org. Our lab schema for one customer message looks like this:
{
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["late", "quality", "price", "praise", "other"]},
"urgency": {"type": "string", "enum": ["low", "medium", "high"]},
"summary": {"type": "string", "minLength": 5, "maxLength": 120},
"refund_requested": {"type": "boolean"},
"order_ref": {"type": ["string", "null"], "pattern": "^AT-[0-9]{4}$"}
},
"required": ["category", "urgency", "summary", "refund_requested", "order_ref"],
"additionalProperties": false
}
Read each part as a plain rule. The enum lists are the only allowed words, and they are case sensitive, so “Late” is not the same as “late.” The required list says every field must be present. Setting additionalProperties to false says that no surprise fields are allowed. The order number may be null when the customer did not write one, but if it is text, it must look like AT followed by four digits.
Notice that every field is required, and “no order number” is written as null rather than by leaving the field out. OpenAI's guide says that all fields must be required in its strict mode and suggests a type that also allows null when a value is optional. Anthropic's documentation says additionalProperties must be set to false for objects. This style also makes your own code simpler, because every reply has the same keys. Use clear field names and short descriptions, because the model reads them too.
4. Parse strictly: never guess and never use eval
The first gate turns reply text into a Python dictionary. It is tempting to “help” the program by cutting out the part between the first { and the last }, or by using eval. Both are bad ideas. Cutting text can hide a reply that was cut off or that contains two objects, and eval runs text as Python code, which is dangerous with any outside input.
Our lab uses json.loads from the standard library with two extra hooks that the Python json documentation describes. The object_pairs_hook lets us reject an object that repeats the same key, because Python would otherwise silently keep the last value. The parse_constant hook lets us reject NaN and Infinity, which Python accepts by default but which are not valid in standard JSON. We also reject empty text, very long text, a top-level list and text that is not a string.
| Reply text | Result | Reason |
|---|---|---|
| Sure! Here is your JSON: {"category": "late", ...} | Rejected | Extra words before the object are not JSON. |
| {'category': 'late'} | Rejected | JSON needs double quotes around keys and text. |
| {"urgency": "low", "urgency": "high"} | Rejected | The same key appears twice, so we cannot tell which value was meant. |
| {"category": "la | Rejected | The reply stops in the middle, usually because it hit the output limit. |
| [{"category": "late", ...}] | Rejected | We asked for one object, not a list. |
Ravindra Bagale's Tip
Treat a model reply like a form filled in by a stranger. You would not save a form without checking each box, so do not save a reply without checking each field. When a reply looks almost right, reject it and ask again instead of quietly fixing it yourself.
Ravindra Bagale's Tip – मराठी
AI चं उत्तर म्हणजे एखाद्या अनोळखी माणसाने भरलेला form आहे असं समजा. आपण प्रत्येक box तपासल्याशिवाय form save करत नाही, तसंच प्रत्येक field तपासल्याशिवाय उत्तर save करू नका. उत्तर “जवळजवळ बरोबर” दिसलं तरी ते स्वतः गुपचूप दुरुस्त करू नका; ते reject करा आणि पुन्हा विचारा.
Ravindra Bagale's Tip – हिंदी
AI के जवाब को किसी अनजान आदमी का भरा हुआ form समझो. हम हर box चेक किए बिना form save नहीं करते, वैसे ही हर field चेक किए बिना जवाब save मत करो. जवाब “लगभग सही” लगे तब भी उसे चुपचाप खुद ठीक मत करो; उसे reject करो और दोबारा पूछो.
5. Business rules that a schema cannot express
A schema checks each field on its own. It cannot compare one field with another, and it cannot look at the customer's original message. Those checks belong in your own code, after the schema check passes. Our lab adds four rules.
| Rule | Mistake it catches |
|---|---|
| If order_ref is not null, that exact order number must appear in the customer's message. | The model invents a believable order number such as AT-9999. |
| If the customer's message contains an order number, order_ref must not be null. | The model forgets an order number that the customer clearly wrote. |
| A praise message cannot request a refund. | Two fields contradict each other. |
| A praise message must have low urgency. | A thank-you message jumps to the top of the urgent queue. |
Real projects will have different rules. A bank form might require the amount to match the amount in the source document. A leave request might require the end date to be on or after the start date. Write each rule as one plain sentence first, then turn it into code and a test.
6. Retry safely: a small budget and a clear exit
When a reply fails a check, asking once more often fixes it, especially if we tell the model exactly what was wrong. But retries cost time and tokens, and an endless loop can burn money without helping. Our lab follows these steps for every message:
- Send the customer's message and the schema to the model.
- Read the reply status first. If the model refused, stop immediately and send the message to a person. Do not keep asking.
- If the reply was cut off, count it as a failed attempt and try again. In a real project, also check whether your output limit is too small or the input is too long.
- If the reply finished normally, run the strict parser, then the schema check, then the business rules.
- If every check passes, accept the data and stop.
- If any check fails, build a short repair note that lists only the problems, and try again with that note.
- After three attempts in total, stop and put the message in a human review queue with the last list of problems.
| Situation | Action | Outcome label |
|---|---|---|
| All checks pass. | Accept the data. | ok |
| Not valid JSON, wrong shape or broken business rule. | Retry with a repair note that lists the problems. | ok if a later attempt passes |
| Reply cut off or unknown status. | Retry and investigate limits. | ok if a later attempt passes |
| Model refused. | Do not retry. Send to a person. | refused |
| Still failing after the last attempt. | Stop. Send to a person with the errors. | needs_review |
The repair note never pastes the bad reply back into the prompt. It lists field problems in a fixed format and is capped at eight lines. This keeps the prompt short and avoids feeding strange text, such as an instruction hidden inside a reply, back into the next request. Read the prompt injection chapter to see why outside text should be treated as data.
One more rule matters more than all the others. Never take an action, such as issuing a refund or sending a message, until the reply has passed every check. Validation comes first, action comes after, and a person approves anything with money attached.
Ravindra Bagale's Tip
In interviews I ask freshers one question about AI features: “What happens on the third failure?” A good answer names a limit, a log and a person who reviews the case. A loop without an exit is not a feature; it is a bill waiting to arrive.
Ravindra Bagale's Tip – मराठी
Interview मध्ये मी freshers ना AI feature बद्दल एक प्रश्न विचारतो: “तिसऱ्यांदा fail झालं तर काय होणार?” चांगल्या उत्तरात एक limit, एक log आणि case तपासणारा एक माणूस असतो. ज्या loop ला exit नाही, ते feature नाही; ते येणारं bill आहे.
Ravindra Bagale's Tip – हिंदी
Interview में मैं freshers से AI feature के बारे में एक सवाल पूछता हूँ: “तीसरी बार fail हुआ तो क्या होगा?” अच्छे जवाब में एक limit, एक log और case देखने वाला एक इंसान होता है. जिस loop का exit नहीं, वो feature नहीं; वो आने वाला bill है.
7. Run the offline lab
Save the two files below in one folder. Use Python 3.9 or newer. No package installation is needed. Run python3 -B so_guard.py, then python3 -B -m unittest -v test_so_guard. You should see 44 tests pass. No internet and no API key are required. A small class called ScriptedModel plays the part of the AI model by returning hand-typed replies in order, so every run gives the same result.
Demo output (synthetic)
clean reply: ok after 1 attempt(s)
chatty reply, then fixed: ok after 2 attempt(s)
invented order number, then fixed: ok after 2 attempt(s)
cut off, then complete: ok after 2 attempt(s)
refusal: refused after 1 attempt(s)
never valid: needs_review after 3 attempt(s)
Test runner tail
Ran 44 tests in 0.002s
OK
Read the demo carefully. The chatty reply is rejected on the first attempt even though it contains good JSON, because our parser refuses to guess. The invented order number passes the schema but fails a business rule. The refusal ends after one attempt, and the reply that never becomes valid ends in the review queue after three attempts. The schema check in this file supports only a small teaching subset of JSON Schema. In a real project, use a maintained validator library or your SDK's typed models, and keep the business rules in your own code.
so_guard.py
"""Offline synthetic structured-output exercise. No AI, network, keys or private data.
A scripted fake model stands in for a real API. The guard parses strictly, checks a
small JSON Schema subset, checks business rules, and retries a bounded number of times.
Every message, order number and reply below is made up for learning.
"""
import json
import re
MAX_RAW_CHARS = 4000
MAX_ATTEMPTS = 3
CATEGORIES = ["late", "quality", "price", "praise", "other"]
URGENCY = ["low", "medium", "high"]
SCHEMA = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": CATEGORIES},
"urgency": {"type": "string", "enum": URGENCY},
"summary": {"type": "string", "minLength": 5, "maxLength": 120},
"refund_requested": {"type": "boolean"},
"order_ref": {"type": ["string", "null"], "pattern": r"^AT-[0-9]{4}$"},
},
"required": ["category", "urgency", "summary", "refund_requested", "order_ref"],
"additionalProperties": False,
}
class Rejected(ValueError):
"""Raised when a reply cannot be trusted as data."""
def _no_duplicates(pairs):
seen = {}
for key, value in pairs:
if key in seen:
raise Rejected("duplicate key: " + key)
seen[key] = value
return seen
def _no_constants(name):
raise Rejected("non-finite number: " + name)
def parse_strict(raw):
"""Turn reply text into a Python dict, or raise Rejected. Never uses eval."""
if not isinstance(raw, str):
raise Rejected("reply must be text")
if not raw.strip():
raise Rejected("empty reply")
if len(raw) > MAX_RAW_CHARS:
raise Rejected("reply too long")
try:
data = json.loads(raw, object_pairs_hook=_no_duplicates, parse_constant=_no_constants)
except Rejected:
raise
except (ValueError, RecursionError) as exc:
raise Rejected("not valid JSON: " + type(exc).__name__)
if not isinstance(data, dict):
raise Rejected("top level must be an object")
return data
_TYPES = {
"object": lambda v: isinstance(v, dict),
"string": lambda v: isinstance(v, str),
"boolean": lambda v: isinstance(v, bool),
"integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
"null": lambda v: v is None,
}
def schema_errors(data, schema=SCHEMA):
"""Return a list of readable problems. An empty list means the shape is right.
Supports only: type, enum, required, additionalProperties false,
minLength, maxLength and pattern. It is a teaching subset, not a full validator."""
errors = []
if not isinstance(data, dict):
return ["top level must be an object"]
props = schema["properties"]
for name in schema["required"]:
if name not in data:
errors.append(name + ": missing")
if schema.get("additionalProperties") is False:
for name in sorted(data):
if name not in props:
errors.append(name + ": unexpected field")
for name, rule in props.items():
if name not in data:
continue
value = data[name]
types = rule["type"] if isinstance(rule["type"], list) else [rule["type"]]
if not any(_TYPES[t](value) for t in types):
errors.append(name + ": wrong type, expected " + " or ".join(types))
continue
if value is None:
continue
if "enum" in rule and value not in rule["enum"]:
errors.append(name + ": must be one of " + ", ".join(rule["enum"]))
if isinstance(value, str):
if len(value) < rule.get("minLength", 0):
errors.append(name + ": too short")
if len(value) > rule.get("maxLength", 10 ** 9):
errors.append(name + ": too long")
if "pattern" in rule and not re.fullmatch(rule["pattern"], value):
errors.append(name + ": wrong format")
return errors
def rule_errors(data, message):
"""Business rules that a schema cannot express. Assumes the shape is already valid."""
errors = []
if data["category"] == "praise" and data["refund_requested"]:
errors.append("refund_requested: praise cannot request a refund")
if data["category"] == "praise" and data["urgency"] != "low":
errors.append("urgency: praise must be low urgency")
ref = data["order_ref"]
if ref is not None and ref not in message:
errors.append("order_ref: not present in the customer message")
if ref is None and re.search(r"AT-[0-9]{4}", message):
errors.append("order_ref: message contains an order number but reply has null")
return errors
def check(raw, message):
"""Return (data, errors). data is None when the text could not be parsed."""
try:
data = parse_strict(raw)
except Rejected as exc:
return None, [str(exc)]
errors = schema_errors(data)
if errors:
return data, errors
return data, rule_errors(data, message)
def repair_note(errors):
"""Short, fixed-format feedback for the next attempt. It lists problems only;
it never repeats the bad reply back, and it is capped in size."""
lines = ["Your previous reply was rejected. Fix only these problems:"]
lines += ["- " + e for e in errors[:8]]
lines.append("Reply with one JSON object that follows the schema. No extra text.")
return "\n".join(lines)
def run_with_retries(call_model, message, max_attempts=MAX_ATTEMPTS):
"""call_model(message, note) returns a dict like {"status": "completed", "text": "..."}.
Status may be "completed", "incomplete" or "refused". Returns a result dict with
outcome "ok", "needs_review" or "refused", the attempts used and the last errors."""
if not isinstance(max_attempts, int) or isinstance(max_attempts, bool) or not 1 <= max_attempts <= 5:
raise ValueError("max_attempts must be an integer from 1 to 5")
note = None
errors = []
for attempt in range(1, max_attempts + 1):
reply = call_model(message, note)
status = reply.get("status") if isinstance(reply, dict) else None
if status == "refused":
return {"outcome": "refused", "attempts": attempt, "data": None, "errors": ["model refused"]}
if status == "incomplete":
errors = ["reply was cut off before it finished"]
note = repair_note(errors)
continue
if status != "completed":
errors = ["unknown reply status"]
note = repair_note(errors)
continue
data, errors = check(reply.get("text"), message)
if not errors:
return {"outcome": "ok", "attempts": attempt, "data": data, "errors": []}
note = repair_note(errors)
return {"outcome": "needs_review", "attempts": max_attempts, "data": None, "errors": errors}
class ScriptedModel:
"""A fake model that returns pre-written replies in order. It records each note."""
def __init__(self, replies):
self.replies = list(replies)
self.notes = []
def __call__(self, message, note):
self.notes.append(note)
if not self.replies:
return {"status": "completed", "text": ""}
return self.replies.pop(0)
def done(obj_or_text):
text = obj_or_text if isinstance(obj_or_text, str) else json.dumps(obj_or_text)
return {"status": "completed", "text": text}
GOOD = {"category": "late", "urgency": "high", "summary": "Lunch arrived 50 minutes late.",
"refund_requested": True, "order_ref": "AT-1042"}
MESSAGE = "Order AT-1042 came 50 minutes late and the dal was cold. Please refund me."
if __name__ == "__main__":
demos = [
("clean reply", [done(GOOD)]),
("chatty reply, then fixed", ["Sure! Here is your JSON: " + json.dumps(GOOD), GOOD]),
("invented order number, then fixed", [dict(GOOD, order_ref="AT-9999"), GOOD]),
("cut off, then complete", [{"status": "incomplete", "text": '{"category": "la'}, GOOD]),
("refusal", [{"status": "refused", "text": ""}]),
("never valid", [dict(GOOD, urgency="URGENT")] * 3),
]
for name, script in demos:
script = [s if isinstance(s, dict) and "status" in s else done(s) for s in script]
result = run_with_retries(ScriptedModel(script), MESSAGE)
print(name + ":", result["outcome"], "after", result["attempts"], "attempt(s)")
test_so_guard.py
"""Tests for so_guard.py. Offline, synthetic, standard library only."""
import copy
import json
import unittest
from so_guard import (GOOD, MESSAGE, Rejected, ScriptedModel, check, done,
parse_strict, repair_note, rule_errors, run_with_retries,
schema_errors)
def good(**changes):
d = copy.deepcopy(GOOD)
d.update(changes)
return d
class ParseTests(unittest.TestCase):
def test_valid_object(self):
self.assertEqual(parse_strict(json.dumps(GOOD)), GOOD)
def test_prose_around_json_rejected(self):
self.assertRaises(Rejected, parse_strict, "Sure! " + json.dumps(GOOD))
def test_markdown_fence_rejected(self):
self.assertRaises(Rejected, parse_strict, "```json\n" + json.dumps(GOOD) + "\n```")
def test_empty_and_blank(self):
for bad in ("", " ", "\n"):
self.assertRaises(Rejected, parse_strict, bad)
def test_non_text_rejected(self):
for bad in (None, 42, b"{}", {"a": 1}):
self.assertRaises(Rejected, parse_strict, bad)
def test_top_level_array_rejected(self):
self.assertRaises(Rejected, parse_strict, "[" + json.dumps(GOOD) + "]")
def test_duplicate_keys_rejected(self):
self.assertRaises(Rejected, parse_strict, '{"urgency": "low", "urgency": "high"}')
def test_nan_and_infinity_rejected(self):
for c in ("NaN", "Infinity", "-Infinity"):
self.assertRaises(Rejected, parse_strict, '{"x": ' + c + '}')
def test_truncated_json_rejected(self):
self.assertRaises(Rejected, parse_strict, json.dumps(GOOD)[:-5])
def test_single_quotes_rejected(self):
self.assertRaises(Rejected, parse_strict, "{'category': 'late'}")
def test_too_long_rejected(self):
self.assertRaises(Rejected, parse_strict, '{"summary": "' + "x" * 5000 + '"}')
def test_deep_nesting_fails_closed(self):
self.assertRaises(Rejected, parse_strict, "[" * 1500 + "]" * 1500)
class SchemaTests(unittest.TestCase):
def test_good_has_no_errors(self):
self.assertEqual(schema_errors(GOOD), [])
def test_missing_field(self):
d = good(); del d["urgency"]
self.assertIn("urgency: missing", schema_errors(d))
def test_extra_field(self):
self.assertIn("mood: unexpected field", schema_errors(good(mood="angry")))
def test_enum_is_case_sensitive(self):
self.assertTrue(schema_errors(good(category="Late")))
def test_unknown_enum_value(self):
self.assertTrue(schema_errors(good(urgency="URGENT")))
def test_string_true_is_not_boolean(self):
self.assertTrue(schema_errors(good(refund_requested="true")))
def test_integer_one_is_not_boolean(self):
self.assertTrue(schema_errors(good(refund_requested=1)))
def test_null_allowed_only_where_declared(self):
self.assertEqual(schema_errors(good(order_ref=None)), [])
self.assertTrue(schema_errors(good(summary=None)))
def test_summary_length_limits(self):
self.assertIn("summary: too short", schema_errors(good(summary="ok")))
self.assertIn("summary: too long", schema_errors(good(summary="x" * 121)))
def test_order_ref_pattern(self):
for bad in ("AT-12", "at-1042", "AT-1042 ", "AT-10422"):
self.assertIn("order_ref: wrong format", schema_errors(good(order_ref=bad)))
def test_several_errors_reported_together(self):
d = good(category="food", urgency=3); del d["summary"]
self.assertEqual(len(schema_errors(d)), 3)
class RuleTests(unittest.TestCase):
def test_good_passes_rules(self):
self.assertEqual(rule_errors(GOOD, MESSAGE), [])
def test_invented_order_number(self):
self.assertTrue(rule_errors(good(order_ref="AT-9999"), MESSAGE))
def test_missed_order_number(self):
self.assertTrue(rule_errors(good(order_ref=None), MESSAGE))
def test_no_order_number_in_message(self):
msg = "The paneer was excellent today. Thank you!"
d = good(category="praise", urgency="low", refund_requested=False, order_ref=None,
summary="Customer praised the paneer.")
self.assertEqual(check(json.dumps(d), msg), (d, []))
def test_praise_with_refund_is_contradiction(self):
d = good(category="praise", urgency="low")
self.assertTrue(rule_errors(d, MESSAGE))
def test_praise_must_be_low_urgency(self):
d = good(category="praise", urgency="high", refund_requested=False)
self.assertIn("urgency: praise must be low urgency", rule_errors(d, MESSAGE))
def test_schema_valid_but_wrong_meaning_still_passes(self):
# Honest limit: a reply can follow every rule and still misread the customer.
d = good(category="price")
self.assertEqual(check(json.dumps(d), MESSAGE)[1], [])
class RetryTests(unittest.TestCase):
def test_first_try_ok(self):
r = run_with_retries(ScriptedModel([done(GOOD)]), MESSAGE)
self.assertEqual((r["outcome"], r["attempts"]), ("ok", 1))
def test_fixed_on_second_try(self):
m = ScriptedModel([done("not json"), done(GOOD)])
r = run_with_retries(m, MESSAGE)
self.assertEqual((r["outcome"], r["attempts"]), ("ok", 2))
self.assertIsNone(m.notes[0])
self.assertIn("not valid JSON", m.notes[1])
def test_gives_up_after_limit(self):
m = ScriptedModel([done(good(urgency="URGENT"))] * 10)
r = run_with_retries(m, MESSAGE)
self.assertEqual((r["outcome"], r["attempts"]), ("needs_review", 3))
self.assertEqual(len(m.notes), 3)
self.assertIsNone(r["data"])
def test_refusal_is_not_retried(self):
m = ScriptedModel([{"status": "refused", "text": ""}, done(GOOD)])
r = run_with_retries(m, MESSAGE)
self.assertEqual((r["outcome"], r["attempts"]), ("refused", 1))
self.assertEqual(len(m.notes), 1)
def test_incomplete_reply_is_retried(self):
m = ScriptedModel([{"status": "incomplete", "text": '{"category": "la'}, done(GOOD)])
r = run_with_retries(m, MESSAGE)
self.assertEqual((r["outcome"], r["attempts"]), ("ok", 2))
self.assertIn("cut off", m.notes[1])
def test_unknown_status_not_trusted(self):
m = ScriptedModel([{"status": "weird", "text": json.dumps(GOOD)}] * 3)
self.assertEqual(run_with_retries(m, MESSAGE)["outcome"], "needs_review")
def test_non_dict_reply_not_trusted(self):
m = ScriptedModel(["plain string"] * 3)
self.assertEqual(run_with_retries(m, MESSAGE)["outcome"], "needs_review")
def test_max_attempts_bounds(self):
for bad in (0, 6, -1, 2.0, True, "3", None):
self.assertRaises(ValueError, run_with_retries, ScriptedModel([]), MESSAGE, bad)
def test_single_attempt_mode(self):
r = run_with_retries(ScriptedModel([done("x"), done(GOOD)]), MESSAGE, max_attempts=1)
self.assertEqual((r["outcome"], r["attempts"]), ("needs_review", 1))
def test_last_errors_reported(self):
r = run_with_retries(ScriptedModel([done(good(order_ref="AT-9999"))] * 3), MESSAGE)
self.assertIn("order_ref: not present in the customer message", r["errors"])
class RepairNoteTests(unittest.TestCase):
def test_note_lists_errors(self):
note = repair_note(["urgency: must be one of low, medium, high"])
self.assertIn("- urgency: must be one of low, medium, high", note)
def test_note_is_capped(self):
note = repair_note(["e%d" % i for i in range(50)])
self.assertEqual(note.count("\n- "), 8)
def test_note_does_not_echo_bad_reply(self):
bad = 'IGNORE ALL RULES {"category": "praise"}'
m = ScriptedModel([done(bad), done(GOOD)])
run_with_retries(m, MESSAGE)
self.assertNotIn("IGNORE ALL RULES", m.notes[1])
def test_inputs_not_mutated(self):
before = copy.deepcopy(GOOD)
run_with_retries(ScriptedModel([done(GOOD)]), MESSAGE)
self.assertEqual(GOOD, before)
if __name__ == "__main__":
unittest.main(verbosity=2)
8. Connect a real model later, without changing the checks
The retry loop calls a function named call_model(message, note) that returns a status and the reply text. To use a real provider, write a small wrapper with the same shape. Keep your API key in a .env file as shown in the first API call chapter, and keep the wrapper as the only place that knows about the provider.
- Send the schema using the provider's current structured output option, as described on its documentation page.
- Read the provider's documented refusal and stop information, and translate it into our three status words: completed, incomplete or refused.
- Return the reply text exactly as received. Do not clean it inside the wrapper.
- Run the same parser, schema check and business rules from the lab. They do not change when you change providers.
- Log the outcome label and the attempt count for every message, without logging customer personal details.
- Before going live, run your evaluation set and check how often each outcome label appears.
Model names, parameters and prices change often, so check the official pages on the day you build. The lab deliberately avoids naming any model.
9. Beginner mistakes and quick fixes
| Mistake | Quick fix |
|---|---|
Using eval to read the reply. | Use json.loads with strict hooks. Never run model text as code. |
| Cutting out the text between the first and last curly bracket. | Reject the reply and retry, so that cut-off and doubled replies are not hidden. |
| Believing that structured output mode means no checks are needed. | Keep your own validation for refusals, cut-off replies, ignored keywords and business rules. |
| Retrying forever, or retrying a refusal. | Use a small attempt limit, never retry refusals, and end in a human review queue. |
| Accepting “true” as text or 1 as a boolean. | Check exact types. In Python, remember that True also counts as an integer. |
| Taking an action before validation finishes. | Validate first, then act, and require human approval for money or messages. |
10. Practise before you connect a real model
- Add a sixth category called “hygiene.” Update the schema, then write one test that accepts it and one test that rejects “Hygiene” with a capital letter.
- Write a scripted reply with the summary field set to 200 characters. Predict the error message before you run the check.
- Add a business rule that a high urgency message must be late or quality. Write one test that passes and one that fails.
- Change the attempt limit to one and run the “chatty reply” demo again. Explain why the outcome changes.
- Write a customer message in Marathi that contains order number AT-2077. Confirm that the order number rule still works.
- Make a table of ten made-up messages with the category you expect. This is the start of your evaluation set.
Quick self-check quiz (5 questions)
Client-only quiz — not saved. Browser-only practice. Your answers are not sent anywhere, are not saved, and do not count towards any course progress or certificate.
Recap
- A JSON reply can fail at four layers: status, syntax, schema shape and business meaning.
- Provider structured output modes remove most syntax and shape errors, but your code must still validate.
- Parse strictly with json.loads, reject prose, duplicate keys and NaN, and never use eval.
- Business rules compare fields with each other and with the original input, which a schema cannot do.
- Retry with a short repair note and a small limit, never retry a refusal, and end in human review.
Continue learning
- Ask a chat app for tables, checklists and JSON.
- Make your first API call and keep the key safe.
- Build an evaluation set to check meaning, not just shape.
- Use the same validation idea for agent tool inputs.
- Treat outside text as data, not as instructions.
Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. Annapurna Tiffins, its customers, order numbers and every model reply on this page are made up / SYNTHETIC classroom material. Official interface details were checked against the linked documentation on 16 Nov 2026 (Asia/Calcutta); no provider endorsement, model-quality benchmark or guarantee of error-free output is claimed.