RAGAS的ContextRecall指标分析

示例代码

ragas版本:0.4.2

ContextRecall指标使用:

https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/context_recall/

import os

from openai import AsyncOpenAI
from ragas.llms import llm_factory
from ragas.metrics.collections import ContextRecall

# 1. 设置 LLM 客户端
# 初始化异步 OpenAI 客户端
# 从环境变量中获取 API Key 和 Base URL (通常用于兼容 OpenAI 接口的模型,如 DeepSeek, Kimi 等)
async_openai_client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"),
                                  base_url=os.environ.get("OPENAI_BASE_URL"))

# 2. 创建评估用 LLM 实例
# 使用 ragas 的 llm_factory 包装客户端
# 这里的模型被指定为 "deepseek-v3.2" (也就是用 DeepSeek 模型作为裁判/评估者)
# max_tokens: 设置生成的最大 token 数,防止输出截断
# evaluator_llm = llm_factory("kimi-k2-thinking-turbo", client=async_openai_client)
evaluator_llm = llm_factory("deepseek-v3.2", client=async_openai_client, max_tokens=32768)

# 3. 创建指标对象
# 初始化 ContextRecall 指标
# ContextRecall 用于衡量检索到的上下文 (retrieved_contexts) 是否足以推导出参考答案 (reference)
contextRecall = ContextRecall(llm=evaluator_llm)

# 4. 执行评估
# 调用 score 方法计算分数
result = contextRecall.score(
    user_input="埃菲尔铁塔位于哪里?",  # 用户的原始查询
    retrieved_contexts=[
        "巴黎是法国的首都。",
        "埃菲尔铁塔位于巴黎。"
    ],                                # RAG 系统检索到的文档片段列表
    reference="埃菲尔铁塔位于巴黎。他的名字叫汤姆。"     # 标准答案 (Ground Truth)
)

# 5. 输出结果
# 打印上下文召回率得分 (范围通常是 0 到 1,1 表示完全召回)
print(f"Context Recall Score: {
     
     result.value}")

源码分析

源码位置:ragas\metrics\collections\context_recall\metric.py

async def ascore(
    self,
    user_input: str,
    retrieved_contexts: List[str],
    reference: str,
) -> MetricResult:
    """
    Calculate context recall score asynchronously.

    Components are guaranteed to be validated and non-None by the base class.

    Args:
        user_input: The original question
        retrieved_contexts: List of retrieved context strings
        reference: The reference answer to evaluate

    Returns:
        MetricResult with recall score (0.0-1.0, higher is better)
    """
    # Input validation
    if not user_input:
        raise ValueError("user_input cannot be empty")
    if not reference:
        raise ValueError("reference cannot be empty")
    if not retrieved_contexts:
        raise ValueError("retrieved_contexts cannot be empty")

    # Combine contexts into a single string
    context = "\n".join(retrieved_contexts) if retrieved_contexts else ""

    # Create input data and generate prompt
    input_data = ContextRecallInput(
        question=user_input, context=context, answer=reference
    )
    prompt_string = self.prompt.to_string(input_data)

    # Ge
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shulu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值