跳至内容

评估一个 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_experimental.metrics import numeric_metric
from ragas_experimental.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):
    question = row["question"]
    expected_answer = row["answer"]

    # Get the model's prediction
    prediction = math_agent.solve(question)

    # Calculate the correctness metric
    correctness = correctness_metric.score(prediction=prediction.get("result"), actual=expected_answer)

    return {
        "question": question,
        "expected_answer": expected_answer,
        "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
    

好了!您已成功使用 Ragas 评估了一个智能体。您现在可以通过打开 experiments/experiment_name.csv 文件来查看结果。