Module 5 · Industrialization

Automated evaluations with Promptfoo

7 min read

Throughout this course, every technique has been judged on numbers: 0.55 → 0.89 for examples, 0.18 → 0.57 for the chain. These measurements are not one-offs: every prompt change, every model switch can improve one case and break three. An automated evaluation replays the same test cases on every change, like unit tests for code. This lesson sets one up with Promptfoo, an open-source tool that compares several prompts and several models on the same cases.

The three ingredients

An evaluation, with any tool, brings together three things:

IngredientHere
The prompts to compareVersions 1, 2 and 3 of the extraction prompt, read from the registry (lesson 5.1)
The providers (models)Qwen2.5-1.5B served locally; Claude with one more line
The test cases with their assertions30 purchase orders and their expected values; valid JSON and correct fields

The configuration

description: Extraction de bons de commande — v1, v2, v3
prompts:
  - id: file://prompts.py:extraction_v1
    label: v1
  - id: file://prompts.py:extraction_v2
    label: v2
  - id: file://prompts.py:extraction_v3
    label: v3
providers:
  - id: openai:chat:qwen-local
    label: qwen2.5-1.5b-local
    config:
      apiBaseUrl: http://127.0.0.1:8765/v1
      apiKey: local
      temperature: 0
      max_tokens: 250
  # Avec Claude (ANTHROPIC_API_KEY), même configuration de tests :
  # - id: anthropic:messages:claude-haiku-5-5
  #   config:
  #     max_tokens: 2000
defaultTest:
  assert:
    - type: contains-json
    - type: python
      value: file://assert_fields.py
tests: file://tests.yaml

Three choices deserve an explanation.

Prompts come from the registry. Promptfoo calls a Python function that loads the requested version from prompts/: it is the same file as in production, not a copy that would drift.

def _render(version: int, context: dict) -> str:
    return registry.load("extraction_bon_de_commande", version).render(document=context["vars"]["document"])


def extraction_v1(context: dict) -> str:
    return _render(1, context)

The local model goes through an OpenAI-compatible server. The project provides a small server (standard library only) that exposes Qwen on http://127.0.0.1:8765/v1. Promptfoo, DSPy and any OpenAI client can then use it like a hosted model:

python -m quill.server

Test cases are generated, with their ground truth, by examples/07_promptfoo_tests.py. For a real project, you start from real annotated examples, and add every bug found in production.

Assertions that measure the business need

contains-json checks the form: the output contains a readable JSON object. The choice matters: a first attempt with is-json, which requires the entire output to be JSON, failed on every case, because the model wraps its JSON in Markdown code fences (```json). The assertion was correct, but it measured something other than what the program actually consumes: our parser extracts the JSON from the text. An assertion must test the output's real contract, neither more nor less strict.

The real question is a business one: is each field correct? A Python assertion returns a verdict, a partial score and a readable reason:

def get_assert(output: str, context: dict) -> dict:
    expected = json.loads(context["vars"]["expected"])
    match = re.search(r"\{.*\}", output, re.S)
    try:
        data = json.loads(match.group(0)) if match else {}
    except json.JSONDecodeError:
        data = {}
    ok = {
        "fournisseur": str(data.get("fournisseur", "")).strip() == expected["fournisseur"],
        "montant_ht": isinstance(data.get("montant_ht"), (int, float))
        and abs(data["montant_ht"] - expected["montant_ht"]) < 0.01,
        "devise": data.get("devise") == expected["devise"],
        "echeance": data.get("echeance") == expected["echeance"],
        "penalites_retard": data.get("penalites_retard") is expected["penalites_retard"],
    }
    wrong = [k for k, v in ok.items() if not v]
    return {"pass": not wrong, "score": sum(ok.values()) / len(ok),
            "reason": "tous les champs justes" if not wrong else f"champs faux : {', '.join(wrong)}"}

The reason ("champs faux : devise, echeance") shows up in the report: you see at a glance what breaks, not just that it breaks.

Running the evaluation

npx promptfoo@latest eval -c promptfoo/promptfooconfig.yaml

Promptfoo's summary, over 30 cases × 3 prompts (4 minutes with the local model):

Prompt (registry)Passed cases (all fields right)Mean assertion scoreMost frequently wrong fields
v10 / 300.63amount, due date, penalties (30 times each)
v211 / 30 (0.37)0.89penalties (12), amount (11)
v314 / 30 (0.47)0.94amount (9), penalties (9)

Three readings:

  • The v1 → v2 progress is clear, v2 → v3 is not. Over 30 cases, the uncertainty on a rate is about ± 18 points: 0.37 versus 0.47 does not allow a conclusion. The partial score (0.89 → 0.94) and the error breakdown suggest progress on penalties; more cases would be needed to claim it;
  • these numbers are not those of lesson 1.2 (0.55 and 0.89 for V2 and V3), and that is expected: the registry prompts are different prompts (a single example inside the message, no system role, written for Claude Haiku), evaluated on different cases. A score only makes sense for one prompt, one model and one test set;
  • the prompt's target model matters: v3's header says model: claude-haiku-5-5. Evaluating it on Qwen2.5-1.5B tells you whether the prompt is robust on a small model, not whether it is good for its target. The Claude provider commented out in the configuration is there for that.

npx promptfoo@latest view then opens a comparison table in the browser: one row per case, one column per prompt, the output and the reason for each failure.

Assertion types

TypeUse
equals, contains, regexShort, deterministic answers
is-json, contains-jsonOutput form
python, javascriptAny business rule (fields, calculations, consistency)
similarSemantic closeness to a reference answer (embeddings)
llm-rubricA model judges against a rubric ("is the tone professional?")
cost, latencyBudgets not to exceed

Prefer deterministic assertions (code) whenever possible: they are free, fast and never wrong. Keep llm-rubric for qualities no code can measure (tone, clarity, relevance), and check on a sample that the judge agrees with a human.

In continuous integration

The evaluation becomes a safeguard when it runs on every prompt change:

  • it runs in CI when a file in prompts/ changes;
  • it fails if the pass rate drops below a threshold, checked by a small script on the results file (-o results.json);
  • the report is attached to the review (lesson 5.1), so the reviewer sees the effect of the change in numbers.

A set of 30 cases is enough to spot a clear regression; not to decide between two prompts 2 points apart. For fine decisions, you need several hundred cases (Fine-tuning & Alignment course, lesson 5.1: the confidence interval of a score over n cases).

Key takeaways

  • An automated evaluation replays the same cases on every change, like unit tests.
  • Promptfoo compares several prompts and several models; the local model plugs in through an OpenAI-compatible server.
  • Read prompts from the registry: you evaluate what goes to production.
  • Deterministic assertions first; an LLM judge only for what code cannot measure.
  • In CI, with a threshold: no prompt change gets through without its numbers.

Practice

  1. Start the local server, then the evaluation, and open the report with promptfoo view: which cases fail for all three versions?
  2. Add a latency assertion and a javascript assertion checking that the due date is after today.
  3. Uncomment the Claude provider (with your key) and compare the two models on the three prompt versions.

Resources