Sub topic 5
Getting Parseable Verdicts with Short Reasoning
This chapter assumes you can read Python and have prompted an LLM through an API. You should also have a rubric like the one from the previous chapter, with a single criterion and defined score anchors. Here the question is how to get a verdict out of the judge that code can trust.
Why free-text verdicts break pipelines
A judge that replies "I'd say this answer is mostly good, maybe a 4" is easy for a person to read. A pipeline cannot use it. Parsing it with a regex fails when the model writes "4/5", "four", or "between 3 and 4". A failed parse often turns into a silent default, and a silent default corrupts your metric without any error.
The fix has two parts:
- Define an output contract that is small and strict.
- Reject anything that violates it, and count the rejections.
Designing the output contract
A good contract for a pointwise judge has three properties.
- Few fields. Use a
reasoningstring and ascoreinteger. Each extra field adds a way to fail. - A closed value set. Scores are integers in a fixed range. Pairwise verdicts are a fixed set of labels such as
"first"and"second". Avoid open-ended values. - Reasoning before the score. The model generates tokens in order. If the score comes first, the reasoning can only rationalize it. If the reasoning comes first, the score can depend on it.
The prompt below puts reasoning first and ends with an explicit format instruction. The parser rejects malformed or out-of-range output instead of accepting it.
import json
RUBRIC = """Score the answer from 1 to 5 for faithfulness to the context.
1 = contradicts the context; 3 = partly supported; 5 = fully supported.
Judge faithfulness only. Ignore length and writing style."""
def build_prompt(question, context, answer):
return (
f"{RUBRIC}\n\nQuestion: {question}\nContext: {context}\nAnswer: {answer}\n\n"
'Reply with JSON only: {"reasoning": "<one or two sentences>", "score": <integer 1-5>}'
)
def parse_verdict(text):
data = json.loads(text)
score = data["score"]
if not isinstance(score, int) or not 1 <= score <= 5:
raise ValueError(f"invalid score: {score!r}")
return datajson.loads raises an error on text that is not JSON. The range check catches 7, 0, and "4" (a string). Both failures surface as exceptions, which is what you want.
Keeping the reasoning short
Reasoning helps in two ways. A short rationale often improves the score, and it gives you something to read when you audit disagreements with human labels. The limit "one or two sentences" matters for three reasons:
- Long reasoning costs tokens on every item in every run.
- Long reasoning drifts toward style commentary, which pulls the judge away from the single criterion.
- Long reasoning gives the model more room to produce JSON that is broken by unescaped quotes or a truncated ending.
Treat the reasoning as evidence for your review, not as an explanation of how the model decided. The text is generated alongside the score, and it can be fluent and wrong. When you audit, check whether the cited evidence exists in the context. Do not assume the rationale describes the real cause of the score.
Hardening the parser
Real models break a strict contract in predictable ways. The table lists the common failures and a response to each.
| Failure | Example | Response |
|---|---|---|
| Markdown fence around JSON | a `json` fence wrapping the object | Strip one outer fence, then parse |
| Prose before or after the JSON | "Sure! Here is my verdict: {...}" | Retry. Do not hunt for braces in prose |
| Score as a string | `"score": "4"` | Reject, because the type is wrong |
| Score out of range | `"score": 7` | Reject |
| Boolean as score | `"score": true` | Reject, since `bool` is a subclass of `int` in Python |
| Missing or extra keys | no `reasoning` | Reject |
| Truncated output | JSON ends mid-string | Retry. Check the token limit |
Tolerating a code fence is a reasonable compromise because it is common and unambiguous. Searching for the first { in arbitrary prose is not, because the model may quote braces from the context. The version below adds these checks and a bounded retry. A retry is a fresh sample, so it can legitimately differ from the first reply.
import json
import re
FENCE = "`" * 3
FENCE_RE = re.compile(rf"{FENCE}(?:json)?\s*(.*?)\s*{FENCE}", re.DOTALL)
def parse_verdict(text, lo=1, hi=5):
text = text.strip()
match = FENCE_RE.fullmatch(text)
if match:
text = match.group(1)
data = json.loads(text)
if not isinstance(data, dict) or set(data) != {"reasoning", "score"}:
raise ValueError("expected exactly the keys reasoning and score")
score = data["score"]
if isinstance(score, bool) or not isinstance(score, int) or not lo <= score <= hi:
raise ValueError(f"invalid score: {score!r}")
if not isinstance(data["reasoning"], str) or not data["reasoning"].strip():
raise ValueError("empty reasoning")
return data
def judge_with_retry(call_model, prompt, max_attempts=3):
errors = []
for _ in range(max_attempts):
try:
return parse_verdict(call_model(prompt))
except ValueError as exc: # JSONDecodeError is a ValueError
errors.append(str(exc))
return {"score": None, "reasoning": None, "errors": errors}
replies = iter([
"Sure! Here is my verdict: 4",
'{"reasoning": "The context supports every claim.", "score": 5}',
])
print(judge_with_retry(lambda prompt: next(replies), "ignored"))Running this prints {'reasoning': 'The context supports every claim.', 'score': 5}. The first reply is rejected, and the second parses.
Never convert failures into scores
When all attempts fail, the function returns score: None. It does not return 3, 1, or 0. A fallback score is a fabricated measurement. Keep the item as "unscored" and report two numbers:
- the parse failure rate across the run
- the metric computed over the items that parsed
If the failure rate is 2%, the metric is probably fine. If it is 20%, the metric describes only the items the judge found easy to answer in format. That is a biased subset. Failure rates also differ by condition. Long answers and answers containing JSON or quotation marks tend to break the output format more often.
Using the provider's structured output features
Many APIs can constrain generation to a JSON schema or a fixed set of labels. Use this when available, because it removes most syntax failures. Two caveats apply.
- A valid schema does not mean a valid judgment. The constraint guarantees the shape of the reply. It does not guarantee the score is correct. Your range check should stay in place.
- Field order still matters. If the schema lists
scorebeforereasoning, the model will emit the score first. Keep the order you want the model to generate.
Constrained output can also change score distributions slightly compared with free generation. If you switch the format mid-project, treat it as a judge change and re-validate (see the later chapter on pinning and re-validating).
Format choices that affect variance
Format decisions feed into run-to-run variance, which later chapters measure.
- Narrow scales are steadier. A 1 to 5 scale with written anchors gives more repeatable scores than 1 to 10, where adjacent values have no distinct meaning.
- Binary labels are steadier still. For pass/fail criteria, a
"pass"or"fail"label with a one-sentence reason is often the most reliable contract. It also maps directly onto the agreement and confidence-interval tools used later. - Low temperature reduces variance but does not remove it. Parse each run the same way and compare, rather than assuming determinism.
Log the raw reply text for every item, including failures. When a human label disagrees with the judge, you need the original text to see whether the cause was the rubric, the model, or the parser.
Exercise
Your judge returns {"score": 4, "reasoning": "Mostly supported."} for 190 of 200 items. The other 10 replies are prose without JSON, and a teammate proposes giving those 10 a score of 3 "to stay neutral". What should you do instead, and what two numbers should you report?
Show answer
Mark the 10 items as unscored, optionally after a bounded retry, and do not invent a score. A default of 3 is a made-up measurement that pulls the average toward the middle. Report the parse failure rate (10 of 200, or 5%) and the metric computed over the 190 parsed items. Also check whether the 10 failures share a trait, such as very long answers, because that would mean the 190 are a biased subset.