LlamaIndex

LlamaIndex

LlamaIndex는 LLM 애플리케이션이 사적이거나 도메인 특화된 데이터를 수집(ingest)·구조화·접근할 수 있게 하는 데이터 프레임워크예요. LLM을 여러분의 데이터와 연결하는 걸 아주 쉽게 만들어 주죠. 하지만 LlamaIndex와 데이터에 가장 좋은 구성을 찾으려면 성능의 객관적 측정치가 필요해요. 여기서 ragas가 등장해요. Ragas는 QueryEngine을 평가하고, 가장 높은 점수를 얻도록 구성을 조정할 수 있는 확신을 줘요.

출처: 문서

본문

이 가이드는 LlamaIndex 프레임워크에 익숙하다고 가정해요.

테스트셋 구축

QueryEngine을 평가하려면 테스트셋이 필요해요. 직접 만들거나, Ragas의 Testset Generator 모듈을 사용해 작은 합성 테스트셋으로 시작할 수 있어요.

LlamaIndex에서 어떻게 동작하는지 볼게요.

문서 로드

from llama_index.core import SimpleDirectoryReader

documents = SimpleDirectoryReader("./nyc_wikipedia").load_data()

이제 해당 generator와 critic LLM으로 TestsetGenerator 객체를 초기화해 보겠습니다.

from ragas.testset import TestsetGenerator

from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding

# generator with openai models
generator_llm = OpenAI(model="gpt-4o")
embeddings = OpenAIEmbedding(model="text-embedding-3-large")

generator = TestsetGenerator.from_llama_index(
    llm=generator_llm,
    embedding_model=embeddings,
)

이제 데이터셋을 생성할 준비가 됐어요.

# generate testset
testset = generator.generate_with_llamaindex_docs(
    documents,
    testset_size=5,
)

df = testset.to_pandas()
df.head()

QueryEngine을 테스트할 테스트 데이터셋이 생겼으니, 이제 QueryEngine을 만들고 평가해 보겠습니다.

QueryEngine 구축

시작하려면 예시로 뉴욕시 위키백과 페이지 위에 VectorStoreIndex 를 만들고 ragas로 평가해 볼게요.

이미 데이터셋을 documents로 로드했으니 그것을 사용하겠습니다.

# build query engine
from llama_index.core import VectorStoreIndex

vector_index = VectorStoreIndex.from_documents(documents)

query_engine = vector_index.as_query_engine()

생성된 테스트셋의 샘플 질문을 시도해 동작하는지 확인해 보겠습니다.

# convert it to pandas dataset
df = testset.to_pandas()
df["user_input"][0]
'Cud yu pleese explane the role of New York City within the Northeast megalopolis, and how it contributes to the cultural and economic vibrancy of the region?'
response_vector = query_engine.query(df["user_input"][0])

print(response_vector)
New York City serves as a key hub within the Northeast megalopolis, playing a significant role in enhancing the cultural and economic vibrancy of the region. Its status as a global center of creativity, entrepreneurship, and cultural diversity contributes to the overall dynamism of the area. The city's renowned arts scene, including Broadway theatre and numerous cultural institutions, attracts artists and audiences from around the world, enriching the cultural landscape of the Northeast megalopolis. Economically, New York City's position as a leading financial and fintech center, home to major stock exchanges and a bustling real estate market, bolsters the region's economic strength and influence. Additionally, the city's diverse culinary scene, influenced by its immigrant history, adds to the cultural richness of the region, making New York City a vital component of the Northeast megalopolis's cultural and economic tapestry.

QueryEngine 평가

이제 VectorStoreIndex 용 QueryEngine이 생겼으니, Ragas가 가진 llama_index 통합을 사용해 평가할 수 있어요.

Ragas와 LlamaIndex로 평가를 실행하려면 3가지가 필요해요.

  • LlamaIndex QueryEngine : 평가할 대상
  • 메트릭 : Ragas는 QueryEngine 의 다양한 측면을 측정하는 메트릭 집합을 정의해요. 사용 가능한 메트릭과 그 의미는 여기에서 찾을 수 있어요
  • 질문 : ragas가 QueryEngine 을 테스트할 질문 목록

먼저 질문을 생성해 보겠습니다. 이상적으로는 프로덕션에서 보는 질문을 사용해서, 우리가 평가하는 질문의 분포가 프로덕션에서 보는 질문의 분포와 일치하도록 해야 해요. 이렇게 하면 점수가 프로덕션 성능을 반영하지만, 시작할 때는 몇 가지 예시 질문을 사용하겠습니다.

이제 평가에 사용할 메트릭을 import 해 보겠습니다.

# import metrics
from ragas.metrics import (
    Faithfulness,
    AnswerRelevancy,
    ContextPrecision,
    ContextRecall,
)

# init metrics with evaluator LLM
from ragas.llms import LlamaIndexLLMWrapper

evaluator_llm = LlamaIndexLLMWrapper(OpenAI(model="gpt-4o"))
metrics = [
    Faithfulness(llm=evaluator_llm),
    AnswerRelevancy(llm=evaluator_llm),
    ContextPrecision(llm=evaluator_llm),
    ContextRecall(llm=evaluator_llm),
]

evaluate() 함수는 메트릭에 대해 "question"과 "ground_truth" 딕셔너리를 기대해요. 테스트셋을 그 형식으로 쉽게 변환할 수 있어요.

# convert to Ragas Evaluation Dataset
ragas_dataset = testset.to_evaluation_dataset()
ragas_dataset
EvaluationDataset(features=['user_input', 'reference_contexts', 'reference'], len=6)

마지막으로 평가를 실행해 보겠습니다.

from ragas.integrations.llama_index import evaluate

result = evaluate(
    query_engine=query_engine,
    metrics=metrics,
    dataset=ragas_dataset,
)

# final scores
print(result)
{'faithfulness': 0.7454, 'answer_relevancy': 0.9348, 'context_precision': 0.6667, 'context_recall': 0.4667}

pandas DataFrame으로 변환해 더 많은 분석을 실행할 수 있어요.

result.to_pandas()

더 알아보기 (Learn more)