Laptop showing a terminal with a green test run for an LLM application

DeepEval Guide: Metrics and CI for LLM Apps

If your team already trusts pytest, the quickest way to start testing an LLM app is to keep using it. That is the pitch behind DeepEval: an open-source Python framework where an LLM output becomes a test case, a metric becomes an assertion, and a failing score fails the build. This DeepEval guide walks through how the pieces fit, which metrics are worth the tokens, how to set thresholds you will not regret, and what to watch for when the suite grows beyond a demo.

I will assume you can write Python and have a pipeline (a RAG chain, a chat endpoint, an agent) that you can call from a function. Commands and class names below follow the DeepEval documentation; since the library moves quickly, check the docs for current signatures before copying anything into production.

What DeepEval is, in one paragraph

DeepEval is a testing and evaluation library for LLM applications. You describe each scenario as a test case (input, actual output, optionally expected output and retrieved context), attach one or more metrics, and run them either through a CLI wrapper around pytest or through a plain Python evaluate() call. Many of its built-in metrics use a language model as the grader, so you are really adopting two things at once: a test runner and a library of ready-made judge prompts. That second part is where both the value and the risk live, and the LLM-as-judge guide is worth reading beside this one.

Install and your first test

Setup is a single package install, then a test file that looks like any other pytest module:

pip install -U deepeval
# test_support_bot.py
from deepeval import assert_test
from deepeval.test_case import LLMTestCase
from deepeval.metrics import AnswerRelevancyMetric

from myapp import answer_question

def test_refund_window():
    question = "How long do I have to return a laptop?"
    test_case = LLMTestCase(
        input=question,
        actual_output=answer_question(question),
    )
    assert_test(test_case, [AnswerRelevancyMetric(threshold=0.7)])

Run it with deepeval test run test_support_bot.py. The CLI collects tests the way pytest does, adds DeepEval’s plugin, and reports metric scores and reasons for each case. If a score lands below its threshold, the test fails and the process exits non-zero, which is exactly the signal a CI job needs.

Anatomy of a test case

A single-turn LLMTestCase can carry several fields, and which ones you fill decides which metrics you can run:

FieldPurposeNeeded by
inputThe user queryAlmost every metric
actual_outputWhat your app returnedAlmost every metric
expected_outputReference answerReference-based metrics
retrieval_contextChunks your retriever returnedFaithfulness, contextual metrics
contextGround-truth source factsHallucination-style checks
tools_called / expected_toolsAgent tool usageTool-correctness checks

The most common mistake is confusing retrieval_context with context. The first is what your system actually retrieved at run time; the second is the ideal source material you know to be correct. Evaluating faithfulness against hand-picked context instead of the real retrieved chunks tells you nothing about production behavior. Build the test case from a real pipeline run, capturing retrieved chunks as they were served.

Choosing metrics: a short list that covers most apps

DeepEval ships many metrics, and a long list invites a long bill. Start with a small set matched to what can break.

  • Answer relevancy. Does the response address the question? Cheap sanity check for any chat or Q&A app.
  • Faithfulness. Are claims in the answer supported by the retrieval context? The core RAG hallucination check.
  • Contextual precision and recall. Did retrieval surface the right chunks, and in a useful order? Needs expected output. These point at the index, not the prompt.
  • G-Eval. A flexible metric where you write criteria in plain language and a judge scores against them using chain-of-thought. Use it for the things nothing else covers: tone, policy compliance, completeness for your domain.
  • Tool correctness and task-completion style metrics. For agents, check whether the right tools were called and the task finished.

For RAG pipelines, DeepEval’s retrieval and generation metrics overlap with what RAGAS offers, and many teams run one as primary and spot-check the other. The RAGAS evaluation guide explains how those metric families differ, which helps when two tools disagree on the same row.

A custom metric with G-Eval

When built-ins do not match your rules, G-Eval lets you encode them. Keep criteria short and specific:

from deepeval.metrics import GEval
from deepeval.test_case import LLMTestCaseParams

policy_tone = GEval(
    name="Refund policy tone",
    criteria=(
        "The answer states the refund window accurately, does not promise "
        "exceptions, and stays polite without apologizing more than once."
    ),
    evaluation_params=[
        LLMTestCaseParams.INPUT,
        LLMTestCaseParams.ACTUAL_OUTPUT,
    ],
    threshold=0.6,
)

Two notes. First, G-Eval scores are continuous and noisy, so a threshold of 0.6 is a judgment call that you should justify against labeled examples rather than a standard. Second, bundle multiple unrelated rules into one G-Eval and you will not know which one failed. One rule per metric keeps failures readable.

Setting thresholds you can defend

Thresholds are the policy layer of your test suite, and the default values in a tutorial are not yours.

1. Run the metric on 30 or more rows you have already labeled by hand, pass and fail mixed. 2. Look at the score distribution for good answers and bad ones. Place the threshold in the gap, not at a round number. 3. Record which judge model produced those scores. A different judge shifts every score. 4. Re-check after changing the judge model, the prompt template, or DeepEval’s own version, since metric internals can change between releases.

Where you can, assert on the trend rather than the absolute: “faithfulness mean on this dataset must not drop more than three points below the stored baseline.” That pattern lives in the eval regression gates article and holds up better than fixed cutoffs because it survives judge drift.

Datasets: from rows to a parameterized test

A single hand-written test is a demo. The real structure is a dataset of cases parameterized into pytest. Load rows from your golden dataset and generate one test per row:

import json, pytest

rows = [json.loads(l) for l in open("golden/v1.4.0.jsonl")]

@pytest.mark.parametrize("row", rows, ids=[r["id"] for r in rows])
def test_golden(row):
    out = run_pipeline(row["input"])
    case = LLMTestCase(
        input=row["input"],
        actual_output=out.text,
        expected_output=row["expected"]["reference_answer"],
        retrieval_context=out.chunks,
    )
    assert_test(case, [FaithfulnessMetric(threshold=0.8),
                       AnswerRelevancyMetric(threshold=0.7)])

Using row ids as test ids means a failing line in CI points to a specific example you can open and read. Separate dev and holdout files so the nightly job and the PR job do not blur together.

Running it in CI without a surprise invoice

DeepEval documents running evals inside CI/CD with its CLI, so wiring is straightforward. The part teams underestimate is cost and runtime. Each judge-based metric makes one or more model calls per test case; 200 cases with four metrics is hundreds to thousands of calls per run.

  • Split suites by speed. A 30-row smoke set on every pull request, the full set nightly or before release.
  • Cheaper judge for PR runs, stronger judge for release runs, and never compare scores across the two.
  • Run in parallel where your provider’s rate limits allow, and cache pipeline outputs if only the metric changed.
  • Pin versions of DeepEval, the judge model, and your dataset so a red build means your change, not a dependency drift.
  • Keep API keys in CI secrets, and avoid sending real customer text to a judge provider unless your data policy permits it.

Treat the eval job like any other test job: it should fail fast, print the failing row ids and reasons, and attach the results file as an artifact.

Where DeepEval fits next to other tools

DeepEval is code-first: ideal when engineers own evaluation and want assertions in Python. promptfoo (covered in our promptfoo evaluation guide) is config-first, strong for side-by-side prompt and model comparison and for teams that want a YAML file instead of a test module. RAGAS focuses on RAG metrics specifically. They are not exclusive; a common arrangement is promptfoo for prompt iteration, DeepEval for the pytest gate, and RAGAS for retrieval diagnostics. Whatever combination you pick, put the results in the same place as traces and cost, as described in the LLMOps production guide.

For agent systems, metric-level scores are only one input. If you are new to the term, what is an agent harness defines it, and the harness engineering in practice article describes how checks, retries, and verification loops wrap the model, and that loop is where DeepEval-style tests belong.

Pitfalls we see repeatedly

  • Passing on average, failing on a slice. A mean of 0.85 hides the 12 refund questions at 0.4. Report by tag.
  • Trusting reason strings blindly. Judge explanations are useful hints, not proof. Spot-check them.
  • Evaluating the wrong output. Test the response after your post-processing and guardrails, since that is what users see.
  • Flaky tests. Nondeterministic scores near the threshold produce red builds with no code change. Widen the margin or average multiple runs for borderline rows.
  • Metrics without owners. Every metric needs a person who knows what a drop means and what to do about it.

Start with three metrics, twenty rows, and one CI job. Add another metric only when you can name the failure it catches.

DeepEval questions from teams adopting it

What is DeepEval used for?
DeepEval is an open-source Python framework for testing LLM applications. You turn outputs into test cases, score them with built-in or custom metrics, and run them under pytest-style assertions locally or in CI.

Does DeepEval need an LLM to run metrics?
Most of its predefined metrics use a language model as a judge, so you need access to a judge model and should budget for the extra calls. Deterministic checks you write yourself in plain Python do not need one.

What is the difference between deepeval test run and evaluate()?
Both run evaluations and produce scores. The test run command is a CLI built on pytest and suits CI pipelines, while evaluate() is a Python function that suits notebooks and scripts.

How do I choose a threshold for a DeepEval metric?
Score 30 or more hand-labeled good and bad answers, inspect the distributions, and set the threshold between them for your chosen judge model. Re-check it whenever the judge, prompt, or library version changes.

Can DeepEval evaluate RAG pipelines?
Yes. Pass the retrieved chunks as the retrieval context and use metrics like faithfulness, answer relevancy, and contextual precision or recall to separate retrieval problems from generation problems.

How do I keep DeepEval CI runs affordable?
Run a small smoke set on each pull request and the full dataset nightly. Use a cheaper judge for pull requests, cache pipeline outputs, and limit the number of metrics to those that map to real failure modes.

Related reading

About Mudasir Syed

Check Also

Rows of server racks in a data center suggesting storage infrastructure for vector database workloads

Open-Source Vector DB Projects Worth Tracking

Choosing among open source vector database projects is less about finding the fastest one and …

Leave a Reply