评测一个 AI 工作流
本教程演示如何用 Ragas 评测 AI 工作流,这里是一个简单的自定义邮件支持分流工作流。教程结束时,你将学会如何用评测驱动开发来评测并迭代工作流。
flowchart LR
A["Email Query"] --> B["Rule based Info Extractor"]
B --> C["Template + LLM Response"]
C --> D["Email Reply"]
我们将先测试这个简单工作流:从邮件中提取必要信息,路由到正确模板,并用 LLM 生成回复。
python -m ragas_examples.workflow_eval.workflow
接下来,我们会为工作流写下若干样本邮件查询和期望输出,然后把它们转换成 CSV 文件。
import pandas as pd
dataset_dict = [
{
"email": "Hi, I'm getting error code XYZ-123 when using version 2.1.4 of your software. Please help!",
"pass_criteria": "category Bug Report; product_version 2.1.4; error_code XYZ-123; response references both version and error code"
},
{
"email": "I need to dispute invoice #INV-2024-001 for 299.99 dollars. The charge seems incorrect.",
"pass_criteria": "category Billing; invoice_number INV-2024-001; amount 299.99; response references invoice and dispute process"
}]
pd.DataFrame(dataset_dict).to_csv("datasets/test_dataset.csv", index=False)
为了评测工作流的表现,我们将定义一个基于 LLM 的指标:把工作流的输出与通过标准比较,并据此输出 pass/fail。
from ragas.metrics import DiscreteMetric
my_metric = DiscreteMetric(
name="response_quality",
prompt="Evaluate the response based on the pass criteria: {pass_criteria}. Does the response meet the criteria? Return 'pass' or 'fail'.\nResponse: {response}",
allowed_values=["pass", "fail"],
)
接下来,我们将编写评测实验循环:在测试数据集上运行工作流,用该指标评测,并把结果存到 CSV 文件中。
from ragas import experiment
@experiment()
async def run_experiment(row):
response = workflow_client.process_email(
row["email"]
)
score = my_metric.score(
llm=llm,
response=response.get("response_template", " "),
pass_criteria=row["pass_criteria"]
)
experiment_view = {
**row,
"response": response.get("response_template", " "),
"score": score.value,
"score_reason": score.reason,
}
return experiment_view
现在无论何时你改了工作流,都可以运行实验,看看它如何影响工作流的表现。然后与之前的结果比较,看它是改进了还是变差了。
端到端运行示例
- 设置你的 OpenAI API key
bash
export OPENAI_API_KEY="your_openai_api_key"
- 运行实验
bash
python -m ragas_examples.workflow_eval.evals
搞定!你已经成功用 Ragas 跑完第一次评测。现在可以通过打开 experiments/experiment_name.csv 文件来查看结果。