Traditional software has unit tests because functions return the same output for the same input. Language model features do not, which tempts teams to skip testing and rely on a few impressive demos. That works until a prompt tweak, a model upgrade or a change in user behavior quietly degrades quality, and nobody notices for weeks.
Evaluation is how you replace opinion with evidence. Guardrails are how you limit damage when the evidence is not enough. This article covers both: building golden sets, using models as judges without fooling yourself, wiring regression tests into delivery, filtering unsafe input and output, and monitoring what happens after launch.
Why LLM features need their own testing discipline
Three properties make these systems hard to test with ordinary methods.
- Open-ended outputs. There are many acceptable answers, so exact-match assertions rarely apply.
- Hidden coupling. Prompts, models, retrieval settings, tool definitions and temperature all affect results. A change in one place shifts behavior in another.
- Moving dependencies. Hosted models are updated or deprecated. The model you tested in March may not be the model serving traffic in June, even under the same name, unless you pin a dated version.
The goal is not to prove correctness, which is impossible. The goal is to detect regressions, compare alternatives quantitatively, and know the failure rate well enough to design around it.
Build a golden set
A golden set is a collection of representative inputs paired with what good looks like. It is the foundation for every other technique here.
Where examples come from
- Production logs, sampled and anonymized. Real queries are messier and more varied than anything you will invent.
- Support tickets and user complaints. Each past failure becomes a permanent test.
- Subject matter experts who write hard cases and edge cases.
- Synthetic variations generated by a model, then reviewed by a human. Useful for coverage, risky if used alone since they inherit the generator’s blind spots.
Start with 50 to 100 examples; grow to several hundred. Stratify by task type, user segment, language and difficulty, and include negative cases: inputs that should be refused, questions with no answer, and adversarial prompts.
What to store with each example
- The input, including any context the system would receive.
- A reference output or, more flexibly, a rubric: a list of properties a good answer must have (“states the refund window”, “does not promise a specific date”, “uses formal tone”).
- Labels for slicing results: category, language, risk level.
- For tool-using systems, the expected tool calls or final state.
Rubrics age better than reference answers. Two correct responses can differ in wording, but both can be checked against the same list of required facts and prohibited behaviors.
A golden set is a product asset, not a testing chore. Every incident that reaches a customer should leave a new test behind.

Three kinds of checks
Not everything needs a model to grade it. Use the cheapest check that works.
- Deterministic checks. Schema validity, required fields, length limits, presence or absence of specific strings, regular expressions for forbidden content, code that compiles, SQL that parses and returns expected rows. These are fast, free and perfectly repeatable. Use them first.
- Reference-based metrics. Exact match for classification labels, F1 for extraction fields, retrieval recall for search. Classic metrics remain the best choice when the task has a ground truth.
- Model-graded checks. An LLM scores qualities that are hard to code: helpfulness, faithfulness to a source, tone, completeness.
LLM-as-judge, done carefully
A judge model reads the input, the output and a rubric, and returns a score or verdict. It scales evaluation far beyond what humans can review, and with care it correlates well with human preference. Without care it produces confident nonsense.
Known biases to counter:
- Position bias. In pairwise comparison, judges favor the first or second answer more than chance. Run each comparison twice with the order swapped and only count consistent verdicts.
- Verbosity bias. Longer answers score higher. Add length-neutral instructions to the rubric, or compare length-controlled outputs.
- Self-preference. A model tends to rate its own family’s outputs higher. Prefer a judge from a different provider than the system under test when feasible.
- Vague rubrics. “Rate quality from 1 to 10” gives noise. Break it into binary questions: “Does the answer cite a source? Is every claim supported by the source? Does it answer the question asked?”
Good practice:
- Ask for reasoning before the verdict, and store it. Reading the reasoning is how you find judge errors.
- Use low temperature and pin the judge model version.
- Calibrate against humans. Label 100 or so examples by hand, compute agreement with the judge (Cohen’s kappa or simple percent agreement), and iterate on the rubric until agreement is acceptable, often above 80 percent for binary criteria.
- Re-check calibration when you change the judge model or the rubric.
- Never evaluate high-stakes decisions with a judge alone. Keep human review on a sample.
Regression testing in the delivery pipeline
Evaluations only help if they run automatically. Treat prompts, model versions and retrieval configs as code under version control, and run the golden set on every change.
A workable setup has three tiers:
| Tier | When | Size | Purpose |
|---|---|---|---|
| Smoke | Every commit | 20 to 50 cases, deterministic checks | Catch broken formats and obvious failures in minutes |
| Full | Every pull request that touches prompts, models or retrieval | Entire golden set, judges included | Detect quality regressions with numbers |
| Deep | Nightly or before release | Golden set plus fresh production samples and adversarial suite | Catch drift and rare failures |
Report results as a comparison against the main branch: pass rate per category, a diff of cases that flipped from pass to fail, and the cost and latency delta. A change that raises average score but breaks a safety category should still fail. Define thresholds per slice, not just on the mean.
Because outputs vary between runs, quantify noise. Run the baseline several times to learn its standard deviation, and do not chase differences smaller than that. For borderline decisions, increase the sample size or run each case multiple times.
When you consider a model upgrade, run the full set on both models before switching and read the flipped cases by hand. A newer model is usually better on average and worse on a few things you depended on.
Guardrails
Evaluation measures quality offline. Guardrails act at runtime on individual requests. They are layered controls, and no single layer is enough.
Input guardrails
- Validation and limits. Cap input length, file types and request rates. Cheap and effective against abuse and runaway cost.
- Prompt injection detection. Classifiers and heuristics can flag instructions such as “ignore previous instructions.” Treat them as a signal, not a wall. The reliable defense is architectural: untrusted content is delimited as data, and the model is given no capability that the user lacks.
- PII handling. Detect and redact personal identifiers before sending text to a vendor if your policy or contract requires it.
- Topic and policy filters. Route out-of-scope requests (medical advice in a banking app, for example) to a fixed response.
Output guardrails
- Schema and format validation for anything consumed by code.
- Content moderation for hate, self-harm, sexual content and violence, using a provider moderation endpoint or a self-hosted classifier.
- Grounding checks. For retrieval-based answers, verify each cited passage exists and supports the claim.
- Sensitive data leak checks. Scan for secrets, keys, other customers’ identifiers and system prompt text.
- Business rule enforcement. The model may draft a refund approval, but code decides whether the amount is within policy.
Design principles
Put hard constraints in code, not in the prompt. A prompt that says “never exceed a 10 percent discount” is a request; a validator that rejects discounts above 10 percent is a guarantee. Fail closed for risky actions and fail open for low-risk ones. Measure the false positive rate of every filter, since over-blocking harms users and teams will quietly disable filters that annoy people.
Latency is a cost. Run independent checks in parallel, use small classifiers rather than large models where accuracy allows, and apply the heaviest checks only to high-risk routes.
Monitoring in production
Offline sets cannot cover what users will actually do. Production monitoring closes the loop.
What to capture
- Full request traces: prompt version, model version, retrieved context, tool calls, output, latency, tokens.
- Explicit feedback: thumbs, corrections, regenerate clicks.
- Implicit signals: edit distance between draft and final text, conversation abandonment, escalation to a human agent, repeated rephrasing.
- Guardrail events: blocks, redactions, repair retries.
What to watch
- Rolling quality scores from sampling 1 to 5 percent of traffic through your LLM judge, with alerts on drops.
- Refusal rate and fallback rate. A sudden jump signals a provider change or a bad deploy.
- Distribution drift: new languages, topics or input lengths that the golden set does not represent.
- Cost per request and tail latency.
Close the loop
Run a weekly review of low-scored and thumbs-down traces. Label them, add the representative ones to the golden set, and fix the root cause. This is where most of the real improvement comes from. Also keep an incident process: define severity, a rollback path (flag off, previous prompt version, fallback model) and a post-mortem template that ends with a new test.
Datainter builds this loop into client AI projects as a standing weekly ritual of thirty minutes, because the teams that look at real failures every week improve faster than teams that tune prompts by intuition.
Key takeaways
- Start with a golden set of 50 to 100 real cases, grow it from every production failure, and prefer rubrics to single reference answers.
- Use the cheapest check that works: deterministic first, reference metrics second, model judges for qualities you cannot code.
- Calibrate LLM judges against human labels, counter position and verbosity bias, and never rely on a judge alone for high-stakes decisions.
- Run evaluations automatically in tiers on every change, set thresholds per slice, and measure run-to-run noise before trusting small differences.
- Enforce hard rules in code, layer input and output guardrails, and track the false positive rate of each filter.
- Sample production traffic for ongoing scoring, review failures weekly and feed them back into the test set.

