提示评估

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

在这里插入图片描述
我们将从测试一个简单的提示开始,该提示将电影评论分类为正面或负面。

首先,确保您已安装 ragas 示例并设置了您的 OpenAI API 密钥:

pip install ragas[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”。

💡 快速开始 :如果您想查看完整的评估运行过程,可以直接跳转到端到端命令,该命令会运行所有内容并自动生成 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")

端到端运行示例

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

这将执行以下操作:

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

完成!您已成功使用 Ragas 运行了首次评估。现在可以通过打开 experiments/experiment_name.csv 文件来查看结果。

Logo

脑启社区是一个专注类脑智能领域的开发者社区。欢迎加入社区,共建类脑智能生态。社区为开发者提供了丰富的开源类脑工具软件、类脑算法模型及数据集、类脑知识库、类脑技术培训课程以及类脑应用案例等资源。

更多推荐