Skip to content

Ragas安装与使用

安装

安装

bash
pip install ragas -i https://mirrors.aliyun.com/pypi/simple --trusted-host=mirrors.aliyun.com

查看版本

python
import ragas

print(ragas.__version__)

已有测试数据集 (Evaluation)

假设已经有了一组测试数据,包含:question (问题), answer (模型回答), contexts (检索到的文档片段列表), ground_truth (可选的标准答案)。

python
from datasets import Dataset
from ragas import evaluate
from ragas.metrics import (
    faithfulness,
    answer_relevancy,
    context_precision,
    context_recall,
)
from langchain_ollama import OllamaEmbeddings
from langchain.chat_models import init_chat_model


# 1. 准备数据
# contexts 必须是列表的列表,例如 [["doc1", "doc2"], ["doc3"]]
data_samples = {
    "question": ["什么是RAG?", "如何安装Ragas?"],
    "answer": ["RAG是检索增强生成...", "使用pip install ragas..."],
    "contexts": [
        ["RAG (Retrieval-Augmented Generation) is a technique..."],
        ["You can install ragas via pip command..."],
    ],
    # ground_truth 是可选的,如果有,可以计算 context_recall 等更精确的指标
    "ground_truth": ["RAG combines retrieval and generation...", "pip install ragas"],
}
dataset = Dataset.from_dict(data_samples)


# 2. 配置 LLM 和 Embedding 模型 (用于评估裁判)
# 注意:评估用的模型最好比业务模型更强(如用 GPT-4o 评估业务用的 GPT-3.5)
MODEL = "deepseek-v3.2"
API_KEY = "sk-"
BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"

llm_judge = init_chat_model(
    model=MODEL, model_provider="openai", api_key=API_KEY, base_url=BASE_URL
)
embeddings = OllamaEmbeddings(model="bge-m3", base_url="http://127.0.0.1:11434")


# 3. 执行评估
results = evaluate(
    dataset=dataset,
    metrics=[
        faithfulness,  # 忠实度
        answer_relevancy,  # 答案相关性
        context_precision,  # 上下文精确度
        context_recall,  # 上下文召回率 (需要 ground_truth)
    ],
    llm=llm_judge,
    embeddings=embeddings,
    raise_exceptions=False,  # 遇到错误不中断,返回 NaN
)

# 4. 查看结果
print(results)
# 转换为 pandas DataFrame 方便分析
df = results.to_pandas()
print(df[["faithfulness", "answer_relevancy", "context_precision", "context_recall"]])

输出结果示例

bash
Evaluating: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:27<00:00,  3.45s/it]
{'faithfulness': 1.0000, 'answer_relevancy': 0.9509, 'context_precision': 1.0000, 'context_recall': 1.0000}
   faithfulness  answer_relevancy  context_precision  context_recall
0           1.0          0.973654                1.0             1.0
1           1.0          0.928051                1.0             1.0

没有测试数据 (Synthetic Data Generation)

从你的知识库文档中自动生成测试题

python