By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The extractor returned JSON on the first attempt. It parsed. It matched the schema. Every key had the right type. And it was wrong. It reported a total of $0.00 for an invoice with three line items, because it summed a field the document does not contain.
A parse error is a gift. It stops the pipeline. A valid object with a wrong number flows into your database, your email and your monthly report, and nothing alerts you.
You have three ways to ask for a shape. They differ in how strongly the format is enforced.
| Pattern | How it works | Best for | Limitation |
|---|---|---|---|
| Tool use as a schema | Declare one tool whose input_schema is your object; the model returns matching arguments | Objects that drive code paths | The model can still decline to call it |
| Assistant prefill | Write the first characters, such as { or a key name | Locking a format quickly | Does not validate the contents |
| Schema in the prompt | Paste the schema and one example, ask for JSON only | Small objects and prototypes | The model can add prose around it |
Tool use is the strongest option, because the schema is machine-readable on both sides. Your code validates against the same definition the model was given, so a disagreement is a bug you can see. Prefill and prompt wording are cheaper and weaker, which is fine for a summary and wrong for a payment record.
Parse. Turn the text into a Python object. Strip a code fence first, because models sometimes wrap JSON in one.
Check the structure. Required keys, types, enum values, number ranges, string lengths. A JSON Schema gives you this.
Check the meaning. Do the referenced ids exist? Do the line items sum to the total? Is the date in the future? Does the currency match the account?
Decide. Accept, re-ask with the specific error, or stop and escalate. Never accept a partial object in silence.
Structure checks catch a broken contract. Meaning checks catch a confident mistake. You need both, and most pipelines ship with only the first because it is the easy one to write.
import json
REQUIRED = {"ticket_id": str, "priority": str, "summary": str}
PRIORITIES = {"low", "normal", "high"}
def check(raw):
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
return None, f"not JSON ({exc.msg})"
if not isinstance(data, dict):
return None, "top level is not an object"
missing = [key for key in REQUIRED if key not in data]
if missing:
return None, "missing keys: " + ", ".join(missing)
wrong = [key for key, kind in REQUIRED.items() if not isinstance(data[key], kind)]
if wrong:
return None, "wrong type: " + ", ".join(wrong)
if data["priority"] not in PRIORITIES:
return None, f"priority {data['priority']!r} not in {sorted(PRIORITIES)}"
if not data["summary"].strip():
return None, "summary is empty"
return data, None
REPLIES = [
'{"ticket_id": "T-9", "priority": "urgent"}',
'{"ticket_id": "T-9", "priority": "high", "summary": "Damaged vase, order A-4471"}',
]
MAX_ATTEMPTS = 2
def ask(prompt):
"""Stand-in for the model call: returns the canned replies in order."""
return REPLIES.pop(0) if REPLIES else ""
for attempt in range(1, MAX_ATTEMPTS + 1):
raw = ask("route this ticket")
data, error = check(raw)
if data:
print(f"attempt {attempt}: accepted {data['priority']} for {data['ticket_id']}")
break
print(f"attempt {attempt}: rejected -> {error}")
print(f" re-ask: return JSON with ticket_id, priority, summary; fix: {error}")
else:
print("escalate: no valid object after 2 attempts")Three properties make this loop safe. The attempt count is bounded, so a bad prompt cannot cost you an hour. The error message goes back to the model, so the second attempt knows something the first one did not. And the failure path is defined, so a ticket with no valid object reaches a human queue instead of nowhere.
Models write fluently, and fluency reads as competence to humans. A model that invents a policy number writes it in the same tone as a correct one, so tone cannot be your signal.
Three habits keep this honest. Make the model cite an id your code can look up, and reject a citation that does not resolve. Require an explicit unknown for missing values, so an empty string cannot pass for a fact. And before an action moves money, publishes content or deletes a record, check the result against the source system.
Treat every response as a proposal from an untrusted service. Your code makes the decision, and your code owns the evidence.
Add a validator to one output in your application. Write the structural checks, then the single meaning check that would have caught your last bad output. Wrap the call in a two-attempt loop that re-asks with the error and escalates after the second failure. Feed it three deliberately broken replies and confirm each one is rejected with a reason.
Key takeaways
A parse error stops the pipeline; a valid but wrong object does not.
Tool schemas enforce shape hardest; prefill and prompt text are cheaper and weaker.
Validate structure first, then meaning: ids, totals, dates, currency.
Bound the retry, send the error back, and define the escalation path.
Ask for citations and explicit unknowns, and check high-impact results against the source.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.