Sub topic 6
Parsing and validating the response
This chapter covers what happens after the model replies. The reply is text, and your router needs a trustworthy label. You will parse the reply, check it against the label set, retry when it is bad, and fall back safely when retries run out.
Prerequisites assumed: basic Python, comfort with JSON, and a call_llm(prompt) function that takes a prompt string and returns the model's reply as a string. The examples build on the LABELS dictionary and build_prompt function from the earlier chapters on label design and prompt writing.
Why model output must be treated as untrusted
Even when the prompt says "Reply with JSON only", the model can still return something else. A parser that assumes the happy path will crash or, worse, route silently to the wrong queue.
Common failures:
- Wrapped output. The JSON sits inside a Markdown fence or after a sentence such as "Sure, here is the result:".
- Invalid JSON. Trailing commas, single quotes, or a truncated reply that hit the token limit.
- Missing or renamed keys. The reply has
"category"instead of"label". - Wrong types.
"confidence": "high"where you expected a number, or"label": ["billing", "account"]. - Invented labels.
"label": "Billing"(wrong case) or"label": "refund"(not in your set). - Out-of-range values.
"confidence": 85when you asked for 0 to 1.
Each one needs a defined response in code. The pattern is: parse, validate, retry, then fall back.
The baseline implementation
This is the core function. It receives call_llm as an argument, so you can test it without a real API.
import json
def classify(text, call_llm, max_attempts=2):
prompt = build_prompt(text)
for _ in range(max_attempts):
raw = call_llm(prompt)
try:
data = json.loads(raw)
label = data["label"]
confidence = float(data["confidence"])
except (json.JSONDecodeError, KeyError, TypeError, ValueError):
continue
if label in LABELS and 0.0 <= confidence <= 1.0:
return label, confidence
return "other", 0.0Walk through what each part does.
json.loads(raw)raisesjson.JSONDecodeErrorfor invalid JSON. It can also return something that is not a dictionary, such as a list or a number.data["label"]raisesKeyErrorif the key is missing. Ifdatais a list, it raisesTypeError. Ifdatais a string, indexing with a string key also raisesTypeError.float(data["confidence"])raisesValueErrorfor"high"andTypeErrorforNoneor a list.- The
exceptclause catches all four exception types and usescontinueto go to the next attempt. - The check
label in LABELSrejects invented labels. The range check rejects values such as 85. - If every attempt fails, the function returns
("other", 0.0).
Parsing versus validating
These are two separate steps, and the code handles them differently.
- Parsing asks whether the text is well-formed and has the shape you need. Failures raise exceptions.
- Validating asks whether the values make sense for your task. Failures are ordinary
Falseconditions.
Keeping them apart helps when you debug. A spike in parse failures points to a formatting problem, such as a model change or a truncated reply. A spike in validation failures points to a label-set problem, such as the model inventing a label that your definitions do not cover.
Edge cases worth handling
The baseline is correct for the common failures. A few cases deserve extra attention.
Booleans pass `float()`
float(True) returns 1.0. A reply of {"label": "billing", "confidence": true} would be accepted with full confidence. If this matters to you, check the type before converting.
NaN passes the range check incorrectly
float("nan") succeeds. The comparison 0.0 <= nan <= 1.0 is False, so the baseline rejects it. This works by accident of how comparisons behave. If you rewrite the check as not (confidence < 0 or confidence > 1), NaN would pass. Keep the positive form 0.0 <= confidence <= 1.0.
Case and whitespace in labels
"Billing" and "billing " are rejected by the baseline. You can normalize with .strip().lower() before the membership test. This is a reasonable leniency because the intent is unambiguous. Do not go further and try to map synonyms such as "refund" to "billing". That hides a gap in your label definitions that you should fix in the prompt.
Extra text around the JSON
Models often wrap JSON in a Markdown fence. You can strip a fence before parsing. This version extracts the outermost braces:
import json
def extract_json(raw):
start = raw.find("{")
end = raw.rfind("}")
if start == -1 or end <= start:
raise json.JSONDecodeError("no JSON object found", raw, 0)
return json.loads(raw[start : end + 1])Use it in place of json.loads(raw). It is a convenience for harmless wrapping. It will not repair broken JSON, and it can grab the wrong span if the reply contains several objects. If your provider offers a structured-output or JSON mode that constrains the reply, prefer that over extraction.
Non-dictionary JSON
json.loads("[]") succeeds and returns a list. The baseline then raises TypeError on data["label"], which the except clause handles. If you refactor and move the key lookups out of the try block, you lose that protection.
Retry design
The baseline retries with the identical prompt. That works because model output varies between calls, especially at a temperature above zero. Consider these points.
- Cap attempts. Each retry costs money and adds latency. Two or three attempts is typical.
- Retry only on bad output. Do not retry on a valid reply with low confidence. A second call does not make an uncertain model more certain, and it can hide real ambiguity. Handle low confidence by abstaining, covered in the next chapter.
- Separate transport errors. Timeouts, rate limits, and server errors from the API are a different failure class. Handle them with backoff in the layer that wraps
call_llm, not in the parsing loop. - Consider feeding the error back. A retry can append a short note such as "Your last reply was not valid JSON. Reply with JSON only." This helps for formatting mistakes but adds prompt complexity. Start with the plain retry and measure.
If a model fails the same way on every attempt, retrying will not help. Fix the prompt or switch to constrained output.
The safe default
After the last attempt, the function returns ("other", 0.0). This choice has two purposes.
"other"is a label that exists in your set, so downstream code never sees an undefined value.- A confidence of
0.0falls below any reasonable threshold, so the router sends the item to human triage.
The fallback should never pick a real queue. Guessing "billing" after a failure sends an unrelated message to the wrong team with no sign that anything went wrong.
One weakness is that a genuine ("other", 0.0) and a failed parse look the same to the caller. For monitoring you may want to tell them apart. A small change is to return a third value, or to log the failure inside classify.
import logging
logger = logging.getLogger("classifier")
def classify_logged(text, call_llm, max_attempts=2):
prompt = build_prompt(text)
for attempt in range(1, max_attempts + 1):
raw = call_llm(prompt)
try:
data = json.loads(raw)
label = data["label"]
confidence = float(data["confidence"])
except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
logger.warning("parse failure on attempt %d: %r", attempt, exc)
continue
if label in LABELS and 0.0 <= confidence <= 1.0:
return label, confidence
logger.warning("validation failure on attempt %d: %r", attempt, label)
logger.error("all %d attempts failed; using fallback", max_attempts)
return "other", 0.0Do not log the full message text if it may contain personal data. Log the error type and an item ID instead.
Testing the validator with a fake model
Because call_llm is a parameter, you can test every failure mode without network access. This fake returns a scripted sequence of replies.
def make_fake(replies):
iterator = iter(replies)
return lambda prompt: next(iterator)
good = '{"label": "billing", "confidence": 0.9}'
bad_json = "Sure! The label is billing."
bad_label = '{"label": "refund", "confidence": 0.9}'
bad_range = '{"label": "billing", "confidence": 85}'
print(classify("I was charged twice", make_fake([good])))
print(classify("I was charged twice", make_fake([bad_json, good])))
print(classify("I was charged twice", make_fake([bad_label, bad_range])))Expected output:
('billing', 0.9)
('billing', 0.9)
('other', 0.0)The first call succeeds immediately. The second recovers on the retry. The third fails both attempts and returns the fallback. Turn each failure mode listed earlier into a test like these, and run them whenever you change the prompt or the parser.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Catching bare `Exception` | Hides bugs such as a misspelled variable | Catch the specific exception types |
| Returning the model's raw label without checking it | Unknown labels reach routing code | Test `label in LABELS` |
| Defaulting to a real queue on failure | Wrong team gets the item silently | Fall back to `"other"` with zero confidence |
| Retrying forever | Unbounded cost and latency | Cap attempts |
| Mapping synonyms to labels in the parser | Hides gaps in label definitions | Fix the definitions in the prompt |
| Not logging failures | No signal when the format drifts | Log error type and attempt number |
Exercises
Exercise
A model replies with {"label": "billing", "confidence": "high"}. Trace what the baseline classify function does with this reply on a single attempt, and name the exception involved.
Show answer
json.loads succeeds and data["label"] returns "billing". Then float("high") raises ValueError. The except clause catches it and continue moves to the next attempt. If no attempts remain, the function returns ("other", 0.0).
Exercise
Why does the fallback return ("other", 0.0) instead of the most common label, such as "technical"?
Show answer
"other" is a valid label, so downstream code never sees an undefined value, and a confidence of 0.0 falls below the routing threshold, so the item goes to human triage. Returning "technical" would send items to a real queue after a failure, with no signal that the model's output was unusable.
Exercise
Write a test using make_fake that confirms classify returns ("other", 0.0) when the reply is the JSON array [] on every attempt.
Show answer
print(classify("hello", make_fake(["[]", "[]"]))) prints ('other', 0.0). json.loads("[]") returns a list, data["label"] raises TypeError, the except clause catches it, and both attempts fail.