간단한 RAG 시스템 평가하기

간단한 RAG 시스템 평가하기 (Evaluate a simple RAG system)

이 튜토리얼에서는 RAG(Retrieval-Augmented Generation) 시스템을 평가하는 간단한 평가 파이프라인을 작성해 봐요. 평가 주도 개발(evaluation-driven development)로 RAG 시스템을 평가하고 개선하는 법을 배울 수 있어요.

출처: 문서

본문

flowchart LR
    A["Query<br/>'What is Ragas 0.3?'"] --> B[Retrieval System]

    C[Document Corpus<br/> Ragas 0.3 Docs📄] --> B

    B --> D[LLM + Prompt]
    A --> D

    D --> E[Final Answer]

먼저 문서 모음(corpus)에서 관련 문서를 검색하고 LLM으로 답변을 생성하는 간단한 RAG 시스템을 작성해요.

python -m ragas_examples.rag_eval.rag

다음으로 RAG 시스템을 위한 몇 가지 샘플 질의와 기대 출력을 적고, 이를 CSV 파일로 변환해요.

import pandas as pd

samples = [
    {"query": "What is Ragas 0.3?", "grading_notes": "- Ragas 0.3 is a library for evaluating LLM applications."},
    {"query": "How to install Ragas?", "grading_notes": "- install from source  - install from pip using ragas[examples]"},
    {"query": "What are the main features of Ragas?", "grading_notes": "organised around - experiments - datasets - metrics."}
]
pd.DataFrame(samples).to_csv("datasets/test_dataset.csv", index=False)

RAG 시스템의 성능을 평가하기 위해, RAG 시스템의 출력을 채점 노트(grading notes)와 비교해 pass/fail을 돌려주는 LLM 기반 지표를 정의해요.

from ragas.metrics import DiscreteMetric
my_metric = DiscreteMetric(
    name="correctness",
    prompt = "Check if the response contains points mentioned from the grading notes and return 'pass' or 'fail'.\nResponse: {response} Grading Notes: {grading_notes}",
    allowed_values=["pass", "fail"],
)

이제 테스트 데이터셋에서 RAG 시스템을 실행하고 지표로 평가한 뒤 결과를 CSV 파일에 저장하는 실험 루프를 작성해요.

@experiment()
async def run_experiment(row):
    response = rag_client.query(row["query"])

    score = my_metric.score(
        llm=llm,
        response=response.get("answer", " "),
        grading_notes=row["grading_notes"]
    )

    experiment_view = {
        **row,
        "response": response.get("answer", ""),
        "score": score.value,
        "log_file": response.get("logs", " "),
    }
    return experiment_view

이제 RAG 파이프라인에 어떤 변경을 가하든 실험을 실행해서 RAG 성능에 어떤 영향을 주는지 확인할 수 있어요.

예제를 처음부터 끝까지 실행하기

  1. OpenAI API 키 설정하기
export OPENAI_API_KEY="your_openai_api_key"
  1. 평가 실행하기
python -m ragas_examples.rag_eval.evals

축하해요! Ragas로 첫 평가를 성공적으로 실행했어요. 이제 experiments/experiment_name.csv 파일을 열어 결과를 확인하면 돼요.

더 알아보기 (Learn more)