Sub topic 6
Parsing and validating the response
This chapter assumes you can call a chat API from Python, read JSON, and have the label set and prompt from the earlier chapters. The model's reply is text. Your router needs a label it can trust. Validation is the step between the two.
Why you cannot trust the raw reply
Even with a prompt that asks for JSON only, a model can return:
- Text around the JSON, such as "Here is the result:".
- A label that is not in your set, such as
refundinstead ofbilling. - A confidence outside the range 0 to 1, or a string like
"high". - A missing key, or a truncated reply.
If you pass these straight to a router, you get crashes or silent misrouting. Treat the reply as untrusted input and check it before use.
What to check
Validation has two layers. Parsing checks that the text is valid JSON with the keys you expect. Validation checks that the values make sense for your task.
- Parse the text with
json.loads. - Read the
labelandconfidencekeys. - Convert
confidenceto a number. - Confirm the label is one of your defined labels.
- Confirm the confidence is between 0 and 1.
If any step fails, the reply is rejected.
The classify function
This function calls a call_llm function that you supply. It returns a valid (label, confidence) pair or a safe default. It uses build_prompt and LABELS from the prompt chapter.
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.0The except clause names four errors:
json.JSONDecodeError: the text is not valid JSON.KeyError: a required key is missing.TypeError: the parsed JSON is not an object, orconfidenceisnull.ValueError:confidencecannot be converted to a number.
The check after the try block catches replies that parse fine but hold bad values. A catch-all except Exception would hide real bugs, so list the errors you expect.
Retries and the safe default
The loop gives the model a second chance. Many bad replies are one-off formatting slips, and a repeat call often fixes them. Keep max_attempts small. Each retry adds cost and delay, and a prompt that fails repeatedly needs fixing, not more retries.
When all attempts fail, the function returns ("other", 0.0). The label other is your fallback, and the confidence of zero guarantees that the routing step sends the item to a human. A failure never becomes a confident wrong answer.
Common errors
- Markdown fences around the JSON. Some models wrap output in a code fence.
json.loadsfails on it. You can strip the fence before parsing, or ask for raw JSON in the prompt. Retries usually recover from this too. - Returning the failure as a real label. Return a value that the router already treats as "needs a human". Here that is
otherwith confidence 0. - Swallowing failures silently. The code above hides why a call failed. In production, log the raw reply on each rejection so you can find patterns, as the monitoring chapter describes.
- Boolean confidence.
float(True)returns1.0, so a reply withtruepasses. This is rare. If it matters, check the type before converting.
Exercise
A model replies {"label": "billing", "confidence": 1.4}. Does classify return it? What happens on the next attempt, and what is returned if every attempt looks like this?
Show answer
No. The JSON parses and the label is valid, but the confidence 1.4 is outside 0 to 1, so the reply is rejected. The function calls the model again, up to max_attempts. If every attempt fails, it returns ("other", 0.0), which the router sends to human triage.
Exercise
Why does the fallback return a confidence of 0.0 instead of a plausible value such as 0.5?
Show answer
The router sends anything below its threshold to human triage. A value of 0.0 is below any sensible threshold, so a failed parse can never pass as a confident prediction. A value like 0.5 could clear a low threshold and misroute the item.