评测一个 AI 智能体
本教程演示如何用 Ragas 评测 AI 智能体,具体是一个能用原子运算和函数调用能力求解复杂表达式的数学智能体。教程结束时,你将学会如何用评测驱动开发来评测并迭代智能体。
graph TD
A[User Input<br/>Math Expression] --> B[MathToolsAgent]
subgraph LLM Agent Loop
B --> D{Need to use a Tool?}
D -- Yes --> E[Call Tool<br/>add/sub/mul/div]
E --> F[Tool Result]
F --> B
D -- No --> G[Emit Final Answer]
end
G --> H[Final Answer]
我们将先测试这个简单智能体:它能用原子运算和函数调用能力求解数学表达式。
python -m ragas_examples.agent_evals.agent
接下来,我们会为智能体创建若干样本表达式和期望输出,然后把它们转换成 CSV 文件。
import pandas as pd
dataset = [
{"expression": "(2 + 3) * (4 - 1)", "expected": 15},
{"expression": "5 * (6 + 2)", "expected": 40},
{"expression": "10 - (3 + 2)", "expected": 5},
]
df = pd.DataFrame(dataset)
df.to_csv("datasets/test_dataset.csv", index=False)
为了评测智能体的表现,我们将定义一个非 LLM 指标:比较智能体输出是否在期望输出的某一容差范围内,并据此返回 1/0。
from ragas.metrics import numeric_metric
from ragas.metrics.result import MetricResult
@numeric_metric(name="correctness")
def correctness_metric(prediction: float, actual: float):
"""Calculate correctness of the prediction."""
if isinstance(prediction, str) and "ERROR" in prediction:
return 0.0
result = 1.0 if abs(prediction - actual) < 1e-5 else 0.0
return MetricResult(value=result, reason=f"Prediction: {prediction}, Actual: {actual}")
接下来,我们将编写实验循环:在测试数据集上运行智能体,用该指标评测,并把结果存到 CSV 文件中。
from ragas import experiment
@experiment()
async def run_experiment(row):
expression = row["expression"]
expected_result = row["expected"]
# Get the model's prediction
prediction = math_agent.solve(expression)
# Calculate the correctness metric
correctness = correctness_metric.score(prediction=prediction.get("result"), actual=expected_result)
return {
"expression": expression,
"expected_result": expected_result,
"prediction": prediction.get("result"),
"log_file": prediction.get("log_file"),
"correctness": correctness.value
}
现在无论何时你改了智能体,都可以运行实验,看看它如何影响智能体的表现。
端到端运行示例
- 设置你的 OpenAI API key
bash
export OPENAI_API_KEY="your_api_key_here"
- 运行评测
bash
python -m ragas_examples.agent_evals.evals
搞定!你已经成功用 Ragas 评测了一个 AI 智能体。现在可以通过打开 experiments/experiment_name.csv 文件来查看结果。