Skip to main content

The LLM Evaluation Framework

Project description

DeepEval Logo

The LLM Evaluation Framework

confident-ai%2Fdeepeval | Trendshift

discord-invite

Documentation | Metrics and Features | Getting Started | Integrations | DeepEval Platform

GitHub release Try Quickstart in Colab License Twitter Follow

Deutsch | Español | français | 日本語 | 한국어 | Português | Русский | 中文

DeepEval is a simple-to-use, open-source LLM evaluation framework, for evaluating and testing large-language model systems. It is similar to Pytest but specialized for unit testing LLM outputs. DeepEval incorporates the latest research to evaluate LLM outputs based on metrics such as G-Eval, task completion, answer relevancy, hallucination, etc., which uses LLM-as-a-judge and other NLP models that run locally on your machine for evaluation.

Whether your LLM applications are AI agents, RAG pipelines, or chatbots, implemented via LangChain or OpenAI, DeepEval has you covered. With it, you can easily determine the optimal models, prompts, and architecture to improve your RAG pipeline, agentic workflows, prevent prompt drifting, or even transition from OpenAI to hosting your own Deepseek R1 with confidence.

[!IMPORTANT] Need a place for your DeepEval testing data to live 🏡❤️? Sign up to the DeepEval platform to compare iterations of your LLM app, generate & share testing reports, and more.

Demo GIF

Want to talk LLM evaluation, need help picking metrics, or just to say hi? Come join our discord.


🔥 Metrics and Features

🥳 You can now share DeepEval's test results on the cloud directly on Confident AI

  • Supports both end-to-end and component-level LLM evaluation.
  • Large variety of ready-to-use LLM evaluation metrics (all with explanations) powered by ANY LLM of your choice, statistical methods, or NLP models that run locally on your machine:
    • G-Eval
    • DAG (deep acyclic graph)
    • RAG metrics:
      • Answer Relevancy
      • Faithfulness
      • Contextual Recall
      • Contextual Precision
      • Contextual Relevancy
      • RAGAS
    • Agentic metrics:
      • Task Completion
      • Tool Correctness
    • Others:
      • Hallucination
      • Summarization
      • Bias
      • Toxicity
    • Conversational metrics:
      • Knowledge Retention
      • Conversation Completeness
      • Conversation Relevancy
      • Role Adherence
    • etc.
  • Build your own custom metrics that are automatically integrated with DeepEval's ecosystem.
  • Generate synthetic datasets for evaluation.
  • Integrates seamlessly with ANY CI/CD environment.
  • Red team your LLM application for 40+ safety vulnerabilities in a few lines of code, including:
    • Toxicity
    • Bias
    • SQL Injection
    • etc., using advanced 10+ attack enhancement strategies such as prompt injections.
  • Easily benchmark ANY LLM on popular LLM benchmarks in under 10 lines of code., which includes:
    • MMLU
    • HellaSwag
    • DROP
    • BIG-Bench Hard
    • TruthfulQA
    • HumanEval
    • GSM8K
  • 100% integrated with Confident AI for the full evaluation & observability lifecycle:
    • Curate/annotate evaluation datasets on the cloud
    • Benchmark LLM app using dataset, and compare with previous iterations to experiment which models/prompts works best
    • Fine-tune metrics for custom results
    • Debug evaluation results via LLM traces
    • Monitor & evaluate LLM responses in product to improve datasets with real-world data
    • Repeat until perfection

[!NOTE] DeepEval is available on Confident AI, an LLM evals platform for AI observability and quality. Create an account here.


🔌 Integrations


🚀 QuickStart

Let's pretend your LLM application is a RAG based customer support chatbot; here's how DeepEval can help test what you've built.

Installation

Deepeval works with Python>=3.9+.

pip install -U deepeval

Create an account (highly recommended)

Using the deepeval platform will allow you to generate sharable testing reports on the cloud. It is free, takes no additional code to setup, and we highly recommend giving it a try.

To login, run:

deepeval login

Follow the instructions in the CLI to create an account, copy your API key, and paste it into the CLI. All test cases will automatically be logged (find more information on data privacy here).

Writing your first test case

Create a test file:

touch test_chatbot.py

Open test_chatbot.py and write your first test case to run an end-to-end evaluation using DeepEval, which treats your LLM app as a black-box:

import pytest
from deepeval import assert_test
from deepeval.metrics import GEval
from deepeval.test_case import LLMTestCase, LLMTestCaseParams

def test_case():
    correctness_metric = GEval(
        name="Correctness",
        criteria="Determine if the 'actual output' is correct based on the 'expected output'.",
        evaluation_params=[LLMTestCaseParams.ACTUAL_OUTPUT, LLMTestCaseParams.EXPECTED_OUTPUT],
        threshold=0.5
    )
    test_case = LLMTestCase(
        input="What if these shoes don't fit?",
        # Replace this with the actual output from your LLM application
        actual_output="You have 30 days to get a full refund at no extra cost.",
        expected_output="We offer a 30-day full refund at no extra costs.",
        retrieval_context=["All customers are eligible for a 30 day full refund at no extra costs."]
    )
    assert_test(test_case, [correctness_metric])

Set your OPENAI_API_KEY as an environment variable (you can also evaluate using your own custom model, for more details visit this part of our docs):

export OPENAI_API_KEY="..."

And finally, run test_chatbot.py in the CLI:

deepeval test run test_chatbot.py

Congratulations! Your test case should have passed ✅ Let's breakdown what happened.

  • The variable input mimics a user input, and actual_output is a placeholder for what your application's supposed to output based on this input.
  • The variable expected_output represents the ideal answer for a given input, and GEval is a research-backed metric provided by deepeval for you to evaluate your LLM output's on any custom with human-like accuracy.
  • In this example, the metric criteria is correctness of the actual_output based on the provided expected_output.
  • All metric scores range from 0 - 1, which the threshold=0.5 threshold ultimately determines if your test have passed or not.

Read our documentation for more information on more options to run end-to-end evaluation, how to use additional metrics, create your own custom metrics, and tutorials on how to integrate with other tools like LangChain and LlamaIndex.


Evaluating Nested Components

If you wish to evaluate individual components within your LLM app, you need to run component-level evals - a powerful way to evaluate any component within an LLM system.

Simply trace "components" such as LLM calls, retrievers, tool calls, and agents within your LLM application using the @observe decorator to apply metrics on a component-level. Tracing with deepeval is non-instrusive (learn more here) and helps you avoid rewriting your codebase just for evals:

from deepeval.tracing import observe, update_current_span
from deepeval.test_case import LLMTestCase
from deepeval.dataset import Golden
from deepeval.metrics import GEval
from deepeval import evaluate

correctness = GEval(name="Correctness", criteria="Determine if the 'actual output' is correct based on the 'expected output'.", evaluation_params=[LLMTestCaseParams.ACTUAL_OUTPUT, LLMTestCaseParams.EXPECTED_OUTPUT])

@observe(metrics=[correctness])
def inner_component():
    # Component can be anything from an LLM call, retrieval, agent, tool use, etc.
    update_current_span(test_case=LLMTestCase(input="...", actual_output="..."))
    return

@observe
def llm_app(input: str):
    inner_component()
    return

evaluate(observed_callback=llm_app, goldens=[Golden(input="Hi!")])

You can learn everything about component-level evaluations here.


Evaluating Without Pytest Integration

Alternatively, you can evaluate without Pytest, which is more suited for a notebook environment.

from deepeval import evaluate
from deepeval.metrics import AnswerRelevancyMetric
from deepeval.test_case import LLMTestCase

answer_relevancy_metric = AnswerRelevancyMetric(threshold=0.7)
test_case = LLMTestCase(
    input="What if these shoes don't fit?",
    # Replace this with the actual output from your LLM application
    actual_output="We offer a 30-day full refund at no extra costs.",
    retrieval_context=["All customers are eligible for a 30 day full refund at no extra costs."]
)
evaluate([test_case], [answer_relevancy_metric])

Using Standalone Metrics

DeepEval is extremely modular, making it easy for anyone to use any of our metrics. Continuing from the previous example:

from deepeval.metrics import AnswerRelevancyMetric
from deepeval.test_case import LLMTestCase

answer_relevancy_metric = AnswerRelevancyMetric(threshold=0.7)
test_case = LLMTestCase(
    input="What if these shoes don't fit?",
    # Replace this with the actual output from your LLM application
    actual_output="We offer a 30-day full refund at no extra costs.",
    retrieval_context=["All customers are eligible for a 30 day full refund at no extra costs."]
)

answer_relevancy_metric.measure(test_case)
print(answer_relevancy_metric.score)
# All metrics also offer an explanation
print(answer_relevancy_metric.reason)

Note that some metrics are for RAG pipelines, while others are for fine-tuning. Make sure to use our docs to pick the right one for your use case.

Evaluating a Dataset / Test Cases in Bulk

In DeepEval, a dataset is simply a collection of test cases. Here is how you can evaluate these in bulk:

import pytest
from deepeval import assert_test
from deepeval.dataset import EvaluationDataset, Golden
from deepeval.metrics import AnswerRelevancyMetric
from deepeval.test_case import LLMTestCase

dataset = EvaluationDataset(goldens=[Golden(input="What's the weather like today?")])

for golden in dataset.goldens:
    test_case = LLMTestCase(
        input=golden.input,
        actual_output=your_llm_app(golden.input)
    )
    dataset.add_test_case(test_case)

@pytest.mark.parametrize(
    "test_case",
    dataset.test_cases,
)
def test_customer_chatbot(test_case: LLMTestCase):
    answer_relevancy_metric = AnswerRelevancyMetric(threshold=0.5)
    assert_test(test_case, [answer_relevancy_metric])
# Run this in the CLI, you can also add an optional -n flag to run tests in parallel
deepeval test run test_<filename>.py -n 4

Alternatively, although we recommend using deepeval test run, you can evaluate a dataset/test cases without using our Pytest integration:

from deepeval import evaluate
...

evaluate(dataset, [answer_relevancy_metric])
# or
dataset.evaluate([answer_relevancy_metric])

A Note on Env Variables (.env / .env.local)

DeepEval auto-loads .env.local then .env from the current working directory at import time. Precedence: process env -> .env.local -> .env. Opt out with DEEPEVAL_DISABLE_DOTENV=1.

cp .env.example .env.local
# then edit .env.local (ignored by git)

DeepEval With Confident AI

DeepEval is available on Confident AI, an evals & observability platform that allows you to:

  1. Curate/annotate evaluation datasets on the cloud
  2. Benchmark LLM app using dataset, and compare with previous iterations to experiment which models/prompts works best
  3. Fine-tune metrics for custom results
  4. Debug evaluation results via LLM traces
  5. Monitor & evaluate LLM responses in product to improve datasets with real-world data
  6. Repeat until perfection

Everything on Confident AI, including how to use Confident is available here.

To begin, login from the CLI:

deepeval login

Follow the instructions to log in, create your account, and paste your API key into the CLI.

Now, run your test file again:

deepeval test run test_chatbot.py

You should see a link displayed in the CLI once the test has finished running. Paste it into your browser to view the results!

Demo GIF


Configuration

Environment variables via .env files

Using .env.local or .env is optional. If they are missing, DeepEval uses your existing environment variables. When present, dotenv environment variables are auto-loaded at import time (unless you set DEEPEVAL_DISABLE_DOTENV=1).

Precedence: process env -> .env.local -> .env

cp .env.example .env.local
# then edit .env.local (ignored by git)

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.


Roadmap

Features:

  • Integration with Confident AI
  • Implement G-Eval
  • Implement RAG metrics
  • Implement Conversational metrics
  • Evaluation Dataset Creation
  • Red-Teaming
  • DAG custom metrics
  • Guardrails

Authors

Built by the founders of Confident AI. Contact jeffreyip@confident-ai.com for all enquiries.


License

DeepEval is licensed under Apache 2.0 - see the LICENSE.md file for details.

Project details


Release history Release notifications | RSS feed

This version

3.8.4

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

deepeval-3.8.4.tar.gz (593.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

deepeval-3.8.4-py3-none-any.whl (819.3 kB view details)

Uploaded Python 3

File details

Details for the file deepeval-3.8.4.tar.gz.

File metadata

  • Download URL: deepeval-3.8.4.tar.gz
  • Upload date:
  • Size: 593.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.11.9 Darwin/22.4.0

File hashes

Hashes for deepeval-3.8.4.tar.gz
Algorithm Hash digest
SHA256 cb60c4a53488970136e8149de4beb3a0e1272feb6b8ec2a8ee633ca2ad3bbce7
MD5 4bd91443d63c0b8a25278353a25bcfe2
BLAKE2b-256 e6ef577e7dc254f9c81bb122b2e137ec1b09d9c80b674fdea33f24923cbc8342

See more details on using hashes here.

File details

Details for the file deepeval-3.8.4-py3-none-any.whl.

File metadata

  • Download URL: deepeval-3.8.4-py3-none-any.whl
  • Upload date:
  • Size: 819.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.11.9 Darwin/22.4.0

File hashes

Hashes for deepeval-3.8.4-py3-none-any.whl
Algorithm Hash digest
SHA256 4435aeb854a454bba00d6f4d6fb31ae3e70420d2be065ce9a966f09bb691fed7
MD5 61e504ea94796ef3eba4367873c6b93a
BLAKE2b-256 7a48feab76e41dc8c34a26a22289005b62f1a2d43b9cc0d95e0a2d68e4332d73

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page