跳至内容

提示评估

在本教程中,我们将编写一个简单的评估管道来评估作为 AI 系统一部分的提示,这里是一个电影评论情感分类器。在本教程结束时,你将学会如何使用评估驱动开发来评估和迭代单个提示。

flowchart LR
    A["'This movie was amazing!<br/>Great acting and plot.'"] --> B["Classifier Prompt"]
    B --> C["Positive"]

我们将先测试一个简单的提示,用于将电影评论分类为正面或负面。

首先,确保您已安装 ragas 示例并设置好您的 OpenAI API key:

pip install ragas_experimental[examples]
export OPENAI_API_KEY = "your_openai_api_key"

现在测试提示:

python -m ragas_examples.prompt_evals.prompt

这将测试输入 "The movie was fantastic and I loved every moment of it!",并应输出 "positive"

💡 快速开始:如果您想查看完整的评估演示,您可以直接跳转到 end-to-end command,该命令会运行所有步骤并自动生成 CSV 结果。

接下来,我们将写出一些示例输入和期望输出,然后将它们转换为一个 CSV 文件。

import pandas as pd

samples = [{"text": "I loved the movie! It was fantastic.", "label": "positive"},
    {"text": "The movie was terrible and boring.", "label": "negative"},
    {"text": "It was an average film, nothing special.", "label": "positive"},
    {"text": "Absolutely amazing! Best movie of the year.", "label": "positive"}]
pd.DataFrame(samples).to_csv("datasets/test_dataset.csv", index=False)

现在我们需要一种方法来衡量在此任务中提示的性能。我们将定义一个指标,用于将提示的输出与期望输出进行比较,并据此判定通过/失败。

from ragas_experimental.metrics import discrete_metric
from ragas_experimental.metrics.result import MetricResult

@discrete_metric(name="accuracy", allowed_values=["pass", "fail"])
def my_metric(prediction: str, actual: str):
    """Calculate accuracy of the prediction."""
    return MetricResult(value="pass", reason="") if prediction == actual else MetricResult(value="fail", reason="")

接下来,我们将编写实验循环,该循环将在测试数据集上运行我们的提示(prompt),使用该指标进行评估,并将结果存储到 CSV 文件中。

from ragas import experiment

@experiment()
async def run_experiment(row):

    response = run_prompt(row["text"])
    score = my_metric.score(
        prediction=response,
        actual=row["label"]
    )

    experiment_view = {
        **row,
        "response":response,
        "score":score.result,
    }
    return experiment_view

现在,每当你对提示进行更改时,你都可以运行实验,查看它如何影响提示的性能。

传递附加参数

您可以向您的实验函数传递额外的参数,例如模型或配置:

@experiment()
async def run_experiment(row, model):
    response = run_prompt(row["text"], model=model)
    score = my_metric.score(
        prediction=response,
        actual=row["label"]
    )

    experiment_view = {
        **row,
        "response": response,
        "score": score.result,
    }
    return experiment_view

# Run with specific parameters
run_experiment.arun(dataset, "gpt-4")

# Or use keyword arguments
run_experiment.arun(dataset, model="gpt-4o")

端到端运行示例

  1. 设置你的 OpenAI API 密钥
    export OPENAI_API_KEY = "your_openai_api_key"
    
  2. 运行评估
    python -m ragas_examples.prompt_evals.evals
    

这将:

  • 创建包含示例电影评论的测试数据集
  • 对每个样本运行情感分类提示
  • 使用准确率指标评估结果
  • 将所有内容与结果导出为 CSV 文件

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