Dev.to AI 🤖 Ai 👁 0 📖 3 min read

How to Test LLM JSON Outputs Beyond Valid Syntax

An LLM that routes support tickets can return {"queue":"billing","needs_human":false} for a customer who reports an unrecognized charge. The JSON parses. Both fields have the expected types. The result still misses the c

An LLM that routes support tickets can return {"queue":"billing","needs_human":false} for a customer who reports an unrecognized charge. The JSON parses. Both fields have the expected types. The result still misses the case that needs human review.

Keep two checks in your evaluation. First, verify that the response can enter your application. Then, check whether it makes the right decision for a specific input. The same harness can run against saved responses on your laptop and against a live model before you change a prompt.

Define the output contract

In this example, the model returns a queue and a review flag. A separate service decides what to do with the result. The application's policy sends unrecognized charges to billing with human review and routine export crashes to technical support.

The following script uses Python's standard library. Save it as eval_triage.py.

import json
from collections.abc import Callable
from dataclasses import dataclass


@dataclass(frozen=True)
class Decision:
    queue: str
    needs_human: bool


@dataclass(frozen=True)
class Case:
    name: str
    ticket: str
    expected: Decision


def parse_decision(raw: str) -> Decision:
    value = json.loads(raw)
    if not isinstance(value, dict) or value.keys() != {"queue", "needs_human"}:
        raise ValueError("expected exactly queue and needs_human")

    queue = value["queue"]
    if queue not in ("billing", "technical", "other"):
        raise ValueError("unknown queue")
    if not isinstance(value["needs_human"], bool):
        raise ValueError("needs_human must be a JSON boolean")

    return Decision(queue, value["needs_human"])


CASES = (
    Case(
        "unrecognized-charge",
        "There is a charge on my account that I do not recognize.",
        Decision("billing", True),
    ),
    Case(
        "negated-billing",
        "This isn't a billing question. The app crashes when I export.",
        Decision("technical", False),
    ),
)


def evaluate(call_model: Callable[[str], str]) -> list[str]:
    failures = []
    for case in CASES:
        raw = call_model(case.ticket)
        try:
            actual = parse_decision(raw)
        except ValueError as error:
            failures.append(f"{case.name}: invalid output ({error})")
            continue

        if actual != case.expected:
            failures.append(
                f"{case.name}: expected {case.expected}, got {actual}"
            )
    return failures


if __name__ == "__main__":
    saved_outputs = {
        CASES[0].ticket: '{"queue":"billing","needs_human":false}',
        CASES[1].ticket: '{"queue":"technical","needs_human":false}',
    }
    failures = evaluate(saved_outputs.__getitem__)
    for failure in failures:
        print(failure)
    print(f"{len(CASES) - len(failures)}/{len(CASES)} cases passed")
    raise SystemExit(1 if failures else 0)

Run python eval_triage.py. The saved outputs deliberately include one incorrect decision. You'll see unrecognized-charge fail and the runner report 1/2 cases passed. Change that response's needs_human to true and rerun. Use the failure label to distinguish a malformed response from a valid response with the wrong decision.

Keep the cases tied to real failures

The second ticket mentions billing in a negation. It catches a prompt that routes on keywords even when it handles straightforward examples well. When a new failure appears, reduce it to the smallest ticket that still reproduces the problem. Give the case a name that describes what went wrong and record the expected decision according to your application's policy.

Saved responses make parser and runner changes repeatable. To evaluate the model itself, replace saved_outputs.__getitem__ with the function your app uses to produce the raw response. Compare the old and new prompt on the same cases with the same model configuration. When a failing case could affect a customer, run it several times and record how often it fails. A single passing response can hide a decision that changes between calls.

Treat these examples as regression tests for the decisions your application depends on. A passing set tells you which cases you covered and gives you a concrete place to add the next failure.

Drafted with AI assistance. The Python example was run locally.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.