Ragas Ragas
stable · 中文译文

Answer Relevancy(答案相关性)

Answer Relevancy 指标衡量回答与用户输入的相关程度。范围为 0 到 1,分数越高表示与用户输入的对齐越好。

如果答案直接且恰当地回应了原始问题,则认为该答案相关。此指标关注答案与问题意图的匹配程度,而不评估事实准确性。它会惩罚不完整或包含不必要细节的答案。

此指标使用 user_input 和 response 按如下方式计算:

  1. 基于 response 生成一组人工问题(默认 3 个)。这些问题旨在反映 response 的内容。
  2. 计算用户输入的嵌入 ((E_o)) 与每个生成问题的嵌入 ((E_{g_i})) 之间的余弦相似度。
  3. 取这些余弦相似度分数的平均值,得到 Answer Relevancy:

[ \text{Answer Relevancy} = \frac{1}{N} \sum_{i=1}^{N} \text{cosine similarity}(E_{g_i}, E_o) ]

[ \text{Answer Relevancy} = \frac{1}{N} \sum_{i=1}^{N} \frac{E_{g_i} \cdot E_o}{|E_{g_i}| |E_o|} ]

其中:

  • (E_{g_i}):第 (i^{th}) 个生成问题的嵌入。
  • (E_o):用户输入的嵌入。
  • (N):生成问题的数量(默认为 3,可通过 strictness 参数配置)。

注意:虽然分数通常落在 0 到 1 之间,但由于余弦相似度的数学范围为 -1 到 1,这一点并不保证。

示例

from openai import AsyncOpenAI
from ragas.llms import llm_factory
from ragas.embeddings.base import embedding_factory
from ragas.metrics.collections import AnswerRelevancy

# Setup LLM and embeddings
client = AsyncOpenAI()
llm = llm_factory("gpt-4o-mini", client=client)
embeddings = embedding_factory("openai", model="text-embedding-3-small", client=client)

# Create metric
scorer = AnswerRelevancy(llm=llm, embeddings=embeddings)

# Evaluate
result = await scorer.ascore(
    user_input="When was the first super bowl?",
    response="The first superbowl was held on Jan 15, 1967"
)
print(f"Answer Relevancy Score: {result.value}")

输出:

Answer Relevancy Score: 0.9165088378587264

同步用法

如果你更喜欢同步代码,可以使用 .score() 方法代替 .ascore():

result = scorer.score(
    user_input="When was the first super bowl?",
    response="The first superbowl was held on Jan 15, 1967"
)

计算方式

示例

问题:Where is France and what is it's capital?

低相关性答案:France is in western Europe.

高相关性答案:France is in western Europe and Paris is its capital.

要计算答案与给定问题的相关性,我们遵循两个步骤:

  • 步骤 1: 使用大语言模型(LLM)从生成的答案反向工程出 'n' 个问题变体。例如,对于第一个答案,LLM 可能会生成以下可能的问题:

  • 问题 1: "In which part of Europe is France located?"

  • 问题 2: "What is the geographical location of France within Europe?"
  • 问题 3: "Can you identify the region of Europe where France is situated?"

  • 步骤 2: 计算生成的问题与实际问题之间的平均余弦相似度。

其底层概念是:如果答案正确回应了问题,那么仅从答案重建原始问题的概率就很高。

旧版 Metrics API

以下示例使用旧版 metrics API 模式。对于新项目,我们建议使用上文所示的 collections-based API。

弃用时间表

此 API 将在 0.4 版本中弃用,并在 1.0 版本中移除。请迁移到上文所示的 collections-based API。

使用 SingleTurnSample 的示例

from ragas import SingleTurnSample 
from ragas.metrics import ResponseRelevancy

sample = SingleTurnSample(
        user_input="When was the first super bowl?",
        response="The first superbowl was held on Jan 15, 1967",
        retrieved_contexts=[
            "The First AFL–NFL World Championship Game was an American football game played on January 15, 1967, at the Los Angeles Memorial Coliseum in Los Angeles."
        ]
    )

scorer = ResponseRelevancy(llm=evaluator_llm, embeddings=evaluator_embeddings)
await scorer.single_turn_ascore(sample)

输出:

0.9165088378587264