Reliable LLM application testing requires more than checking whether a few answers “look good.” This guide shows how to build a repeatable Python evaluation workflow that measures answer quality, structured-output validity, retrieval and citation behavior, latency, token cost, and safety-related failures whenever you change a model, prompt, tool, or retrieval index.
Overview
An LLM application can regress even when its core code has not changed. A model migration may alter formatting or refusal behavior. A prompt revision may improve one intent while weakening another. A new retrieval index may return newer documents but reduce citation coverage. A tool change may increase latency or produce malformed arguments.
For that reason, treat evaluations as regression tests rather than as a one-time benchmark. Each test case should describe an input, the expected behavior, and the measurements you want to collect. The expected behavior does not always need to be one exact answer. For open-ended generation, a rubric or set of required properties is usually more useful than string matching.
A practical evaluation run has five layers:
- Task quality: Does the response solve the user’s request accurately and completely?
- Contract validation: Does it follow the required schema, format, and tool-call rules?
- Grounding: For retrieval-augmented generation, is the response supported by the supplied context and citations?
- Operational performance: How long did the request take, and how many input and output tokens did it use?
- Safety and handling: Does the application refuse, redirect, or escalate cases according to your documented requirements?
Keep these dimensions separate. A response can be factually useful but fail JSON parsing, or be well formatted but unsupported by the retrieved sources. Separate scores make triage more direct.
For application design context, compare this workflow with the retrieval and cost-control practices in Build a Production-Ready RAG Application in Python. Prompt changes that affect tools or structured responses should also be reviewed alongside Prompt Engineering for Developers.
How to estimate
Start with a versioned evaluation dataset. A compact dataset that represents real failure modes is more useful than a large collection of easy examples. Store it in JSONL, a database table, or another format that supports review and version control.
A useful test record can look like this:
{
"id": "billing_014",
"category": "account_question",
"input": "Can I cancel after my renewal date?",
"context": [
{"id": "policy-12", "text": "..."}
],
"expected": {
"must_include": ["explain the applicable cancellation rule"],
"must_cite": ["policy-12"],
"must_not_include": ["an invented refund amount"]
},
"risk": "medium"
}Record the system version with every run. At minimum, include the model identifier, prompt version, application commit, dataset version, retrieval-index version, evaluator version, and timestamp. Without these fields, a score change is difficult to explain later.
For each response, calculate a small set of measurements:
- Pass rate: passed cases divided by total cases for a binary requirement.
- Rubric score: the average of defined criteria such as correctness, completeness, and relevance.
- Schema validity: valid structured responses divided by responses expected to use that schema.
- Citation coverage: supported claims or required source references divided by claims or references that should be supported.
- Latency: record at least the elapsed time per request; summarize with an average and a percentile when the dataset is large enough to make that summary useful.
- Estimated cost: calculate input and output usage separately using the provider’s current published rates or your internal rate card.
The cost formula is intentionally simple:
Estimated run cost = (input tokens ÷ billing unit × input rate) + (output tokens ÷ billing unit × output rate) + tool, retrieval, or platform charges.
Do not hard-code rates into the test logic. Put them in a dated configuration file so a pricing update does not require rewriting the evaluator. If your provider uses a different billing unit or has separate cached-input, batch, tool, or platform charges, represent those as separate inputs rather than hiding them in one blended estimate.
A minimal Python result record might be assembled as follows:
result = {
"case_id": case["id"],
"passed_schema": schema_ok,
"quality_score": quality_score,
"citation_score": citation_score,
"latency_seconds": elapsed,
"input_tokens": usage.input_tokens,
"output_tokens": usage.output_tokens,
"model": config.model,
"prompt_version": config.prompt_version,
"dataset_version": config.dataset_version
}The evaluator should produce both individual records and an aggregate report. Aggregate metrics reveal trends; individual records explain the failures behind those trends.
Inputs and assumptions
Before comparing two application versions, write down the assumptions that make the comparison fair.
Define the test population
Separate cases by intent, risk, language, context length, and tool usage. A single overall score can conceal a serious regression in a small but important category. Maintain a fixed “golden” set for release comparisons and a rotating set of recent production-like cases for discovery.
Define the expected behavior
Use exact matching only for deterministic fields such as enum values, IDs, or required keys. For prose, define observable criteria. For example, a support answer might need to answer the question, avoid unsupported policy details, cite the supplied document, and ask for missing information when the context is insufficient.
Choose evaluator methods carefully
Programmatic checks are best for schemas, required terms, citation IDs, numeric ranges, and tool arguments. Human review remains valuable for nuanced correctness, tone, and policy-sensitive cases. Model-based graders can help scale rubric checks, but treat their scores as one signal: give them a clear rubric, provide the relevant context, and periodically compare their judgments with human review.
Set release thresholds
Define thresholds before looking at the new run. A release policy might require no schema failures, no regression in high-risk cases, and an acceptable quality score while allowing a bounded latency or cost change. The exact thresholds belong to your application and risk model; they should not be copied from an unrelated benchmark.
Use a matrix to make decisions visible:
| Dimension | Measurement | Release question |
|---|---|---|
| Quality | Rubric score and pass rate | Did task performance improve or remain within tolerance? |
| Format | Schema and tool-call validity | Can downstream code safely consume the result? |
| Grounding | Context support and citation coverage | Are claims traceable to retrieved material? |
| Operations | Latency and token usage | Did performance or estimated cost change materially? |
| Safety | Expected handling of risk cases | Did the application respond according to its requirements? |
Worked examples
Assume a small RAG assistant has 40 regression cases. Thirty cases require citations, 25 require structured JSON output, and all cases record token usage and elapsed time. These numbers are illustrative inputs, not a benchmark.
After a prompt revision, the run produces 38 valid JSON responses, 28 citation-compliant responses, and 34 cases that meet the task rubric. The corresponding rates are:
- Schema validity: 38 ÷ 40 = 95%.
- Citation coverage: 28 ÷ 30 = 93.3%.
- Rubric pass rate: 34 ÷ 40 = 85%.
Those results tell you different things. Fixing JSON formatting may be a parser or prompt issue. The citation gap may indicate retrieval misses, context truncation, or a response that makes claims beyond the supplied evidence. The rubric failures need case-level review before you decide whether the prompt, model, data, or evaluator is responsible.
For cost, suppose the run used 180,000 input tokens and 32,000 output tokens. Your configuration file contains the applicable input and output rates for the selected provider and model, expressed in the provider’s billing unit. Calculate the two components separately, then add any configured retrieval, tool, or platform charges. Comparing the result with the previous run shows whether an apparent quality improvement has an operational tradeoff.
A useful triage record includes:
{
"case_id": "billing_014",
"failure_type": "unsupported_claim",
"severity": "high",
"observed": "The answer states a refund amount not present in policy-12.",
"likely_area": "generation_or_prompt",
"owner": "application-team",
"next_action": "Add a no-invention criterion and rerun retrieval checks."
}Group failures by likely cause rather than patching each answer individually. Common groups include missing context, incorrect document ranking, context-window pressure, ambiguous instructions, invalid tool arguments, evaluator disagreement, and genuine model-quality changes.
When to recalculate
Run the full regression suite whenever you change the model, system prompt, output schema, tool definitions, retrieval index, chunking strategy, embedding configuration, safety logic, or post-processing code. Recalculate cost and latency when token limits, routing, caching, concurrency, provider rates, or usage patterns change.
Also schedule periodic review even when the code is unchanged. Production queries can reveal new intents, stale documents, repeated refusal patterns, or cases missing from the golden dataset. Add representative failures to the dataset only after reviewing sensitive information and removing unnecessary personal or confidential data.
Before release, use this checklist:
- Confirm dataset, prompt, model, index, and evaluator versions are recorded.
- Run deterministic contract checks before subjective quality grading.
- Compare quality by category, not only the overall average.
- Inspect every high-severity failure and a sample of passing cases.
- Recalculate token cost using the current, dated rate configuration.
- Review latency separately for short, long-context, and tool-using cases.
- Document accepted tradeoffs, unresolved failures, and rollback criteria.
After the run, update the evaluation matrix and keep the report with the release artifacts. This turns LLM evaluation in Python into an ongoing engineering control: a practical way to decide whether a prompt revision, model migration, or RAG update is ready for users.