RAG 평가 소개

LangChain을 활용한 RAG(검색 증강 생성)

Meri Nova

Machine Learning Engineer

RAG 평가 유형

검색 프로세스, LLM 환각, 입력 질문에 대한 답변 관련성, 참조 답변과의 비교 등 평가 가능한 프로세스를 강조한 RAG 워크플로우.

1 이미지 출처: LangSmith
LangChain을 활용한 RAG(검색 증강 생성)

출력 정확도: 문자열 평가

query = "What are the main components of RAG architecture?"
predicted_answer = "Training and encoding"
ref_answer = "Retrieval and Generation"
LangChain을 활용한 RAG(검색 증강 생성)

출력 정확도: 문자열 평가

prompt_template = """You are an expert professor specialized in grading students' answers to questions.
You are grading the following question:{query}
Here is the real answer:{answer}
You are grading the following predicted answer:{result}
Respond with CORRECT or INCORRECT:
Grade:"""

prompt = PromptTemplate(
    input_variables=["query", "answer", "result"],
    template=prompt_template
)

eval_llm = ChatOpenAI(temperature=0, model="gpt-4o-mini", openai_api_key='...')
LangChain을 활용한 RAG(검색 증강 생성)

출력 정확도: 문자열 평가

from langsmith.evaluation import LangChainStringEvaluator

qa_evaluator = LangChainStringEvaluator(
    "qa",
    config={
        "llm": eval_llm,
        "prompt": PROMPT
    }
)

score = qa_evaluator.evaluator.evaluate_strings( prediction=predicted_answer, reference=ref_answer, input=query )
LangChain을 활용한 RAG(검색 증강 생성)

출력 정확도: 문자열 평가

print(f"Score: {score}")
Score: {'reasoning': 'INCORRECT', 'value': 'INCORRECT', 'score': 0}
query = "What are the main components of RAG architecture?"
predicted_answer = "Training and encoding"
ref_answer = "Retrieval and Generation"
LangChain을 활용한 RAG(검색 증강 생성)

Ragas 프레임워크

생성 메트릭과 검색 메트릭을 비교하는 표.

1 이미지 출처: Ragas
LangChain을 활용한 RAG(검색 증강 생성)

충실도(Faithfulness)

  • 생성된 출력이 컨텍스트를 충실히 반영하는가?

 

$$ \text{Faithfulness} = \frac{\text{No. of claims made that can be inferred from the context}}{\text{Total no. of claims}} $$

  • 정규화 범위: (0, 1)
LangChain을 활용한 RAG(검색 증강 생성)

충실도 평가

from langchain_openai import ChatOpenAI, OpenAIEmbeddings

from ragas.integrations.langchain import EvaluatorChain from ragas.metrics import faithfulness
llm = ChatOpenAI(model="gpt-4o-mini", api_key="...") embeddings = OpenAIEmbeddings(model="text-embedding-3-small", api_key="...")
faithfulness_chain = EvaluatorChain( metric=faithfulness, llm=llm, embeddings=embeddings )
LangChain을 활용한 RAG(검색 증강 생성)

충실도 평가

eval_result = faithfulness_chain({

"question": "How does the RAG model improve question answering with LLMs?",
"answer": "The RAG model improves question answering by combining the retrieval of documents...",
"contexts": [ "The RAG model integrates document retrieval with LLMs by first retrieving relevant passages...", "By incorporating retrieval mechanisms, RAG leverages external knowledge sources, allowing the...", ]
})
print(eval_result)
'faithfulness': 1.0
LangChain을 활용한 RAG(검색 증강 생성)

컨텍스트 정밀도

  • 검색된 문서가 쿼리와 얼마나 관련성이 높은가?
  • 정규화 범위: (0, 1)1 = 매우 관련성 높음
from ragas.metrics import context_precision

llm = ChatOpenAI(model="gpt-4o-mini", api_key="...")
embeddings = OpenAIEmbeddings(model="text-embedding-3-small", api_key="...")

context_precision_chain = EvaluatorChain(
    metric=context_precision,
    llm=llm,
    embeddings=embeddings
)
LangChain을 활용한 RAG(검색 증강 생성)

컨텍스트 정밀도 평가

eval_result = context_precision_chain({
  "question": "How does the RAG model improve question answering with large language models?",
  "ground_truth": "The RAG model improves question answering by combining the retrieval of...",
  "contexts": [
    "The RAG model integrates document retrieval with LLMs by first retrieving...",
    "By incorporating retrieval mechanisms, RAG leverages external knowledge sources...",
  ]
})

print(f"Context Precision: {eval_result['context_precision']}")
Context Precision: 0.99999999995
LangChain을 활용한 RAG(검색 증강 생성)

연습해 봅시다!

LangChain을 활용한 RAG(검색 증강 생성)

Preparing Video For Download...