ragas官方文档中文版(六十五)

操作指南

本节中的每个指南都针对您作为有经验的用户在使用 Ragas 时可能遇到的实际问题提供了专注的解决方案。这些指南设计得简洁直接,为您的问题提供快速解决方案。我们假设您对 Ragas 的概念有基本了解且能够熟练使用。如果不是,请先浏览 快速入门 (Get Started)部分。

LlamaIndex 集成

LlamaIndex 是一个用于 LLM 应用的数据框架,用于导入、结构化和访问私有或领域特定数据。它让连接 LLM 与您自己的数据变得非常简单。但为了找到最适合 LlamaIndex 和您数据的配置,您需要一个客观的性能衡量指标。这就是 Ragas 的用武之地。Ragas 将帮助您评估 QueryEngine,并让您有信心调整配置以获得最高分数。

本指南假设您熟悉 LlamaIndex 框架。

构建测试集

您需要一个测试集来评估 QueryEngine。您可以自己构建一个,或者使用 Ragas 中的测试集生成器模块来快速创建一个小型合成测试集。

让我们看看如何在 LlamaIndex 中实现这一点:

加载文档

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

现在让我们使用相应的生成器和评判 LLM 初始化 TestsetGenerator 对象。

fromragas.testsetimportTestsetGeneratorfromllama_index.llms.openaiimportOpenAIfromllama_index.embeddings.openaiimportOpenAIEmbedding# generator with openai modelsgenerator_llm=OpenAI(model="gpt-4o")embeddings=OpenAIEmbedding(model="text-embedding-3-large")generator=TestsetGenerator.from_llama_index(llm=generator_llm,embedding_model=embeddings,)

现在您已准备好生成数据集:

# generate testsettestset=generator.generate_with_llamaindex_docs(documents,testset_size=5,)
df=testset.to_pandas()df.head()
user_inputreference_contextsreference synthesizer_name
0Cud yu pleese explane the role of New York Cit…[New York, often called New York City or NYC, …New York City serves as the geographical and d…
1So like, what was New York City called before …[History == === Early history === In the pre-C…Before it was called New York, the area was kn…
2what happen in new york with slavery and how i…[and rechristened it “New Orange” after Willia…In the early 18th century, New York became a c…
3What historical significance does Long Island …[<1-hop>\n\nHistory == === Early history === I…Long Island holds historical significance in t…
4What role does the Staten Island Ferry play in…[<1-hop>\n\nto start service in 2017; this wou…The Staten Island Ferry plays a significant ro…

有了测试数据集来测试我们的 QueryEngine,现在让我们构建一个并进行评估。

构建 QueryEngine

首先,让我们以纽约市维基百科页面为例,构建一个 VectorStoreIndex ,然后使用 Ragas 对其进行评估。

由于我们已经将数据集加载到文档中,让我们直接使用它。

# build query enginefromllama_index.coreimportVectorStoreIndex vector_index=VectorStoreIndex.from_documents(documents)query_engine=vector_index.as_query_engine()

让我们尝试从生成的测试集中选择一个示例问题,看看它是否正常工作。

# convert it to pandas datasetdf=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 servesasa key hub within the Northeast megalopolis,playing a significant roleinenhancing the culturalandeconomic vibrancy of the region.Its statusasaglobalcenter of creativity,entrepreneurship,andcultural 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 positionasa leading financialandfintech center,home to major stock exchangesanda 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 culturalandeconomic tapestry.

评估 QueryEngine

现在我们有了 VectorStoreIndex 的 QueryEngine ,可以使用 Ragas 提供的 LlamaIndex 集成来评估它。

要使用 Ragas 和 LlamaIndex 运行评估,您需要三个要素:

  1. LlamaIndex QueryEngine :我们将要评估的对象
  2. 指标 :Ragas 定义了一组可以衡量 QueryEngine 不同方面的指标。可用指标及其含义可以在此处找到
  3. 问题 :Ragas 将用来测试 QueryEngine 的问题列表

首先让我们生成问题。理想情况下,您应该使用生产环境中实际看到的问题,这样我们评估时使用的问题分布就与生产环境中看到的问题分布相匹配。这确保了分数反映生产环境中的性能,但为了快速开始,我们将使用几个示例问题。

现在让我们导入将要用于评估的指标。

# import metricsfromragas.metricsimport(Faithfulness,AnswerRelevancy,ContextPrecision,ContextRecall,)# init metrics with evaluator LLMfromragas.llmsimportLlamaIndexLLMWrapper 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 Datasetragas_dataset=testset.to_evaluation_dataset()ragas_dataset
EvaluationDataset(features=['user_input','reference_contexts','reference'],len=6)

最后,让我们运行评估。

fromragas.integrations.llama_indeximportevaluate result=evaluate(query_engine=query_engine,metrics=metrics,dataset=ragas_dataset,)
# final scoresprint(result)
# final scoresprint(result)

您可以将结果转换为 pandas DataFrame 以进行更多分析:

result.to_pandas()
user_inputretrieved_contextsreference_contextsresponsereferencefaithfulnessanswer_relevancycontext_precisioncontext_recall
0Cud yu pleese explane the role of New York Cit…[and its ideals of liberty and peace. In the 2…[New York, often called New York City or NYC, …New York City plays a significant role within …New York City serves as the geographical and d…0.6153850.9182170.00.0
1So like, what was New York City called before …[New York City is the headquarters of the glob…[History ===== Early history === In the pre-C…New York City was named New Amsterdam before i…Before it was called New York, the area was kn…1.0000000.9678211.01.0
2what happen in new york with slavery and how i…[=== Province of New York and slavery ===\n\nI…[and rechristened it “New Orange” after Willia…Slavery became a significant part of New York’…In the early 18th century, New York became a c…1.000000 0.9192641.01.0
3What historical significance does Long Island …[==== River crossings ====\n\nNew York City is…[<1-hop>\n\nHistory == === Early history === I…Long Island played a significant role in the e…Long Island holds historical significance in t…0.5000000.9318950.00.0
4What role does the Staten Island Ferry play in…[==== Buses ====\n\nNew York City’s public bus…[<1-hop>\n\nto start service in 2017; this wou…The Staten Island Ferry serves as a vital mode…The Staten Island Ferry plays a significant ro…0.5000000.9369201.00.0
5How does Central Park’s role as a cultural and…[==== State parks ====\n\nThere are seven stat…[<1-hop>\n\nCity has over 28,000 acres (110 km…Central Park’s role as a cultural and historic…Central Park, located in middle-upper Manhatta…0.8571430.9348411.00.8