ragas官方文档中文版(五十)
操作指南本节中的每个指南都针对您作为有经验的用户在使用 Ragas 时可能遇到的实际问题提供了专注的解决方案。这些指南设计得简洁直接为您的问题提供快速解决方案。我们假设您对 Ragas 的概念有基本了解且能够熟练使用。如果不是请先浏览 快速入门 Get Started部分。如何评估和改进 RAG 应用在本指南中您将学习如何使用 Ragas 评估和迭代改进一个 RAG检索增强生成应用。您将完成的工作设置评估数据集建立衡量 RAG 性能的指标构建可重用的评估管道分析错误并系统地改进您的 RAG 应用学习如何利用 Ragas 进行 RAG 评估设置并运行 RAG 系统我们构建了一个简单的 RAG 系统从 Hugging Face 文档数据集中检索相关文档并使用 LLM 生成答案。该数据集包含许多 Hugging Face 包的文档页面以 markdown 格式存储为测试 RAG 能力提供了丰富的知识库。完整实现位于 ragas_examples/improve_rag要运行此应用请安装依赖项uv pipinstallragas-examples[improverag]然后运行 RAG 应用importosimportasynciofromopenaiimportAsyncOpenAIfromragas_examples.improve_rag.ragimportRAG,BM25Retriever# Set up OpenAI clientos.environ[OPENAI_API_KEY]your_keyopenai_clientAsyncOpenAI()# Create retriever and RAG systemretrieverBM25Retriever()ragRAG(openai_client,retriever)# Query the systemquestionWhat architecture is the tokenizers-linux-x64-musl binary designed for?resultasyncio.run(rag.query(question))print(fAnswer:{result[answer]})输出Answer:Its builtforthe x86_64 architecture(specifically the x86_64-unknown-linux-musl target —64-bit Linuxwithmusl libc).理解 RAG 实现上面的代码使用了一个简单的 RAG 类演示了核心的 RAG 模式。其工作原理如下# examples/ragas_examples/improve_rag/rag.pyfromtypingimportAny,Dict,OptionalfromopenaiimportAsyncOpenAIclassRAG:Simple RAG system for document retrieval and answer generation.def__init__(self,llm_client:AsyncOpenAI,retriever:BM25Retriever,system_promptNone,modelgpt-4o-mini,default_k3):self.llm_clientllm_client self.retrieverretriever self.modelmodel self.default_kdefault_k self.system_promptsystem_promptorAnswer only based on documents. Be concise.\n\nQuestion: {query}\nDocuments:\n{context}\nAnswer:asyncdefquery(self,question:str,top_k:Optional[int]None)-Dict[str,Any]:Query the RAG system.iftop_kisNone:top_kself.default_kreturnawaitself._naive_query(question,top_k)asyncdef_naive_query(self,question:str,top_k:int)-Dict[str,Any]:Handle naive RAG: retrieve once, then generate.# 1. Retrieve documents using BM25docsself.retriever.retrieve(question,top_k)ifnotdocs:return{answer:No relevant documents found.,retrieved_documents:[],num_retrieved:0}# 2. Build context from retrieved documentscontext\n\n.join([fDocument{i}:\n{doc.page_content}fori,docinenumerate(docs,1)])promptself.system_prompt.format(queryquestion,contextcontext)# 3. Generate response using OpenAI with retrieved contextresponseawaitself.llm_client.chat.completions.create(modelself.model,messages[{role:user,content:prompt}])return{answer:response.choices[0].message.content.strip(),retrieved_documents:[{content:doc.page_content,metadata:doc.metadata,document_id:i}fori,docinenumerate(docs)],num_retrieved:len(docs)}这展示了基本的 RAG 模式检索相关文档 → 注入提示词 → 生成答案。创建评估数据集我们将使用 huggingface_doc_qa_eval 这是一个关于 Hugging Face 文档的问答数据集。以下是数据集中的几个示例行QuestionExpected Answertokenizers-linux-x64-musl 二进制文件是为哪种架构设计的x86_64-unknown-linux-muslBLIP-Diffusion 模型的用途是什么The BLIP-Diffusion model is designed for controllable text-to-image generation and editing.Datasets server API 中 /healthcheck 端点的用途是什么Ensure the app is running评估脚本从此处下载数据集并将其转换为 Ragas Dataset 格式# examples/ragas_examples/improve_rag/evals.pyimporturllib.requestfrompathlibimportPathfromragasimportDatasetimportpandasaspddefdownload_and_save_dataset()-Path:dataset_pathPath(datasets/hf_doc_qa_eval.csv)dataset_path.parent.mkdir(exist_okTrue)ifnotdataset_path.exists():github_urlhttps://raw.githubusercontent.com/vibrantlabsai/ragas/main/examples/ragas_examples/improve_rag/datasets/hf_doc_qa_eval.csvurllib.request.urlretrieve(github_url,dataset_path)returndataset_pathdefcreate_ragas_dataset(dataset_path:Path)-Dataset:datasetDataset(namehf_doc_qa_eval,backendlocal/csv,root_dir.)dfpd.read_csv(dataset_path)for_,rowindf.iterrows():dataset.append({question:row[question],expected_answer:row[expected_answer]})dataset.save()returndataset了解更多关于使用数据集的信息请参阅核心概念 - 数据集Core Concepts - Datasets。设置 RAG 评估指标既然我们的评估数据集已准备就绪我们需要指标来衡量 RAG 性能。从简单、专注的指标开始这些指标直接衡量您的核心用例。有关指标的更多信息请参阅核心概念 - 指标Core Concepts - Metrics。在这里我们使用一个正确性离散指标correctness discrete metric用于评估 RAG 响应是否包含预期答案中的关键信息并且基于提供的上下文在事实层面是准确的。# examples/ragas_examples/improve_rag/evals.pyfromragas.metricsimportDiscreteMetric# Define correctness metriccorrectness_metricDiscreteMetric(namecorrectness,promptCompare the model response to the expected answer and determine if its correct. Consider the response correct if it: 1. Contains the key information from the expected answer 2. Is factually accurate based on the provided context 3. Adequately addresses the question asked Return pass if the response is correct, fail if its incorrect. Question: {question} Expected Answer: {expected_answer} Model Response: {response} Evaluation:,allowed_values[pass,fail],)既然我们有了评估指标我们需要在整个数据集上系统地运行它。这就是 Ragas 实验Ragas experiments的用途。创建评估实验实验函数在每个数据样本上运行您的 RAG 系统并使用我们的正确性指标评估响应。有关实验的更多信息请参阅核心概念 - 实验Core Concepts - Experimentation。实验函数接收包含问题、预期上下文和预期答案的数据集行然后使用问题查询 RAG 系统使用正确性指标评估响应返回详细结果包括分数和原因# examples/ragas_examples/improve_rag/evals.pyimportasynciofromtypingimportDict,Anyfromragasimportexperimentexperiment()asyncdefevaluate_rag(row:Dict[str,Any],rag:RAG,llm)-Dict[str,Any]: Run RAG evaluation on a single row. Args: row: Dictionary containing question and expected_answer rag: Pre-initialized RAG instance llm: Pre-initialized LLM client for evaluation Returns: Dictionary with evaluation results questionrow[question]# Query the RAG systemrag_responseawaitrag.query(question,top_k4)model_responserag_response.get(answer,)# Evaluate correctness asynchronouslyscoreawaitcorrectness_metric.ascore(questionquestion,expected_answerrow[expected_answer],responsemodel_response,llmllm)# Return evaluation resultsresult{**row,model_response:model_response,correctness_score:score.value,correctness_reason:score.reason,mlflow_trace_id:rag_response.get(mlflow_trace_id,N/A),# MLflow trace ID for debugging (explained later)retrieved_documents:[doc.get(content,)[:200]...iflen(doc.get(content,))200elsedoc.get(content,)fordocinrag_response.get(retrieved_documents,[])]}returnresult既然我们的数据集、指标和实验函数都已准备就绪我们现在可以评估我们的 RAG 系统性能了。运行初始 RAG 实验启动 MLflow 服务器在运行评估之前您必须启动 MLflow 服务器。RAG 系统会自动将跟踪信息记录到 MLflow 中以便进行调试和分析# Start MLflow server (required - in a separate terminal)uv run mlflow ui--backend-store-uri sqlite:///mlflow.db--port5000MLflow UI 将在 http://127.0.0.1:5000 可用。运行初始 RAG 实验现在让我们运行完整的评估管道以获取我们 RAG 系统的基线性能指标# Import required componentsimportasynciofromdatetimeimportdatetimefromragas_examples.improve_rag.evalsimport(evaluate_rag,download_and_save_dataset,create_ragas_dataset,get_openai_client,get_llm_client)fromragas_examples.improve_rag.ragimportRAG,BM25Retrieverasyncdefrun_evaluation():# Download and prepare datasetdataset_pathdownload_and_save_dataset()datasetcreate_ragas_dataset(dataset_path)# Initialize RAG componentsopenai_clientget_openai_client()retrieverBM25Retriever()ragRAG(llm_clientopenai_client,retrieverretriever,modelgpt-5-mini,modenaive)llmget_llm_client()# Run evaluation experimentexp_namef{datetime.now().strftime(%Y%m%d-%H%M%S)}_naiveragresultsawaitevaluate_rag.arun(dataset,nameexp_name,ragrag,llmllm)# Print resultsifresults:pass_countsum(1forresultinresultsifresult.get(correctness_score)pass)total_countlen(results)pass_rate(pass_count/total_count)*100iftotal_count0else0print(fResults:{pass_count}/{total_count}passed ({pass_rate:.1f}%))returnresults# Run the evaluationresultsawaitrun_evaluation()print(results)此步骤会下载数据集、初始化 BM25 检索器、对每个样本运行评估实验并将详细结果保存为 CSV 文件到 experiments/ 目录中以便后续分析。输出Results:43/66passed(65.2%)Evaluation completed successfully! Detailed results:Experiment(name20250924-212541_naiverag,len66)在 65.2% 的通过率下我们现在拥有了一个基线。 experiments/ 目录中的详细结果 CSV 文件包含了我们进行错误分析和系统性改进所需的所有数据。在 MLflow 中查看追踪实验结果 CSV 包含每个评估的 mlflow_trace_id 和 mlflow_trace_url 您可以通过它们分析详细的执行追踪。追踪信息帮助您精确定位失败发生的位置——无论是在检索、生成还是评估步骤中。RAG 系统会自动将追踪记录到之前启动的 MLflow 服务器中您可以在 http://127.0.0.1:5000 查看。这让您能够在 CSV 中分析结果查看响应、指标分数和原因通过追踪深入分析点击结果中的 mlflow_trace_url 直接跳转到 MLflow UI 中该评估的详细执行追踪小贴士点击追踪 URL 进行调试每个评估结果都包含 mlflow_trace_url ——一个指向 MLflow UI 中追踪记录的直接可点击链接。无需手动导航或复制追踪 ID只需点击即可直接跳转到详细执行追踪分析错误和失败模式运行评估后检查 experiments/ 目录中的结果 CSV 文件以识别失败案例中的模式。每行包含 mlflow_trace_id / mlflow_trace_url ——可用于在 MLflow UI 中查看详细执行追踪。对每个失败案例进行标注以便理解模式并改进应用程序。评估中的实际失败模式分析在我们的示例中核心问题是检索失败——BM25 检索器未能找到包含答案的文档。模型正确地遵循指令在文档不包含信息时如实说明但检索到了错误的文档。文档检索失败示例 BM25 检索器未能检索到包含答案的相关文档问题预期答案模型响应根本原因“create_repo 的默认仓库类型是什么”model“提供的文档未说明默认仓库类型…”BM25 遗漏了包含 create_repo 详情的文档“BLIP-Diffusion 模型的用途是什么”“可控文本到图像的生成与编辑”“提供的文档未提及 BLIP‑Diffusion…”BM25 未检索到 BLIP-Diffusion相关文档 “Hugging Face 用于托管 scikit-learn 模型的新库名称是什么”Skops“提供的文档未提及或命名任何新的 Hugging Face 库…”BM25 遗漏了 Skops 文档基于此分析我们可以看到检索是主要瓶颈。让我们实施针对性改进。改进 RAG 应用既然检索已被确定为主要瓶颈我们可以通过两种方式改进系统传统方法侧重于更好的分块、混合搜索或向量嵌入。然而由于我们的 BM25 检索在单次查询中始终遗漏相关文档我们将改为探索智能体agentic方法。智能体 RAGAgentic RAG让 AI 能够迭代优化其搜索策略——尝试多个搜索词并自行判断何时已找到足够的上下文而不是依赖单一的静态查询。智能体 RAG 实现运行 Agentic RAG 应用以执行示例查询# Switch to agentic moderag_agenticRAG(openai_client,retriever,modeagentic)questionWhat architecture is the tokenizers-linux-x64-musl binary designed for?resultawaitrag_agentic.query(question)print(fAnswer:{result[answer]})输出Answer:It targets x86_64 — i.e.the x86_64-unknown-linux-musl target triple.理解 Agentic RAG 的实现Agentic RAG 模式使用 OpenAI Agents SDK 创建一个配备 BM25 检索工具的 AI 智能体# Key components from the RAG class when modeagenticfromagentsimportAgent,Runner,function_tooldef_setup_agent(self):Setup agent for agentic mode.function_tooldefretrieve(query:str)-str:Search documents using BM25 retriever for a given query.docsself.retriever.retrieve(query,self.default_k)ifnotdocs:returnNo documents found.return\n\n.join([fDoc{i}:{doc.page_content}fori,docinenumerate(docs,1)])self._agentAgent(nameRAG Assistant,modelself.model,instructionsUse short keywords to search. Try 2-3 different searches. Only answer based on documents. Be concise.,tools[retrieve])asyncdef_agentic_query(self,question:str,top_k:int)-Dict[str,Any]:Handle agentic mode: agent controls retrieval strategy.resultawaitRunner.run(self._agent,inputquestion)print(result.answer)与朴素模式naive mode的单次检索调用不同智能体自主决定何时以及如何搜索——尝试多种关键词组合直到找到足够的上下文。重新运行实验并比较结果现在让我们评估 agentic RAG 方法# Import required componentsimportasynciofromdatetimeimportdatetimefromdotenvimportload_dotenv# Load environment variablesload_dotenv()fromragas_examples.improve_rag.evalsimport(evaluate_rag,download_and_save_dataset,create_ragas_dataset,get_openai_client,get_llm_client)fromragas_examples.improve_rag.ragimportRAG,BM25Retrieverasyncdefrun_agentic_evaluation():# Download and prepare datasetdataset_pathdownload_and_save_dataset()datasetcreate_ragas_dataset(dataset_path)# Initialize RAG components with agentic modeopenai_clientget_openai_client()retrieverBM25Retriever()ragRAG(llm_clientopenai_client,retrieverretriever,modelgpt-5-mini,modeagentic)llmget_llm_client()# Run evaluation experimentexp_namef{datetime.now().strftime(%Y%m%d-%H%M%S)}_agenticragresultsawaitevaluate_rag.arun(dataset,nameexp_name,ragrag,llmllm)# Print resultsifresults:pass_countsum(1forresultinresultsifresult.get(correctness_score)pass)total_countlen(results)pass_rate(pass_count/total_count)*100iftotal_count0else0print(fResults:{pass_count}/{total_count}passed ({pass_rate:.1f}%))returnresults# Run the agentic evaluationresultsawaitrun_agentic_evaluation()print(\nDetailed results:)print(results)Agentic RAG 评估输出Results:58/66passed(87.9%)太棒了我们取得了显著改进正确率从 65.2%朴素模式提升至 87.9%智能体模式——agentic RAG 方法带来了 22.7 个百分点的提升性能对比Agentic RAG 方法相较于朴素 RAG 基线有显著改进方法正确率改进幅度朴素 RAG65.2%-Agentic RAG87.9%22.7%将此循环应用于您的 RAG 系统遵循这一系统化方法来改进任何 RAG 系统创建评估数据集 使用系统中的真实查询或利用 LLM 生成合成数据。定义指标 选择与您的用例对齐的简单指标保持聚焦。运行基线评估 测量当前性能分析错误模式以识别系统性故障。实施针对性改进 基于错误分析改进检索分块、混合搜索、生成提示词、模型或尝试智能体方法。比较并迭代 测试改进方案相对于基线的效果。每次只改变一件事直到准确率达到业务要求。Ragas 框架自动处理编排和结果聚合让您可以专注于分析和改进而不是构建评估基础设施。