用Ragas评估数学智能体的实验流程

该教程介绍如何借助Ragas对具备函数调用能力的数学智能体做评估驱动开发,包括构造表达式测试集、定义数值正确性指标、编写异步实验循环并输出结果CSV,便于在改动智能体后对比性能变化。

## 评估一个 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, } ``` 现在,每当你改变你的经纪人, 你可以运行实验, 看看它如何影响你的经纪人的性能。 ## 运行示例结束到结束 1. 设置您的 OpenAI API 密钥 ``` export OPENAI_API_KEY="your_api_key_here" ``` 2. 运行评价 ``` python -m ragas_examples.agent_evals.evals ``` Voilà! 您已经成功评估了使用 Ragas 的 AI 代理。 您现在可以通过打开 。 `experiments/experiment_name.csv` 文档。 11月 13, 2026 12月 16, 2025

查看原始来源