Skip to main content
Back to all articles
AI Engineering 7 min readUpdated August 31, 2026

Put LLM Evals in CI Before Prompt Changes Become Production Incidents

LLM behavior is probabilistic, but releases still need regression gates. This article builds a versioned evaluation dataset, deterministic checks, model-assisted scoring, confidence-aware thresholds, and CI policies for RAG and agent changes.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#llm-evals#continuous-integration#rag#ai-agents#regression-testing#typescript#python
On this page

Changing one prompt line can improve five examples and quietly break twelve others.

The same is true when you switch models, adjust retrieval, rename a tool, change a JSON Schema, or compact context differently. AI systems have more probabilistic behavior than ordinary application code, but that does not make regression testing optional. It makes the test boundary more important.

I do not expect an LLM evaluation suite to tell me whether a build is mathematically “correct.” I expect it to answer a practical release question:

Did this change make the behaviors we care about meaningfully worse?

The example here is a customer-support RAG agent that retrieves policy documents, answers with citations, and can use read-only account tools. The evaluation design separates deterministic contract checks from graded quality checks so a fuzzy judge is not deciding things application code can verify exactly.

Build cases from real failure modes

A good eval dataset is not a collection of polished demo prompts.

I want cases that represent the distribution and the edges we actually care about:

TypeScript
type EvalCase = {  id: string;  input: string;  tags: string[];  expected: {    requiredSourceIds?: string[];    forbiddenToolNames?: string[];    allowedToolNames?: string[];    mustAbstain?: boolean;    requiredFacts?: string[];  };};

Useful tags might include:

  • exact-identifier;
  • multi-document;
  • missing-evidence;
  • prompt-injection;
  • tool-selection;
  • authorization;
  • long-context;
  • ambiguous-user-intent.

Tags become important later because an overall score can hide a catastrophic regression in one small class.

I seed the dataset from production failures, QA cases, manually written edge cases, and representative normal requests. Synthetic cases can expand coverage, but I do not want a suite made entirely from one model generating tests for another model.

Version the run configuration

An eval result without its configuration is difficult to reproduce.

TypeScript
type EvalRunConfig = {  appVersion: string;  promptVersion: string;  retrievalVersion: string;  toolSchemaVersion: string;  model: string;  temperature: number;  datasetVersion: string;};

For model providers that support deterministic seeds or other reproducibility controls, use them where appropriate—but do not assume they eliminate nondeterminism.

I store the exact configuration next to every result so “the score dropped last Tuesday” can be connected to a concrete change.

Evaluate deterministic contracts first

Some failures need no judge model.

If the agent called a forbidden tool, produced invalid structured output, cited a nonexistent source ID, exceeded a tool-call budget, or failed to abstain when no evidence was retrieved, ordinary code can score that.

TypeScript
type AgentRunResult = {  answer: string;  citedSourceIds: string[];  toolCalls: Array<{ name: string; args: unknown }>;  abstained: boolean;};​type DeterministicScore = {  passed: boolean;  failures: string[];};​function scoreContracts(  test: EvalCase,  result: AgentRunResult,): DeterministicScore {  const failures: string[] = [];​  const forbidden = new Set(test.expected.forbiddenToolNames ?? []);  for (const call of result.toolCalls) {    if (forbidden.has(call.name)) {      failures.push(`forbidden tool called: ${call.name}`);    }  }​  for (const sourceId of result.citedSourceIds) {    if (!sourceRegistry.has(sourceId)) {      failures.push(`unknown citation: ${sourceId}`);    }  }​  if (test.expected.mustAbstain === true && !result.abstained) {    failures.push("expected abstention");  }​  return { passed: failures.length === 0, failures };}

These checks are cheap, explainable, and stable. They should not be delegated to an LLM judge.

Measure retrieval separately from answer quality

If the agent gives a wrong answer because the correct document was never retrieved, generation scoring alone will not tell you where the regression came from.

For RAG cases I record retrieval metrics such as:

  • relevant-source recall@K;
  • MRR for single-best-evidence tasks;
  • duplicate chunk rate;
  • unauthorized result count;
  • stale-document selection.

A retrieval change can then fail CI even if a lucky generator still answers some cases correctly from weak evidence.

The same separation applies to tool agents: candidate-tool recall and final tool selection can be measured independently.

Use a rubric for genuinely semantic quality

Some properties cannot be reduced to string equality.

For support answers I may score:

  • factual correctness against supplied evidence;
  • completeness of the requested answer;
  • unsupported-claim rate;
  • whether uncertainty is communicated appropriately;
  • whether the response follows the requested format.

I keep the rubric narrow and observable.

This is better:

Text
Score factual support from 0–2.2: every material factual claim is supported by the supplied evidence.1: mostly supported, but contains one minor unsupported or overstated claim.0: contains a material claim contradicted by or absent from the evidence.

than this:

Text
Is this a high-quality answer? Score 1–10.

A vague rubric asks the judge to invent your product requirements.

Keep judge output structured

TypeScript
type JudgeScore = {  factualSupport: 0 | 1 | 2;  completeness: 0 | 1 | 2;  notes: string;};​interface Judge {  score(input: {    question: string;    evidence: string[];    answer: string;    rubricVersion: string;  }): Promise<JudgeScore>;}

The judge should see only the material necessary for the rubric. If I am judging grounding, I do not include a reference answer full of facts that were not in the evidence because the judge may reward an unsupported answer for matching it.

Judge design gets its own failure modes, which I cover separately later in the series.

Python runner

Python
from dataclasses import dataclassfrom statistics import mean​@dataclass(frozen=True)class CaseScore:    case_id: str    contract_passed: bool    quality_score: float    latency_ms: float    input_tokens: int    output_tokens: int​@dataclass(frozen=True)class EvalSummary:    pass_rate: float    mean_quality: float    p95_latency_ms: float    total_tokens: int​​def percentile(values: list[float], fraction: float) -> float:    if not values:        return 0.0    ordered = sorted(values)    index = min(len(ordered) - 1, int((len(ordered) - 1) * fraction))    return ordered[index]​​def summarize(scores: list[CaseScore]) -> EvalSummary:    return EvalSummary(        pass_rate=sum(item.contract_passed for item in scores) / len(scores),        mean_quality=mean(item.quality_score for item in scores),        p95_latency_ms=percentile([item.latency_ms for item in scores], 0.95),        total_tokens=sum(            item.input_tokens + item.output_tokens for item in scores        ),    )

For an empty dataset I would fail the runner before calling summarize; a CI gate with zero cases should not report a cheerful 100%.

Compare candidate against a baseline

Absolute thresholds are useful for hard requirements. Relative comparison catches regressions in a system whose raw judge score is not perfectly calibrated.

TypeScript
type GateInput = {  baseline: EvalSummary;  candidate: EvalSummary;};​function evaluateGate({ baseline, candidate }: GateInput): string[] {  const failures: string[] = [];​  if (candidate.passRate < 0.98) {    failures.push("contract pass rate below 98%");  }​  if (candidate.meanQuality < baseline.meanQuality - 0.05) {    failures.push("mean quality regressed by more than 0.05");  }​  if (candidate.p95LatencyMs > baseline.p95LatencyMs * 1.2) {    failures.push("p95 latency regressed by more than 20%");  }​  if (candidate.totalTokens > baseline.totalTokens * 1.25) {    failures.push("evaluation token usage increased by more than 25%");  }​  return failures;}

Those thresholds are examples, not universal defaults. A production team should set them from business risk, natural eval variance, and cost/latency goals.

One aggregate score is dangerous

Suppose 95 ordinary cases improve slightly and five authorization cases all regress. The mean quality score may still rise.

I gate critical slices independently:

TypeScript
type SliceSummary = {  tag: string;  cases: number;  passRate: number;};

Security, side-effect safety, schema validity, and tenant isolation often deserve near-zero tolerance even when stylistic quality can move a little.

A release decision might therefore require:

  • overall quality not worse than baseline beyond tolerance;
  • 100% pass on known cross-tenant isolation cases;
  • 100% pass on forbidden-tool cases;
  • retrieval recall above a minimum;
  • latency/cost within budget.

Different risks deserve different gates.

Run repeated trials where variance matters

A single sample per case can be noisy.

For a low-temperature structured extraction task, one run may be enough for fast CI. For open-ended agent trajectories, I may run multiple trials on a smaller critical set and look at the distribution.

The CI budget does not need to match the nightly research suite.

I often split evaluation into:

pull-request suite — small, fast, high-signal regression set;

nightly suite — larger dataset, repeated trials, multiple models/configurations;

pre-release suite — production-like traffic slices and cost/latency checks.

That keeps developers from disabling evals because every prompt edit takes an hour to validate.

Cache what can safely be cached in eval infrastructure

Running the same retrieval corpus and deterministic preprocessing repeatedly is wasteful.

I cache embeddings, static document preprocessing, and other versioned deterministic artifacts. I do not reuse model outputs across candidate configurations when the model/prompt behavior is the thing being evaluated.

Every cache key should include the versions that affect its result.

Otherwise the evaluation suite can quietly compare a new generator against old retrieval output and tell you everything is fine.

Store traces for failures

A red CI check that says quality=0.71 < 0.75 is not actionable.

For every failed case I want enough material to inspect:

  • input;
  • retrieved source IDs/scores;
  • selected tools and arguments;
  • model output;
  • deterministic failures;
  • judge rubric/result;
  • latency/token breakdown;
  • configuration versions.

I do not dump secrets into CI artifacts. Sensitive inputs need the same redaction and access controls as production traces.

A good eval failure should lead a developer to the relevant stage in minutes.

Add production failures back into the suite

The evaluation dataset is not finished when the first release ships.

When production exposes a meaningful failure:

  1. reproduce it in a sanitized test case;
  2. add it to the appropriate slice;
  3. confirm the current version fails;
  4. implement the fix;
  5. confirm the case and neighboring cases pass.

That is the same regression-testing habit used in ordinary software engineering.

The difference is that the assertion may be a rubric or trajectory constraint rather than one exact output string.

Avoid turning the golden set into prompt training data

If developers repeatedly read the same 50 cases and tune prompts directly against them, the suite becomes less predictive.

I keep a visible development set and a less frequently inspected holdout set where practical. For high-stakes behavior, periodic human review of fresh production-like samples helps detect overfitting.

The objective is not to get a perfect score on one spreadsheet. It is to estimate how the system behaves on requests it has not been hand-tuned around.

Do not fail CI on judge noise you have never measured

Before choosing a threshold such as “0.02 quality drop fails the build,” run the same configuration several times and see how much the score naturally moves.

If identical builds fluctuate by 0.04, a 0.02 gate creates random failures.

You can reduce noise with more cases, repeated sampling, clearer rubrics, paired comparisons, or human-calibrated deterministic checks.

Thresholds need an error model, not optimism.

When CI evals are overkill

A prototype with three users and no consequential actions may not need an elaborate evaluation platform.

But once model changes ship regularly, manual spot-checking scales badly. The first useful suite can be small: twenty or thirty cases representing core behavior and past failures, plus deterministic schema/tool/security assertions.

The important step is to make AI behavior part of the release contract.

Unit tests tell me whether the normal code around the model still works. LLM evals tell me whether the probabilistic component still behaves within the product boundaries we care about.

Both belong in engineering—not in a final manual demo after the deployment is already waiting.

KEEP READING

Related engineering notes