Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Workflow recipe

Evaluate RAG answers with a golden dataset

Set up RAG evaluation with a golden dataset and promptfoo: score retrieval, correctness and grounding for every question, and fail CI when answer quality drops.

By Checked Intermediate2 h6 steps
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On this page

To evaluate RAG with a golden dataset, label a fixed set of questions with expected answers and sources, wrap your pipeline as a promptfoo provider, and score every question on three separate checks: retrieval, correctness and grounding. Check the model grader against your own judgement, then run the eval in CI so a quality drop fails the build.

A golden dataset is a fixed list of questions with known good answers. Run your pipeline on it after every change and you can tell whether the change helped, instead of judging from the three questions you happened to try.

This recipe turns the 20-question set from the RAG pipeline in a day recipe into an automated eval with promptfoo, an open source eval runner. It checks three things for every question, separately, because they fail for different reasons:

  • retrieval: did the expected source file come back?
  • correctness: does the answer agree with the expected answer?
  • grounding: is every claim in the answer supported by the retrieved text?

The examples assume the ask.py and eval.jsonl files from that recipe. Adapt the provider in step 2 if your pipeline looks different.

EditorAbout 30 min

1. Grow and label the golden set

Twenty questions is a start. Aim for 30 to 50 before you trust the numbers, and label each with a category so you can see where failures cluster: simple lookup, needs two passages, numbers and dates, unanswerable.

Convert eval.jsonl into a promptfoo test file. YAML accepts JSON objects, so a short script is enough:

import json

with open("eval.jsonl", encoding="utf-8") as src, open("golden.yaml", "w", encoding="utf-8") as out:
    for line in src:
        if not line.strip():
            continue
        row = json.loads(line)
        test = {
            "description": row["question"][:60],
            "vars": {
                "query": row["question"],
                "expected_source": row["expected_source"],
                "expected_answer": row["expected_answer"],
            },
        }
        out.write("- " + json.dumps(test, ensure_ascii=False) + "\n")
python make_golden.py

Commit golden.yaml. From now on, changing the golden set is a reviewed change like any other.

EditorAbout 10 min

2. Wrap the pipeline as a promptfoo provider

promptfoo can call a Python file directly. It imports the file and calls call_api(prompt, options, context) for each test. Return the answer as output and put the retrieved sources and chunks in metadata, where the assertions can read them.

from ask import answer


def call_api(prompt, options, context):
    try:
        result = answer(prompt)
    except Exception as exc:  # report pipeline errors as test errors, not crashes
        return {"error": f"{type(exc).__name__}: {exc}"}

    return {
        "output": result["answer"],
        "metadata": {
            "sources": [h["source"] for h in result["hits"]],
            "chunks": [h["content"] for h in result["hits"]],
        },
    }

EditorAbout 20 min

3. Write the eval config with three checks

description: RAG golden set

prompts:
  - "{{query}}"

providers:
  - id: file://rag_provider.py
    config:
      pythonExecutable: ./.venv/bin/python

defaultTest:
  options:
    # Model used by the model-graded checks below
    provider: anthropic:messages:claude-opus-5-5
  assert:
    # 1. Retrieval: the expected file is among the retrieved sources
    - type: javascript
      metric: retrieval
      value: "!context.vars.expected_source || context.metadata.sources.includes(context.vars.expected_source)"

    # 2. Correctness: the answer agrees with the reference answer
    - type: factuality
      metric: correctness
      value: "{{expected_answer}}"

    # 3. Grounding: claims in the answer are supported by retrieved chunks
    - type: context-faithfulness
      metric: grounding
      contextTransform: "context.metadata.chunks"
      threshold: 0.8

tests: file://golden.yaml

The javascript check is deterministic and free. The other two use a model as the grader. factuality compares the answer with your reference; context-faithfulness extracts the claims in the answer and checks each against the retrieved text, scoring the share that are supported.

TerminalAbout 20 min

4. Run it and read the failures

npx promptfoo@latest eval
npx promptfoo@latest view    # opens the local results viewer

Read every failure, grouped by metric:

  • A retrieval failure means the pipeline never saw the right text. Fix ingestion or search; prompt changes will not help.
  • Retrieval passed but correctness failed: the model misread the passage, or your reference answer is wrong. Check the reference first.
  • Correctness passed but grounding failed: the answer is right by luck or from general knowledge. That is a risk for questions your documents answer differently from the internet.

Write down the pass rate per metric. This is your baseline.

SpreadsheetAbout 20 min

5. Check the grader against your own judgement

A model grader is a measuring instrument, so calibrate it. Take 10 results, mark each yourself as correct or not without looking at the grader’s verdict, then compare.

If you disagree on more than one or two, change something before trusting the eval: make the reference answers more precise, split compound questions, or replace factuality with an llm-rubric assertion that spells out what “correct” means for your domain. Re-check after each change.

GitHub ActionsAbout 20 min

6. Run it in CI and fail on regressions

promptfoo exits with code 100 when tests fail. PROMPTFOO_PASS_RATE_THRESHOLD lets you allow a small number of failures, since model-graded checks are not perfectly stable. Set it a little below your baseline.

name: RAG eval

on:
  pull_request:
    paths:
      - "ask.py"
      - "common.py"
      - "ingest.py"
      - "docs/**"
      - "golden.yaml"
      - "promptfooconfig.yaml"

jobs:
  eval:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: pgvector/pgvector:pg17
        env:
          POSTGRES_PASSWORD: rag
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
    env:
      DATABASE_URL: postgresql://postgres:rag@localhost:5432/postgres
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
      PROMPTFOO_PASS_RATE_THRESHOLD: "90"
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-python@v6
        with:
          python-version: "3.12"
      - uses: actions/setup-node@v6
        with:
          node-version: "22"
      - run: python -m venv .venv && .venv/bin/pip install -r requirements.txt
      - run: PGPASSWORD=rag psql -h localhost -U postgres -f schema.sql
      - run: .venv/bin/python ingest.py ./docs
      - run: npx promptfoo@latest eval -o results.json
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: rag-eval-results
          path: results.json

Create requirements.txt with the packages from the pipeline (docling, psycopg[binary], pgvector, numpy, openai, anthropic), and add the two API keys as repository secrets.

Check it worked

Verification checklist

0 of 6 done

When it goes wrong

If every test errors, run python -c "from rag_provider import call_api; print(call_api('test', {}, {}))" inside the virtual environment. Import errors and missing environment variables show up there with a readable message.

If context.metadata is undefined in the JavaScript check, the provider is not returning metadata, often because an exception path returned early. Check the error text in the viewer.

If scores move between runs with no code change, the model-graded checks are varying. Keep the threshold a few points below the baseline, and look at trends over several runs before acting on a small drop.

If the CI run is slow, ingestion is the likely cause. Ingest a small fixed subset of documents in CI (the files your golden questions reference), and run the full ingest elsewhere.

Variations

Ragas is a Python library with RAG metrics such as faithfulness and context precision, which some teams prefer to keep everything in Python. The principle is the same: a fixed dataset, separate retrieval and answer metrics, a calibrated grader and a threshold in CI. Check the current Ragas documentation for its API, which has changed between major versions.

To compare two pipeline versions side by side, add a second provider entry pointing at another file (for example rag_provider_v2.py). promptfoo runs every test against both and shows the results in adjacent columns.

When the model behind the feature is retired or replaced, the same golden set is your regression test: move an app to a new model without regressions runs the old and new models side by side on it.

With a golden set of a few dozen questions, a change of one or two passes can be noise. The Statistical analysis skill gives an agent the method for deciding whether a difference between two runs is real, and Explore data profiles the golden set itself (duplicates, empty expected answers, questions bunched on one document) before you trust its scores.

Your first LLM eval covers the basics, LLM-as-a-judge explains how to calibrate the grader from step 5, and evals in CI with promptfoo goes further on the CI gate. When answers fail for reasons a golden set cannot show, start with error analysis. To match a failing case to its likely cause, keep the RAG troubleshooting cheat sheet open. The RAG engineer learning path ties these together, and more recipes are in the AI workflow examples hub.

Outcome and tools

Outcome
A repeatable eval that fails CI when answer quality drops.
For
Developers, ML engineers
  • RAG pipeline in a day with Postgres and pgvector

    Ingest your documents, answer with citations and measure retrieval against 20 questions written first.

    WorkflowIntermediate1 day7 steps

  • Write your first LLM eval

    Turn real outputs into a small test set, add code-based checks in promptfoo and run them in CI to catch regressions on every change.

    TutorialBeginner40 min

  • LLM-as-a-judge: grading outputs you can trust

    Write narrow grading criteria, check the judge's verdicts against your own labels and decide when its agreement is good enough.

    TutorialIntermediate45 min

  • Eval

    A repeatable test that measures how well an AI system performs on a defined set of cases, so you can compare versions instead of guessing.

    Glossary

  • LLM-as-a-judge

    Using a model to grade another model's outputs against written criteria, ideally checked against a sample of human-labelled cases.

    Glossary

Back to top