Prisma
GuidesCookbooks

CI/CD Quality Gates

Catch LLM regressions before they ship — generate fresh answers on every pull request, validate them with Prisma, and block the merge when quality drops.

A prompt edit that looks harmless can quietly raise your hallucination rate. This cookbook turns that into a build failure: on every pull request, generate answers from your current model and prompt against a golden question set, validate them with Prisma's synchronous evaluation API, and block the merge if the pass rate falls below your bar.

What you'll build

A gate script that loads a golden Q&A set, generates a fresh answer for each question, scores them with the built-in correctness and hallucination evaluators in one synchronous call, and exits non-zero when either pass rate drops below threshold — wired into both GitHub Actions and pytest.

Before you start

  • Python 3.10+, a Prisma API key (pq_prisma_sk_…), your workspace ID and project ID, and an OpenAI API key.
  • The synchronous endpoint runs the built-in evaluators. To gate on a custom policy metric, see Gate on a policy metric.
pip install httpx openai pytest

In CI, store the credentials as repository secrets:

export PALQEE_PRISMA_API_KEY="pq_prisma_sk_…"
export PALQEE_PRISMA_BASE_URL="https://prisma.your-company.com"
export PALQEE_PRISMA_WORKSPACE_ID="your-workspace-id"
export PALQEE_PRISMA_PROJECT_ID="your-project-id"
export OPENAI_API_KEY="sk-…"

Step 1 — Build a golden dataset

A golden dataset is a curated set of questions with known-good reference answers — the behaviors your assistant must get right. Keep it small (10–15) so the gate runs fast, and focus on the high-value, regulated paths. Save as tests/eval/golden_dataset.json:

[
  {
    "query": "What is the early-withdrawal penalty on a 12-month CD?",
    "reference": "A 12-month CD incurs an early-withdrawal penalty of 90 days of interest."
  },
  {
    "query": "How long does a credit-card dispute take to investigate?",
    "reference": "Credit-card disputes are investigated under Regulation Z; provisional credit is issued within 10 business days and the investigation can take up to 90 days."
  },
  {
    "query": "What is required to wire more than $10,000 internationally?",
    "reference": "International wires over $10,000 require enhanced due diligence, OFAC screening, and documentation of the purpose and recipient relationship."
  },
  {
    "query": "Can an agent disclose an account balance before verifying identity?",
    "reference": "No. Account information must not be disclosed until identity is verified with at least two factors."
  },
  {
    "query": "What APR disclosures are mandatory before a credit-card application?",
    "reference": "Agents must disclose the post-promotional APR, the annual fee, and the balance-transfer fee before processing an application (TILA Schumer Box)."
  },
  {
    "query": "How long are audit logs retained after account closure?",
    "reference": "Customer data is deleted within 90 days of account closure; audit logs are retained for a minimum of 7 years."
  }
]

Step 2 — Write the gate script

The script generates a response for each question, sends all records to POST /api/v1/evaluations/evaluate in one call, and computes the pass rate per evaluator from the returned labels. The response is a flat results array — each item's evaluations maps the evaluator name to its label (correctness → correct / incorrect / ambiguous; hallucination → factual / hallucinated / ambiguous). There's no server-side summary, so you compute the rates — which keeps the thresholds versioned in your repo.

Save as tests/eval/gate.py:

"""CI/CD quality gate — generate answers, validate with Prisma, enforce thresholds."""

import json, os, sys
from pathlib import Path

import httpx
from openai import OpenAI

DATASET = Path(__file__).parent / "golden_dataset.json"
LLM_MODEL = "gpt-4o"
SYSTEM_PROMPT = "You are a financial-services support assistant. Answer concisely and accurately."

# Pass = this label, for each evaluator. Both rates must clear the threshold.
PASS_LABEL = {"correctness": "correct", "hallucination": "factual"}
THRESHOLDS = {"correctness": 0.90, "hallucination": 0.90}


def generate_answers(dataset: list[dict]) -> list[dict]:
    """Run each golden question through the current model + prompt."""
    oai = OpenAI()
    records = []
    for item in dataset:
        completion = oai.chat.completions.create(
            model=LLM_MODEL,
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": item["query"]},
            ],
            max_tokens=256,
        )
        records.append({
            "query": item["query"],
            "response": completion.choices[0].message.content,
            "reference": item["reference"],
        })
    return records


def evaluate(records: list[dict]) -> list[dict]:
    """Score the records synchronously with the built-in evaluators."""
    resp = httpx.post(
        f"{os.environ['PALQEE_PRISMA_BASE_URL']}/api/v1/evaluations/evaluate",
        headers={"X-API-Key": os.environ["PALQEE_PRISMA_API_KEY"]},
        json={
            "workspace_id": os.environ["PALQEE_PRISMA_WORKSPACE_ID"],
            "project_id": os.environ["PALQEE_PRISMA_PROJECT_ID"],
            "evaluators": [{"name": "correctness"}, {"name": "hallucination"}],
            "data": records,
        },
        timeout=180.0,
    )
    resp.raise_for_status()
    return resp.json()["results"]


def pass_rates(results: list[dict]) -> dict[str, float]:
    n = len(results) or 1
    return {
        ev: sum(1 for r in results if r["evaluations"].get(ev) == good) / n
        for ev, good in PASS_LABEL.items()
    }


def main() -> int:
    dataset = json.loads(DATASET.read_text())
    print(f"Loaded {len(dataset)} golden cases")

    results = evaluate(generate_answers(dataset))
    rates = pass_rates(results)

    failed = False
    for ev, threshold in THRESHOLDS.items():
        rate = rates[ev]
        ok = rate >= threshold
        failed |= not ok
        print(f"  {'PASS' if ok else 'FAIL'} {ev}: {rate:.0%} (threshold {threshold:.0%})")

    print("\nQUALITY GATE", "FAILED" if failed else "PASSED")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())

Step 3 — Tune the thresholds

EvaluatorPass labelGate
correctnesscorrectrate ≥ 0.90
hallucinationfactualrate ≥ 0.90
  • Start permissive, tighten over time. Begin at 0.80 and raise it as the pipeline matures.
  • Split by environment. Staging might gate at 0.85, production at 0.95.
  • Watch the trend. A correctness rate sliding from 0.98 to 0.91 still passes but signals a regression worth a look — log the rates over time.
  • Mind ambiguous. A label that's neither the pass value nor a clear failure counts against the rate; a rising ambiguous share means the golden references need sharpening.

Step 4 — Wire it into GitHub Actions

Run the gate on PRs that touch model-facing code, and block the merge on failure.

name: LLM Quality Gate

on:
  pull_request:
    paths:
      - "prompts/**"
      - "src/**"
      - "tests/eval/**"

jobs:
  llm-eval:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install httpx openai
      - name: Run quality gate
        env:
          PALQEE_PRISMA_BASE_URL: ${{ secrets.PALQEE_PRISMA_BASE_URL }}
          PALQEE_PRISMA_API_KEY: ${{ secrets.PALQEE_PRISMA_API_KEY }}
          PALQEE_PRISMA_WORKSPACE_ID: ${{ secrets.PALQEE_PRISMA_WORKSPACE_ID }}
          PALQEE_PRISMA_PROJECT_ID: ${{ vars.PALQEE_PRISMA_PROJECT_ID }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: python tests/eval/gate.py

To make it blocking, add llm-eval as a required status check under Settings → Branches → Branch protection rules.

Step 5 — Or run it as a pytest check

To see the gate alongside your other tests, assert on the same rates:

import json, os
from pathlib import Path

import httpx, pytest
from openai import OpenAI

DATASET = Path(__file__).parent / "golden_dataset.json"


@pytest.fixture(scope="module")
def results():
    oai = OpenAI()
    records = []
    for item in json.loads(DATASET.read_text()):
        completion = oai.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are a financial-services support assistant. Answer concisely and accurately."},
                {"role": "user", "content": item["query"]},
            ],
            max_tokens=256,
        )
        records.append({
            "query": item["query"],
            "response": completion.choices[0].message.content,
            "reference": item["reference"],
        })

    resp = httpx.post(
        f"{os.environ['PALQEE_PRISMA_BASE_URL']}/api/v1/evaluations/evaluate",
        headers={"X-API-Key": os.environ["PALQEE_PRISMA_API_KEY"]},
        json={
            "workspace_id": os.environ["PALQEE_PRISMA_WORKSPACE_ID"],
            "project_id": os.environ["PALQEE_PRISMA_PROJECT_ID"],
            "evaluators": [{"name": "correctness"}, {"name": "hallucination"}],
            "data": records,
        },
        timeout=180.0,
    )
    resp.raise_for_status()
    return resp.json()["results"]


def _rate(results, evaluator, good):
    return sum(1 for r in results if r["evaluations"].get(evaluator) == good) / len(results)


def test_correctness_rate(results):
    rate = _rate(results, "correctness", "correct")
    assert rate >= 0.90, f"correctness {rate:.0%} below 90%"


def test_grounding_rate(results):
    rate = _rate(results, "hallucination", "factual")
    assert rate >= 0.90, f"grounding {rate:.0%} below 90%"

Skip these when credentials aren't present (local dev) via conftest.py:

import os, pytest


def pytest_collection_modifyitems(config, items):
    if not os.environ.get("PALQEE_PRISMA_API_KEY"):
        skip = pytest.mark.skip(reason="PALQEE_PRISMA_API_KEY not set")
        for item in items:
            if "eval" in str(item.fspath):
                item.add_marker(skip)

Expected output

Loaded 6 golden cases
  PASS correctness: 100% (threshold 90%)
  FAIL hallucination: 83% (threshold 90%)

QUALITY GATE FAILED

The script exits 1, the Actions step fails, and the merge is blocked until the regression is fixed.

Gate on a policy metric

The synchronous endpoint runs the built-in correctness and hallucination evaluators only — any other name (including a custom metric) is skipped. To gate on a custom policy metric you authored with Evaluators.custom(), run the golden set through the batch job path instead: create a run with the metric attached, upload the dataset, and create a job against that run. Read the per-record outcomes back from the run, then apply the same threshold logic. The Files & Jobs endpoints are in the API reference; the policy metric itself is in Policy Metrics.

Project layout

your-repo/
├── .github/workflows/llm-quality-gate.yml   # Actions workflow
└── tests/eval/
    ├── conftest.py            # skip when creds absent
    ├── gate.py                # standalone gate script
    ├── golden_dataset.json    # curated cases
    └── test_llm_quality.py    # pytest integration

Use gate.py for a single pass/fail step, or the pytest version when you already run pytest in CI — both call the same endpoint and enforce the same rates.

Next steps

On this page