응답 관련성(Response Relevancy)

응답 관련성(Response Relevancy)

응답 관련성은 응답이 사용자 입력과 얼마나 관련 있는지 측정하는 지표예요. 0에서 1 사이의 점수로 나타나며, 점수가 높을수록 사용자 입력과 더 잘 맞아떨어진다는 뜻이에요. 이 지표는 답변이 질문의 의도를 얼마나 잘 따르는지에 초점을 맞춰요.

출처: 문서

본문

답변 관련성(Answer Relevancy)

Answer Relevancy 지표는 응답이 사용자 입력과 얼마나 관련 있는지 측정해요. 0에서 1 사이이며, 점수가 높을수록 사용자 입력과 더 잘 맞아떨어진다는 뜻이에요.

답변이 원래 질문을 직접적이고 적절하게 다루면 관련성이 있다고 간주돼요. 이 지표는 사실적 정확성을 평가하지 않고 답변이 질문의 의도를 얼마나 잘 맞추는지에 초점을 맞춰요. 불완전하거나 불필요한 세부사항을 포함하는 답변에는 패널티를 줘요.

이 지표는 user_inputresponse를 사용해 다음과 같이 계산돼요:

  1. 응답에 기반해 인공 질문 집합(기본 3개)을 생성해요. 이 질문들은 응답의 내용을 반영하도록 설계돼요.
  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 파라미터로 설정 가능).

Note: 점수는 보통 0과 1 사이에 떨어지지만, 코사인 유사도의 수학적 범위가 -1에서 1이므로 보장되지는 않아요.

예시(Example)

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}")

출력(Output):

Answer Relevancy Score: 0.9165088378587264

동기 사용법(Synchronous Usage) 동기 코드를 선호한다면 .ascore() 대신 .score() 메서드를 쓸 수 있어요: result = scorer.score( user_input="When was the first super bowl?", response="The first superbowl was held on Jan 15, 1967" )

계산 방법(How It's Calculated)

예시(Example) 질문: Where is France and what is it's capital? 낮은 관련성 답변: France is in western Europe. 높은 관련성 답변: France is in western Europe and Paris is its capital.

주어진 질문에 대한 답변의 관련성을 계산하기 위해 두 단계를 따라가요:

  • Step 1: LLM을 사용해 생성된 답변에서 질문의 'n'개 변형을 역설계해요. 예를 들어 첫 번째 답변에 대해 LLM은 다음과 같은 가능한 질문을 생성할 수 있어요:

Question 1: "In which part of Europe is France located?" Question 2: "What is the geographical location of France within Europe?" Question 3: "Can you identify the region of Europe where France is situated?"

  • Step 2: 생성된 질문들과 실제 질문 사이의 평균 코사인 유사도를 계산해요.

기본 개념은 답변이 질문을 올바르게 다루고 있다면, 원래 질문을 답변만으로 재구성할 가능성이 매우 높다는 거예요.

레거시 지표 API(Legacy Metrics API)

다음 예시는 레거시 지표 API 패턴을 사용해요. 새 프로젝트에는 위에서 보여준 컬렉션 기반 API를 권장해요.

폐지 일정(Deprecation Timeline) 이 API는 버전 0.4에서 폐지되고 버전 1.0에서 제거될 예정이에요. 위에 보여준 컬렉션 기반 API로 마이그레이션해주세요.

SingleTurnSample과 함께하는 예시(Example with 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)

출력(Output):

0.9165088378587264

더 알아보기 (Learn more)