跳转到内容

评估一个简单的LLM应用

本指南旨在说明使用 ragas 测试和评估LLM应用程序的简单工作流程。它假定读者在AI应用构建和评估方面具备最少知识。请参考我们的安装说明来安装 ragas

获取一个工作示例

要最快地看到这些概念的实际应用,可以使用快速入门命令创建一个项目。

uvx ragas quickstart rag_eval
cd rag_eval
uv sync
pip install ragas
ragas quickstart rag_eval
cd rag_eval
uv sync

这将生成一个带有示例代码的完整项目。跟随本指南,了解你生成的代码中发生了什么。让我们开始吧!

项目结构

以下是为你创建的内容

rag_eval/
├── README.md             # Project documentation and setup instructions
├── pyproject.toml        # Project configuration for uv and pip
├── evals.py              # Your evaluation workflow
├── rag.py                # Your RAG/LLM application
├── __init__.py           # Makes this a Python package
└── evals/                # Evaluation artifacts
    ├── datasets/         # Test data files (optional)
    ├── experiments/      # Results from running evaluations (CSV files saved here)
    └── logs/             # Evaluation execution logs

需要关注的关键文件

  • evals.py - 你的评估工作流程,包含数据集加载和评估逻辑
  • rag.py - 你的 RAG/LLM 应用程序代码(查询引擎、检索等)

理解代码

在你生成的项目的 evals.py 文件中,你会看到主要的工作流程模式

  1. 加载数据集 - 使用 SingleTurnSample 定义你的测试用例
  2. 查询 RAG 系统 - 从你的应用程序获取响应
  3. 评估响应 - 根据基准真实值验证响应
  4. 显示结果 - 在控制台中显示评估摘要
  5. 保存结果 - 自动保存为 CSV 文件到 evals/experiments/ 目录

该模板提供了可以自定义的模块化函数

from ragas.dataset_schema import SingleTurnSample
from ragas import EvaluationDataset

def load_dataset():
    """Load test dataset for evaluation."""
    data_samples = [
        SingleTurnSample(
            user_input="What is Ragas?",
            response="",  # Will be filled by querying RAG
            reference="Ragas is an evaluation framework for LLM applications",
            retrieved_contexts=[],
        ),
        # Add more test cases...
    ]
    return EvaluationDataset(samples=data_samples)

你可以使用指标和更复杂的评估逻辑来扩展它。了解更多关于Ragas中的评估

选择你的LLM提供商

你的快速入门项目默认在 _init_clients() 函数中初始化 OpenAI LLM。你可以通过 llm_factory 轻松切换到任何提供商。

设置你的 OpenAI API 密钥

export OPENAI_API_KEY="your-openai-key"

在你的 evals.py_init_clients() 函数中

from ragas.llms import llm_factory

llm = llm_factory("gpt-4o")

这已在你的快速入门项目中设置好!

设置你的 Anthropic API 密钥

export ANTHROPIC_API_KEY="your-anthropic-key"

在你的 evals.py_init_clients() 函数中

from ragas.llms import llm_factory

llm = llm_factory("claude-3-5-sonnet-20241022", provider="anthropic")

设置你的 Google 凭据

export GOOGLE_API_KEY="your-google-api-key"

在你的 evals.py_init_clients() 函数中

from ragas.llms import llm_factory

llm = llm_factory("gemini-1.5-pro", provider="google")

在本地安装并运行 Ollama,然后在你的 evals.py_init_clients() 函数中

from ragas.llms import llm_factory

llm = llm_factory(
    "mistral",
    provider="ollama",
    base_url="https://:11434"  # Default Ollama URL
)

适用于任何具有 OpenAI 兼容 API 的 LLM

from ragas.llms import llm_factory

llm = llm_factory(
    "model-name",
    api_key="your-api-key",
    base_url="https://your-api-endpoint"
)

要了解更多详情,请学习LLM 集成

使用预构建的指标

ragas 附带了用于常见评估任务的预构建指标。例如,方面评判 (Aspect Critique) 使用 DiscreteMetric 评估你输出的任何方面。

from ragas.metrics import DiscreteMetric
from ragas.llms import llm_factory

# Setup your evaluator LLM
evaluator_llm = llm_factory("gpt-4o")

# Create a custom aspect evaluator
metric = DiscreteMetric(
    name="summary_accuracy",
    allowed_values=["accurate", "inaccurate"],
    prompt="""Evaluate if the summary is accurate and captures key information.

Response: {response}

Answer with only 'accurate' or 'inaccurate'.""",
    llm=evaluator_llm
)

# Score your application's output
score = await metric.ascore(
    response="The summary of the text is..."
)
print(f"Score: {score.value}")  # 'accurate' or 'inaccurate'
print(f"Reason: {score.reason}")

像这样的预构建指标让你无需从头定义评估逻辑。探索所有可用指标

信息

ragas 中还有许多其他类型的指标可用(无论是否带有 reference),如果这些都不符合你的情况,你也可以创建自己的指标。要进一步探索,请查看更多关于指标的内容

在数据集上进行评估

在你的快速入门项目中,你会在 load_dataset() 函数中看到,它创建了包含多个样本的测试数据。

from ragas import Dataset

# Create a dataset with multiple test samples
dataset = Dataset(
    name="test_dataset",
    backend="local/csv",  # Can also use JSONL, Google Drive, or in-memory
    root_dir=".",
)

# Add samples to the dataset
data_samples = [
    {
        "user_input": "What is ragas?",
        "response": "Ragas is an evaluation framework...",
        "expected": "Ragas provides objective metrics..."
    },
    {
        "user_input": "How do metrics work?",
        "response": "Metrics score your application...",
        "expected": "Metrics evaluate performance..."
    },
]

for sample in data_samples:
    dataset.append(sample)

# Save to disk
dataset.save()

这为你提供了多个测试用例,而不是一次只评估一个例子。了解更多关于数据集和实验

你生成的项目在 evals/datasets/ 文件夹中包含了示例数据——你可以编辑这些文件来添加更多测试用例。

需要帮助使用评估来改进你的AI应用吗?

在过去的两年里,我们见证并帮助了许多 AI 应用通过评估得到改进。

我们正在将这些知识压缩成一个产品,用评估循环取代感觉检查,这样您就可以专注于构建卓越的 AI 应用。

如果你希望在使用评估来改进和扩展你的 AI 应用方面获得帮助。

🔗 预约时间或给我们留言:founders@vibrantlabs.com

下一步