deepeval README

README проекта с github.com/confident-ai/deepeval. Одним файлом markdown: README.md.

DeepEval.

The LLM Evaluation Framework

confident-ai%2Fdeepeval | Trendshift

discord-invite reddit-community

Documentation | Metrics and Features | Getting Started | Integrations | Confident AI

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 large-language model systems. It is similar to Pytest but specialized for unit testing LLM apps. DeepEval incorporates the latest research to run evals via metrics such as G-Eval, task completion, answer relevancy, hallucination, etc., which use LLM-as-a-judge and other NLP models that run locally on your machine.

Whether you're building AI agents, voice agents, multi-turn chatbots, RAG pipelines, or anything else, implemented via LangChain or OpenAI, DeepEval has you covered. With it, you can easily evaluate:

Use these evaluations to determine the optimal models, prompts, and architecture to improve your AI quality, prevent prompt drifting, or even transition from OpenAI to Claude with confidence.

Jev is now available in DeepEval, both in existing metrics and the latest JevEval.

[!IMPORTANT] If you're already in production, Confident AI surfaces failing traces before anyone has written an eval for them, clusters them into failure modes, and turns them into your next eval.

Demo GIF


🔥 Metrics and Features


🔌 Integrations

DeepEval plugs into any LLM framework — OpenAI Agents, LangChain, CrewAI, and more — and into voice stacks like Vapi, ElevenLabs, LiveKit, and Pipecat. The same traces can go to Confident AI once you're live, where evals run on every production trace.

Frameworks

Voice Agent Connectors

☁️ Platform + Ecosystem

Confident AI is AI monitoring for applications in production. DeepEval tests what you know to test before you ship; Confident AI finds what you didn't, and it's model- and framework-agnostic.

Confident AI MCP Architecture


🤖 Vibe-Coder QuickStart

Want your coding agent to add evals and fix failures for you? Install the DeepEval skill, point it at your AI agent, voice agent, multi-turn chatbot, RAG pipeline, or any other LLM app, and ask it to generate a dataset, write the eval suite, run deepeval test run, and iterate on the failing metrics.

Start with the 5-minute vibe-coder guide.


🚀 Human QuickStart

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

Installation

Deepeval works with Python>=3.10+.

pip install -U deepeval

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).

Write your first test case

Create a test file:

touch test_ai_agent.py

Open test_ai_agent.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, SingleTurnParams

def test_case():
    correctness_metric = GEval(
        name="Correctness",
        criteria="Determine if the 'actual output' is correct based on the 'expected output'.",
        evaluation_params=[SingleTurnParams.ACTUAL_OUTPUT, SingleTurnParams.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.",
    )
    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_ai_agent.py in the CLI:

deepeval test run test_ai_agent.py

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

Read our documentation for more information!


Evals With Full Traceability

Use evals_iterator() to run the same dataset through your app, whether you instrument it manually or through one of DeepEval's framework integrations. Because tracing captures the ordered sequence of model decisions, tool calls, and intermediate steps, you can run trajectory-based evaluations over the complete path your AI agent takes.

Here's an example of manual instrumentation:

from deepeval.tracing import observe, update_current_span
from deepeval.test_case import LLMTestCase
from deepeval.metrics import TaskCompletionMetric

@observe()
def inner_component(input: str):
    output = "result"
    update_current_span(test_case=LLMTestCase(input=input, actual_output=output))
    return output

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

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(metrics=[TaskCompletionMetric()]):
    app(golden.input)
OpenAI
from deepeval.openai import OpenAI
from deepeval.tracing import trace
from deepeval.metrics import TaskCompletionMetric

client = OpenAI()

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator():
    with trace(metrics=[TaskCompletionMetric()]):
        client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": golden.input}],
        )
OpenAI Agents
from agents import Runner
from deepeval.metrics import TaskCompletionMetric

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(metrics=[TaskCompletionMetric()]):
    Runner.run_sync(agent, golden.input)
AI SDK (TypeScript)
import { generateText } from "ai";
import { configureAiSdkTracing } from "deepeval/integrations/ai-sdk";
import { TaskCompletionMetric } from "deepeval/metrics";

const tracer = configureAiSdkTracing({ name: "my-agent" });

const ask = (input: string) =>
  generateText({
    model,
    prompt: input,
    experimental_telemetry: { isEnabled: true, tracer },
  });

// This metric evaluates the complete trajectory captured for this run.
for await (const golden of dataset.evalsIterator({
  metrics: [new TaskCompletionMetric()],
})) {
  await ask(golden.input);
}
Mastra (TypeScript)
import { Mastra } from "@mastra/core/mastra";
import { Observability } from "@mastra/observability";
import { DeepEvalExporter } from "deepeval/integrations/mastra";
import { TaskCompletionMetric } from "deepeval/metrics";

const mastra = new Mastra({
  agents: { agent },
  observability: new Observability({
    configs: {
      deepeval: { exporters: [new DeepEvalExporter()] },
    },
  }),
});

// This metric evaluates the complete trajectory captured for this run.
for await (const golden of dataset.evalsIterator({
  metrics: [new TaskCompletionMetric()],
})) {
  await mastra.getAgent("agent").generate(golden.input);
}
Anthropic
from deepeval.anthropic import Anthropic
from deepeval.tracing import trace
from deepeval.metrics import TaskCompletionMetric

client = Anthropic()

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator():
    with trace(metrics=[TaskCompletionMetric()]):
        client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=1024,
            messages=[{"role": "user", "content": golden.input}],
        )
LangChain
from deepeval.integrations.langchain import CallbackHandler
from deepeval.metrics import TaskCompletionMetric

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator():
    llm.invoke(
        golden.input,
        config={"callbacks": [CallbackHandler(metrics=[TaskCompletionMetric()])]},
    )
LangGraph
from deepeval.integrations.langchain import CallbackHandler
from deepeval.metrics import TaskCompletionMetric

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator():
    agent.invoke(
        {"messages": [{"role": "user", "content": golden.input}]},
        config={"callbacks": [CallbackHandler(metrics=[TaskCompletionMetric()])]},
    )
Pydantic AI
from deepeval.metrics import TaskCompletionMetric

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(metrics=[TaskCompletionMetric()]):
    agent.run_sync(golden.input)
CrewAI
from deepeval.integrations.crewai import instrument_crewai
from deepeval.metrics import TaskCompletionMetric

instrument_crewai()

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(metrics=[TaskCompletionMetric()]):
    crew.kickoff({"input": golden.input})
AWS AgentCore
from deepeval.integrations.agentcore import instrument_agentcore
from deepeval.metrics import TaskCompletionMetric

instrument_agentcore()

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(metrics=[TaskCompletionMetric()]):
    invoke({"prompt": golden.input})
LlamaIndex
import asyncio
from deepeval.evaluate.configs import AsyncConfig
from deepeval.metrics import TaskCompletionMetric

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(
    async_config=AsyncConfig(run_async=True),
    metrics=[TaskCompletionMetric()],
):
    task = asyncio.create_task(agent.run(golden.input))
    dataset.evaluate(task)
Google ADK
import asyncio
from deepeval.evaluate.configs import AsyncConfig
from deepeval.integrations.google_adk import instrument_google_adk
from deepeval.metrics import TaskCompletionMetric

instrument_google_adk()

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(
    async_config=AsyncConfig(run_async=True),
    metrics=[TaskCompletionMetric()],
):
    task = asyncio.create_task(run_agent(golden.input))
    dataset.evaluate(task)
Strands
from deepeval.integrations.strands import instrument_strands
from deepeval.metrics import TaskCompletionMetric

instrument_strands()

# This metric evaluates the complete trajectory captured for this run.
for golden in dataset.evals_iterator(metrics=[TaskCompletionMetric()]):
    agent(golden.input)

Learn more about component-level evaluations here.


Evaluate 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 built for specific use cases, such as AI agents, voice agents, multi-turn chatbots, RAG, and more. Make sure to use our docs to pick the right one for your use case.

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

Confident AI monitors AI applications in production. Evals run on every production trace, failing traces are clustered into failure modes, and each one can be routed to the right annotators — engineers, QA, domain experts or PMs — and turned into a golden for your next eval. The traces your app already produces with DeepEval stream to it with no code changes.

Log in from the CLI to connect:

deepeval login

Test runs also appear on the platform once you're logged in.

Demo GIF

Prefer to stay in your IDE? Inspect failing traces and pull the datasets built from them through Confident AI's MCP server without leaving your editor.

Confident AI MCP Architecture

Learn more in the Confident AI documentation.


Contributing

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


Roadmap

Features:


Authors

Built by the founders of Confident AI. Contact [email protected] for all enquiries.


License

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

deepeval (confident-ai/deepeval)

Ищем в базе…

Что это такое?DeepEval — это open-source фреймворк для оценки LLM: простой способ проверять системы на основе больших языковых моделей по метрикам, обоснованным исследованиями, — например G-Eval, релевантность ответа и проверка на галлюцинации.
Чем это отличается от обычного pytest?Он повторяет стиль юнит-тестирования pytest, но создан специально для LLM-приложений: тест-кейсы — это Python-объекты, объединяющие входные данные, выходные данные и метрики оценки, а не обычные generic-проверки через assert, и запускаются они через собственный CLI DeepEval.
Как начать тестировать своё приложение?Установите пакет через pip (нужен Python 3.9+), напишите тестовый файл с входными данными, actual_output вашего приложения и метрикой вроде GEval с пороговым значением, затем выполните в CLI команду 'deepeval test run'. Оценки варьируются от 0 до 1, и именно порог решает, прошёл тест или нет.
Нужен ли мне API-ключ OpenAI, чтобы запускать оценки?В quickstart задаётся переменная окружения OPENAI_API_KEY, но вы не привязаны к OpenAI: метрики может поддерживать любая выбранная вами LLM или NLP-модели, работающие локально, а оценивать можно и собственной кастомной моделью.
Обязательно ли регистрироваться в облаке Confident AI?Нет — фреймворк open-source и полностью работает локально сам по себе. Платформа Confident AI — это необязательная бесплатная регистрация, которая добавляет к вашим запускам доступные для шаринга облачные отчёты о тестировании.
Для кого это сделано — агенты, RAG-приложения, чат-боты?Для разработчиков AI-агентов, RAG-пайплайнов и чат-ботов — приложение можно оценивать целиком как чёрный ящик или на уровне отдельных компонентов, вплоть до шагов агента вроде вызовов инструментов, поиска (retrieval) и передачи задач суб-агентам.
Работает ли это на Windows, или только на Mac и Linux?Это Python-пакет с CLI, устанавливаемый через pip, поэтому он работает везде, где есть Python 3.9+, — на Windows, macOS и Linux.
Он отправляет мои тестовые данные куда-то?Только если вы сами это включите: после входа в платформу Confident AI все ваши тест-кейсы автоматически логируются в облако, а защита данных описана в отдельной документации.
Может ли он сам генерировать датасеты для оценки?Да — он умеет генерировать синтетические датасеты как с однораундовыми, так и с многораундовыми диалогами, так что каждый тестовый ввод не придётся писать вручную.
Что такое G-Eval?Это метрика в подходе LLM-as-a-judge, подтверждённая исследованиями: она оценивает выходные данные по любым заданным вами критериям с точностью, близкой к человеческой, — в quickstart её используют для проверки ответа на соответствие ожидаемому.
Может ли он бенчмаркить «сырые» LLM, а не только моё приложение?Да — он может прогонять любую LLM по популярным бенчмаркам вроде MMLU, HellaSwag, DROP, BIG-Bench Hard, TruthfulQA, HumanEval и GSM8K менее чем в 10 строках кода.
Он помогает улучшать моё приложение или только оценивает?Он автоматически оптимизирует промпты на основе результатов оценки, так что помимо вердиктов «прошёл/не прошёл» он помогает вам итерациями добиваться более качественных ответов.
Какие есть похожие проекты?promptfoo, jevals, ragas, mlflow, opik, Tracely-ai, phoenix, ParseBench
Автор
confident-ai
Размер
262.6 MB
Звёзды
19.5K
Возраст
3 г
Коммиты · 90 дней