用评测驱动开发评估简单RAG系统

该教程搭建一个简单RAG评测流程,先构造含查询与评分要点的测试数据集,再用基于LLM的离散指标判定回答通过与否,最后用实验循环批量运行并保存结果,便于在改动RAG管线后对比性能。

## 评估一个简单的 RAG 系统 在这个教程中,我们将写一个简单的评价管道来评价一个RAG(检索-增强的一代)系统。 在这个教程结束时,您将学习如何利用评价驱动的开发来评价和提升一个RAG系统。 ``` flowchart LR A["Query<br/>'What is Ragas 0.3?'"] --> B[Retrieval System] C[Document Corpus<br/> Ragas 0.3 Docs📄] --> B B --> D[LLM + Prompt] A --> D D --> E[Final Answer] ``` 我们将首先编写一个简单的RAG系统,从一个实体中检索相关文档,并使用LLM生成一个答案. ``` python -m ragas_examples.rag_eval.rag ``` 接下来,我们将为我们的 RAG 系统记录一些样本查询和预期输出。然后将它们转换为 CSV 文件 。 ``` import pandas as pd samples = [ { "query": "What is Ragas 0.3?", "grading_notes": "- Ragas 0.3 is a library for evaluating LLM applications.", }, { "query": "How to install Ragas?", "grading_notes": "- install from source - install from pip using ragas[examples]", }, { "query": "What are the main features of Ragas?", "grading_notes": "organised around - experiments - datasets - metrics.", }, ] pd.DataFrame(samples).to_csv("datasets/test_dataset.csv", index=False) ``` 为了评价我们的RAG系统的性能,我们将定义一个基于llm的度量衡,将我们的RAG系统的输出与基于它的分级注释和输出通过/失败进行比较. ``` from ragas.metrics import DiscreteMetric my_metric = DiscreteMetric( name="correctness", prompt="Check if the response contains points mentioned from the grading notes and return 'pass' or 'fail'.\nResponse: {response} Grading Notes: {grading_notes}", allowed_values=["pass", "fail"], ) ``` 接下来,我们将将运行我们测试数据集的RAG系统的实验循环写入并使用度量衡来评价,并将结果存储在CSV文件中. ``` @experiment() async def run_experiment(row): response = rag_client.query(row["query"]) score = my_metric.score( llm=llm, response=response.get("answer", " "), grading_notes=row["grading_notes"], ) experiment_view = { **row, "response": response.get("answer", ""), "score": score.value, "log_file": response.get("logs", " "), } return experiment_view ``` 现在,每当你改变你的RAG管道时,你可以运行实验,看看它如何影响你的RAG的性能. ## 运行示例结束到结束 1. 设置您的 OpenAI API 密钥 ``` export OPENAI_API_KEY="your_openai_api_key" ``` 2. 运行评价 ``` python -m ragas_examples.rag_eval.evals ``` Voila ! 您已经成功使用 Ragas 运行了您的第一次评估 。 您现在可以通过打开 。 `experiments/experiment_name.csv` 文档。 11月 13, 2026 12月 16, 2025

查看原始来源