LLM CI/CD: Automated Prompt Regression Testing in Your Pipeline

LLM CI/CD: Automated Prompt Regression Testing in Your Pipeline

Shipping a prompt change without a regression test is the LLM equivalent of deploying code without tests. It feels fine until it catastrophically is not. The discipline of CI/CD — automated tests that gate every change — applies to LLM-powered applications just as much as to traditional software. The implementation is different, but the principle is identical.

This post is a practical, end-to-end guide to building an LLM CI/CD pipeline: GitHub Actions setup, managing evaluation datasets, defining scoring thresholds, generating diff reports, controlling costs, and parallelizing test runs.


The Architecture of an LLM CI/CD Pipeline

A mature LLM CI pipeline has four components:

  1. Evaluation dataset — golden inputs with expected outputs or scoring criteria
  2. Evaluation harness — code that runs the model against the dataset and computes metrics
  3. Baseline storage — persisted results from the last known-good state
  4. CI integration — GitHub Actions (or equivalent) that gates PRs and main branch merges

The flow: on every PR that touches prompts or LLM logic, the CI runs the evaluation harness against the current code, computes metrics, compares to the baseline, and passes or fails the check.


Repository Structure

project/
  prompts/
    classification.py
    summarization.py
    rag_qa.py
  app/
    chains/
    llm_client.py
  eval/
    datasets/
      classification_smoke.jsonl    # 25 samples, fast smoke tests
      classification_full.jsonl     # 200 samples, full regression
      summarization_full.jsonl
      rag_qa_full.jsonl
    baselines/
      classification_main.json      # Updated after each main merge
      summarization_main.json
    scripts/
      run_eval.py                   # Main eval entrypoint
      compare_baseline.py           # Baseline comparison
      generate_report.py            # Markdown report generation
    config/
      thresholds.yaml               # Pass/fail thresholds per metric
  .github/
    workflows/
      llm-regression.yml

Dataset Management

Dataset Format

Use JSONL — one JSON object per line, easy to version, diff, and stream.

{"id":"cls-001","input":"I was charged twice","expected":"billing","tags":["billing","clear"],"added":"2024-01-15","source":"production_sample"}
{"id":"cls-002","input":"App crashes on startup","expected":"technical_issue","tags":["technical","clear"],"added":"2024-01-15","source":"production_sample"}
{"id":"cls-003","input":"Is there a team plan?","expected":"billing","tags":["billing","ambiguous"],"added":"2024-01-20","source":"manual"}

Dataset Versioning

Datasets must be versioned alongside prompts. When you add new samples, create a dated addition commit message. When you update expected outputs because behavior intentionally changed, document why.

# Good commit messages for dataset changes
git commit -m "eval: add 15 ambiguous classification samples from production logs"
git commit -m "eval: update expected outputs for summarization - verbosity threshold relaxed"
git commit -m "eval: remove 3 samples that are genuinely ambiguous (no correct answer)"

Splitting Smoke vs Full Datasets

Smoke datasets run on every PR (fast, cheap). Full datasets run on main merge (comprehensive, thorough).

# eval/scripts/split_dataset.py
import json, random
from pathlib import Path

def create_smoke_split(full_dataset_path: str, n_samples: int = 25, seed: int = 42):
    """
    Create a stratified smoke dataset from the full dataset.
    Ensures all tags/categories are represented.
    """
    with open(full_dataset_path) as f:
        samples = [json.loads(line) for line in f if line.strip()]

    # Group by tag
    by_tag = {}
    for sample in samples:
        for tag in sample.get("tags", ["untagged"]):
            by_tag.setdefault(tag, []).append(sample)

    # Sample proportionally
    selected = set()
    per_tag = max(1, n_samples // len(by_tag))
    random.seed(seed)

    for tag, tag_samples in by_tag.items():
        for s in random.sample(tag_samples, min(per_tag, len(tag_samples))):
            selected.add(s["id"])

    # Fill remaining slots randomly
    remaining = [s for s in samples if s["id"] not in selected]
    random.shuffle(remaining)
    for s in remaining[:max(0, n_samples - len(selected))]:
        selected.add(s["id"])

    smoke_samples = [s for s in samples if s["id"] in selected]

    output_path = full_dataset_path.replace(".jsonl", "_smoke.jsonl")
    with open(output_path, "w") as f:
        for s in smoke_samples:
            f.write(json.dumps(s) + "\n")

    print(f"Smoke dataset: {len(smoke_samples)} samples → {output_path}")

Thresholds and Pass/Fail Criteria

Thresholds should be in configuration, not hardcoded.

# eval/config/thresholds.yaml
classification:
  pass_rate_minimum: 0.90          # Overall pass rate
  pass_rate_regression_delta: -0.05 # Max allowed drop vs baseline
  per_tag_minimum:
    billing: 0.92
    technical_issue: 0.88
    feature_request: 0.80          # Lower bar for genuinely hard category
  latency_p95_ms: 2000

summarization:
  faithfulness_minimum: 0.85
  rouge_l_minimum: 0.40
  pass_rate_regression_delta: -0.03
  latency_p95_ms: 5000

rag_qa:
  faithfulness_minimum: 0.90       # Higher bar since context is provided
  answer_relevance_minimum: 0.80
  pass_rate_regression_delta: -0.05
# eval/scripts/run_eval.py
import yaml
from pathlib import Path

def load_thresholds(suite_name: str) -> dict:
    config_path = Path("eval/config/thresholds.yaml")
    with open(config_path) as f:
        all_thresholds = yaml.safe_load(f)
    return all_thresholds.get(suite_name, {})

def check_thresholds(metrics: dict, thresholds: dict) -> tuple[bool, list[str]]:
    failures = []

    if "pass_rate_minimum" in thresholds:
        if metrics.get("pass_rate", 0) < thresholds["pass_rate_minimum"]:
            failures.append(
                f"Pass rate {metrics['pass_rate']:.1%} < minimum {thresholds['pass_rate_minimum']:.1%}"
            )

    if "faithfulness_minimum" in thresholds:
        if metrics.get("faithfulness", 0) < thresholds["faithfulness_minimum"]:
            failures.append(
                f"Faithfulness {metrics['faithfulness']:.3f} < minimum {thresholds['faithfulness_minimum']:.3f}"
            )

    if "per_tag_minimum" in thresholds:
        for tag, min_rate in thresholds["per_tag_minimum"].items():
            tag_rate = metrics.get(f"pass_rate_{tag}", 1.0)
            if tag_rate < min_rate:
                failures.append(
                    f"Pass rate for '{tag}': {tag_rate:.1%} < minimum {min_rate:.1%}"
                )

    passed = len(failures) == 0
    return passed, failures

GitHub Actions Setup

PR Workflow (Smoke Tests)

# .github/workflows/llm-regression.yml
name: LLM Regression

on:
  pull_request:
    paths:
      - 'prompts/**'
      - 'app/chains/**'
      - 'app/llm_client.py'
      - 'eval/datasets/**'
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      suite:
        description: 'Eval suite to run'
        default: 'all'

jobs:
  smoke-tests:
    name: Smoke Regression (PR)
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    timeout-minutes: 15
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      EVAL_MODEL: gpt-4o-mini
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: pip

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Run classification smoke test
        id: classification
        run: |
          python eval/scripts/run_eval.py \
            --suite classification \
            --dataset eval/datasets/classification_smoke.jsonl \
            --baseline eval/baselines/classification_main.json \
            --output eval/results/classification_pr.json \
            --model $EVAL_MODEL
        continue-on-error: true

      - name: Run summarization smoke test
        id: summarization
        run: |
          python eval/scripts/run_eval.py \
            --suite summarization \
            --dataset eval/datasets/summarization_smoke.jsonl \
            --baseline eval/baselines/summarization_main.json \
            --output eval/results/summarization_pr.json \
            --model $EVAL_MODEL
        continue-on-error: true

      - name: Generate diff report
        run: |
          python eval/scripts/generate_report.py \
            --results eval/results/ \
            --format github \
            >> $GITHUB_STEP_SUMMARY

      - name: Check thresholds
        run: |
          python eval/scripts/check_thresholds.py \
            --results eval/results/ \
            --fail-on-regression

  full-regression:
    name: Full Regression (main)
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    timeout-minutes: 45
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      EVAL_MODEL: gpt-4o
    strategy:
      matrix:
        suite: [classification, summarization, rag_qa]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: '3.11', cache: pip }
      - run: pip install -r requirements.txt

      - name: Run ${{ matrix.suite }} full regression
        run: |
          python eval/scripts/run_eval.py \
            --suite ${{ matrix.suite }} \
            --dataset eval/datasets/${{ matrix.suite }}_full.jsonl \
            --output eval/results/${{ matrix.suite }}_main.json \
            --model $EVAL_MODEL \
            --workers 10

      - name: Update baseline
        run: |
          cp eval/results/${{ matrix.suite }}_main.json \
             eval/baselines/${{ matrix.suite }}_main.json
          git config user.email "ci@yourcompany.com"
          git config user.name "CI"
          git add eval/baselines/${{ matrix.suite }}_main.json
          git commit -m "eval: update ${{ matrix.suite }} baseline [skip ci]" || true
          git push

Parallelization Strategies

LLM API calls are slow. Parallelization is not optional for datasets larger than ~50 samples.

# eval/scripts/run_eval.py
import asyncio
import aiohttp
from asyncio import Semaphore

class AsyncEvalRunner:
    def __init__(self, model: str, max_concurrency: int = 10):
        self.model = model
        self.semaphore = Semaphore(max_concurrency)

    async def run_sample(self, sample: dict, session) -> dict:
        async with self.semaphore:
            async with session.post(
                "https://api.openai.com/v1/chat/completions",
                json={
                    "model": self.model,
                    "messages": build_messages(sample["input"]),
                    "temperature": 0
                },
                headers={"Authorization": f"Bearer {OPENAI_API_KEY}"}
            ) as response:
                data = await response.json()
                output = data["choices"][0]["message"]["content"]
                return {"id": sample["id"], "input": sample["input"], "output": output}

    async def run_dataset(self, samples: list[dict]) -> list[dict]:
        async with aiohttp.ClientSession() as session:
            tasks = [self.run_sample(s, session) for s in samples]
            return await asyncio.gather(*tasks, return_exceptions=False)

def run_parallel_eval(samples: list[dict], model: str, workers: int = 10) -> list[dict]:
    runner = AsyncEvalRunner(model=model, max_concurrency=workers)
    return asyncio.run(runner.run_dataset(samples))

For 200 samples with 10 concurrent workers, total runtime drops from ~200 seconds sequential to ~20–30 seconds.


Cost Management

Uncontrolled LLM API costs in CI can become significant. Practical controls:

Use Cheaper Models for Smoke Tests

MODEL_CONFIG = {
    "smoke": {
        "generation": "gpt-4o-mini",      # $0.15/1M input tokens
        "evaluation": "gpt-4o-mini",       # Fast, cheap, good enough for smoke
    },
    "full": {
        "generation": "gpt-4o",            # $2.50/1M input tokens
        "evaluation": "gpt-4o",            # Higher quality evaluation
    },
    "nightly": {
        "generation": "gpt-4o",
        "evaluation": "gpt-4o",
    }
}

Estimate and Cap Costs Before Running

def estimate_eval_cost(
    samples: list[dict],
    model: str,
    avg_input_tokens: int = 200,
    avg_output_tokens: int = 100
) -> dict:
    PRICING = {
        "gpt-4o": {"input": 0.0025, "output": 0.010},      # per 1K tokens
        "gpt-4o-mini": {"input": 0.00015, "output": 0.0006}
    }
    prices = PRICING.get(model, PRICING["gpt-4o-mini"])
    n = len(samples)
    input_cost = (n * avg_input_tokens / 1000) * prices["input"]
    output_cost = (n * avg_output_tokens / 1000) * prices["output"]

    return {
        "n_samples": n,
        "estimated_input_tokens": n * avg_input_tokens,
        "estimated_cost_usd": round(input_cost + output_cost, 4)
    }

# In CI: fail if estimated cost exceeds budget
estimate = estimate_eval_cost(samples, model)
if estimate["estimated_cost_usd"] > MAX_COST_USD:
    raise ValueError(
        f"Eval cost estimate ${estimate['estimated_cost_usd']:.2f} "
        f"exceeds budget ${MAX_COST_USD:.2f}. "
        f"Use smoke dataset or cheaper model."
    )

Cache Unchanged Inputs

If the input has not changed, do not re-run it. Use a hash of the prompt template + input as a cache key.

import hashlib, json
from pathlib import Path

CACHE_DIR = Path(".eval_cache")

def get_cache_key(model: str, prompt_version: str, input_text: str) -> str:
    content = f"{model}:{prompt_version}:{input_text}"
    return hashlib.sha256(content.encode()).hexdigest()[:16]

def cached_inference(model: str, prompt_version: str, input_text: str, call_fn) -> str:
    CACHE_DIR.mkdir(exist_ok=True)
    key = get_cache_key(model, prompt_version, input_text)
    cache_file = CACHE_DIR / f"{key}.json"

    if cache_file.exists():
        return json.loads(cache_file.read_text())["output"]

    output = call_fn(input_text)
    cache_file.write_text(json.dumps({"output": output, "model": model}))
    return output

Generating Diff Reports

When a regression is detected, the report must tell the developer exactly what changed.

def generate_pr_report(
    current_results: list[dict],
    baseline_results: list[dict],
    suite_name: str
) -> str:
    baseline_by_id = {r["id"]: r for r in baseline_results}
    current_by_id = {r["id"]: r for r in current_results}

    regressions = []
    improvements = []

    for id_, curr in current_by_id.items():
        base = baseline_by_id.get(id_)
        if not base:
            continue
        if base["passed"] and not curr["passed"]:
            regressions.append((id_, base, curr))
        elif not base["passed"] and curr["passed"]:
            improvements.append((id_, base, curr))

    lines = [f"## {suite_name} Eval Report", ""]

    pass_rate_curr = sum(1 for r in current_results if r["passed"]) / len(current_results)
    pass_rate_base = sum(1 for r in baseline_results if r["passed"]) / len(baseline_results)
    delta = pass_rate_curr - pass_rate_base
    delta_str = f"{delta:+.1%}"
    status = "PASSED" if delta >= -0.05 else "FAILED"

    lines += [
        f"**Status: {status}**  ",
        f"Pass rate: {pass_rate_base:.1%} → {pass_rate_curr:.1%} ({delta_str})",
        ""
    ]

    if regressions:
        lines.append(f"### Regressions ({len(regressions)})")
        lines.append("")
        for id_, base, curr in regressions[:5]:
            lines += [
                f"**`{id_}`**",
                f"- Input: `{curr['input'][:80]}`",
                f"- Expected: `{curr.get('expected', 'N/A')}`",
                f"- Baseline output: `{base.get('output', '')[:100]}`",
                f"- Current output: `{curr.get('output', '')[:100]}`",
                ""
            ]

    if improvements:
        lines.append(f"### Improvements ({len(improvements)})")
        for id_, _, curr in improvements[:3]:
            lines.append(f"- `{id_}`: now passing")

    return "\n".join(lines)

End-to-End Integration

LLM CI/CD covers model-level quality. For teams building full-stack AI applications, the end-to-end user experience also needs testing. A user interacts with a UI that calls your LLM chain — that interaction path can break in ways your eval pipeline would never catch: layout issues, response rendering bugs, streaming failures, or error state handling.

HelpMeTest bridges this gap: its usage-based pricing ($0.003 per test run, no base fee) lets you run automated end-to-end tests against your full application stack using Robot Framework and Playwright, with AI-powered test generation that understands natural language. Your LLM eval pipeline catches quality regressions at the model layer; HelpMeTest catches regressions at the application layer. Together, they give you complete coverage.


Summary

A mature LLM CI/CD pipeline requires deliberate engineering, but it pays for itself the first time it catches a prompt regression before it ships.

The key components:

  1. Versioned golden datasets — stratified, tagged, with smoke and full splits
  2. Configuration-driven thresholds — per metric, per category, with delta limits vs baseline
  3. GitHub Actions integration — smoke tests on PR, full regression on main, nightly drift detection
  4. Parallelization — async API calls with concurrency control for reasonable runtimes
  5. Cost management — cheaper models for smoke, estimation gates, output caching
  6. Human-readable diff reports — exact samples that regressed, not just aggregate metrics

The investment is a few days of engineering. The return is confidence that every prompt change, model update, or dependency bump that affects LLM quality is caught automatically — before users notice.

Read more

Start now free