首页
/ 最实用DeepEval示例代码:从入门到精通的LLM评估实战指南

最实用DeepEval示例代码:从入门到精通的LLM评估实战指南

2026-02-04 04:23:14作者:薛曦旖Francesca

你还在为LLM(大语言模型)评估烦恼吗?不知道如何验证模型输出的质量?本文将通过精选的DeepEval示例代码,带你快速掌握LLM评估的核心技能,解决评估过程中的常见痛点。读完本文,你将能够:

  • 使用DeepEval进行基础的LLM测试用例编写
  • 评估RAG(检索增强生成)系统的性能
  • 实现MCP(模型调用协议)工具调用的评估
  • 掌握LLM应用的追踪与性能分析方法

快速入门:基础测试用例实现

DeepEval提供了简洁的API来定义和评估LLM测试用例。下面是一个基础示例,展示了如何创建测试用例并使用评估指标。

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

# 要运行此文件:deepeval test run <file_name>.py

dataset = EvaluationDataset(alias="My dataset", test_cases=[])

@pytest.mark.parametrize(
    "test_case",
    dataset.test_cases,
)
def test_everything(test_case: LLMTestCase):
    test_case = LLMTestCase(
        input="What if these shoes don't fit?",
        # 替换为你的LLM应用的实际输出
        actual_output="We offer a 30-day full refund at no extra cost.",
        expected_output="You're eligible for a free full refund within 30 days of purchase.",
    )
    answer_relevancy_metric = AnswerRelevancyMetric(threshold=0.7)
    correctness_metric = GEval(
        name="Correctness",
        criteria="Correctness - determine if the actual output is correct according to the expected output.",
        evaluation_params=[
            LLMTestCaseParams.ACTUAL_OUTPUT,
            LLMTestCaseParams.EXPECTED_OUTPUT,
        ],
        strict_mode=True,
    )
    assert_test(test_case, [answer_relevancy_metric, correctness_metric])

上述代码来自examples/getting_started/test_example.py,展示了如何使用DeepEval的核心组件:

  • LLMTestCase:定义输入、实际输出和预期输出
  • AnswerRelevancyMetric:评估答案与问题的相关性
  • GEval:使用LLM评估输出的正确性
  • assert_test:执行评估并验证结果是否满足阈值

RAG系统评估:提升检索质量

RAG系统的性能很大程度上依赖于检索质量。DeepEval提供了专门的指标来评估RAG系统的各个方面。下面是一个使用Qdrant向量数据库的RAG评估示例。

def create_deepeval_dataset(dataset, eval_size, retrieval_window_size):
    test_cases = []
    for i in range(eval_size):
        entry = dataset[i]
        question = entry["question"]
        answer = entry["answer"]
        context, rag_response = query_with_context(
            question, retrieval_window_size
        )
        test_case = deepeval.test_case.LLMTestCase(
            input=question,
            actual_output=rag_response,
            expected_output=answer,
            retrieval_context=context,
        )
        test_cases.append(test_case)
    return test_cases

test_cases = create_deepeval_dataset(
    qdrant_qna_dataset, EVAL_SIZE, RETRIEVAL_SIZE
)

deepeval.login(CONFIDENT_AI_API_KEY)

deepeval.evaluate(
    test_cases=test_cases,
    metrics=[
        deepeval.metrics.AnswerRelevancyMetric(),
        deepeval.metrics.FaithfulnessMetric(),
        deepeval.metrics.ContextualPrecisionMetric(),
        deepeval.metrics.ContextualRecallMetric(),
        deepeval.metrics.ContextualRelevancyMetric(),
    ],
)

上述代码片段来自examples/rag_evaluation/rag_evaluation_with_qdrant.py,展示了如何评估RAG系统的关键指标:

  • 答案相关性(AnswerRelevancy)
  • 忠实度(Faithfulness):评估输出是否忠实于检索上下文
  • 上下文精确率(ContextualPrecision):评估检索到的上下文是否与问题相关
  • 上下文召回率(ContextualRecall):评估是否检索到了所有相关上下文
  • 上下文相关性(ContextualRelevancy):综合评估检索上下文的质量

MCP工具调用评估:确保工具使用正确性

随着LLM应用越来越复杂,工具调用能力成为重要评估维度。DeepEval支持MCP(模型调用协议)工具调用的评估,下面是一个单轮MCP评估的示例。

class MCPClient:
    def __init__(self):
        self.session: Optional[ClientSession] = None
        self.exit_stack = AsyncExitStack()
        self.anthropic = Anthropic()

    async def connect_to_server(
        self, base_url: str, api_key: str, profile: str
    ):
        # 连接到MCP服务器的实现代码
        # ...

    async def process_query(self, query: str) -> str:
        messages = [{"role": "user", "content": query}]
        
        # 获取可用工具列表
        tool_response = await self.session.list_tools()
        available_tools = [
            {
                "name": tool.name,
                "description": tool.description,
                "input_schema": tool.inputSchema,
            }
            for tool in tool_response.tools
        ]
        
        # 让LLM决定是否调用工具
        response = self.anthropic.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=1000,
            messages=messages,
            tools=available_tools,
        )
        
        # 处理工具调用并记录结果
        tool_uses = []
        for content in response.content:
            if content.type == "tool_use":
                tool_uses.append(content)
        
        for tool_use in tool_uses:
            tool_name = tool_use.name
            tool_args = tool_use.input
            tool_id = tool_use.id
            
            result = await self.session.call_tool(tool_name, tool_args)
            tool_called = MCPToolCall(
                name=tool_name, args=tool_args, result=result
            )
            
            tools_called.append(tool_called)
        
        return "\n".join(response_text)
    
    async def chat_loop(self):
        query = input("Query: ")
        response = await self.process_query(query)
        
        test_case = LLMTestCase(
            input=query,
            actual_output=response,
            mcp_servers=mcp_servers,
            mcp_tools_called=tools_called,
        )
        
        print(test_case)

上述代码来自examples/mcp_evaluation/mcp_eval_single_turn.py,展示了如何评估LLM的工具调用能力。通过记录mcp_serversmcp_tools_called参数,DeepEval可以评估:

  • 工具选择的适当性:是否选择了正确的工具
  • 参数生成的正确性:工具调用参数是否符合要求
  • 工具结果的处理能力:是否正确使用工具返回结果

LLM应用追踪:性能分析与优化

DeepEval提供了追踪功能,可以帮助你深入了解LLM应用的内部工作流程和性能瓶颈。下面是一个追踪示例,展示了如何追踪LLM应用的各个组件。

from deepeval.tracing import trace, TraceType
from openai import OpenAI

client = OpenAI()

class Chatbot:
    def __init__(self):
        pass

    @trace(type=TraceType.LLM, name="OpenAI", model="gpt-4")
    def llm(self, input):
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[
                {
                    "role": "system",
                    "content": "You are a helpful assistant.",
                },
                {"role": "user", "content": input},
            ],
        )
        return response.choices[0].message.content

    @trace(
        type=TraceType.EMBEDDING,
        name="Embedding",
        model="text-embedding-ada-002",
    )
    def get_embedding(self, input):
        response = (
            client.embeddings.create(
                input=input, model="text-embedding-ada-002"
            )
            .data[0]
            .embedding
        )
        return response

    @trace(type=TraceType.RETRIEVER, name="Retriever")
    def retriever(self, input=input):
        embedding = self.get_embedding(input)

        # 替换为实际的向量搜索
        list_of_retrieved_nodes = ["Retrieval Node 1", "Retrieval Node 2"]
        return list_of_retrieved_nodes

    @trace(type=TraceType.TOOL, name="Search")
    def search(self, input):
        # 替换为实际的搜索功能
        title_of_the_top_search_results = "Search Result: " + input
        return title_of_the_top_search_results

上述代码来自examples/tracing/test_chatbot.py,展示了如何使用@trace装饰器来追踪LLM应用的各个组件:

  • LLM调用:追踪模型响应时间和输入输出
  • 嵌入生成:监控嵌入模型的性能
  • 检索器:分析检索性能和结果质量
  • 工具调用:记录工具使用情况和结果

通过DeepEval的追踪功能,你可以获得类似下图的可视化分析结果:

DeepEval追踪仪表板

总结与下一步

本文介绍了DeepEval的几个核心应用场景和示例代码,包括基础测试用例编写、RAG系统评估、MCP工具调用评估以及LLM应用追踪。这些示例覆盖了从简单到复杂的LLM应用评估需求。

要深入学习DeepEval,建议参考以下资源:

通过这些示例和资源,你可以快速掌握LLM应用的评估方法,提升你的AI应用质量和可靠性。立即开始使用DeepEval,为你的LLM应用保驾护航!

要开始使用DeepEval,只需克隆仓库并安装依赖:

git clone https://gitcode.com/GitHub_Trending/de/deepeval
cd deepeval
pip install -r requirements.txt
登录后查看全文
热门项目推荐
相关项目推荐