跳至内容

评估一个简单的 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_experimental"},
    {"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_experimental.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["question"])

    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
    

太棒了!你已成功使用 Ragas 运行了你的第一个评估。你现在可以通过打开 experiments/experiment_name.csv 文件来检查结果。