提示评估
在本教程中,我们将编写一个简单的评估流程来评估一个作为AI系统一部分的提示,这里是一个电影评论情感分类器。在本教程结束时,你将学会如何使用评估驱动开发来评估和迭代单个提示。
flowchart LR
A["'This movie was amazing!<br/>Great acting and plot.'"] --> B["Classifier Prompt"]
B --> C["Positive"]
我们将从测试一个简单的提示开始,该提示将电影评论分为正面或负面。
首先,请确保你已经安装了 ragas 示例并设置了你的 OpenAI API 密钥
现在测试提示
这将测试输入 "The movie was fantastic and I loved every moment of it!" 并应输出 "positive"。
💡 快速开始:如果你想看到完整的评估过程,可以直接跳转到端到端命令,它会自动运行所有内容并生成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.metrics import discrete_metric
from ragas.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="")
接下来,我们将编写实验循环,它将在测试数据集上运行我们的提示,并使用该指标进行评估,然后将结果存储在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.value,
}
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.value,
}
return experiment_view
# Run with specific parameters
run_experiment.arun(dataset, "gpt-4")
# Or use keyword arguments
run_experiment.arun(dataset, model="gpt-4o")
端到端运行示例
- 设置你的 OpenAI API 密钥
- 运行评估
这将
- 创建包含电影评论样本的测试数据集
- 在每个样本上运行情感分类提示
- 使用准确率指标评估结果
- 将所有内容导出到带有结果的CSV文件
太棒了!你已成功使用Ragas运行了你的第一次评估。现在你可以通过打开 experiments/experiment_name.csv 文件来检查结果。