用Ragas评估LangChain检索问答链
该教程演示如何用LangChain搭建基于向量检索的问答链,并用Ragas对检索问答应用进行评估,以分析并改进其表现。
## LangChain 整合 这个教程演示了如何评价一个基于RAG的QQA应用,使用RAgas使用LangChain构建. 此外,我们将探索RAgas App如何帮助分析和增强应用的性能. ### 建立简单的 QQA 应用程序 为了构建一个问答系统,我们首先创建一个小数据集,并使用它嵌入到矢量数据库中进行索引. ``` import os from dotenv import load_dotenv from langchain_core.documents import Document load_dotenv() content_list = [ "Andrew Ng is the CEO of Landing AI and is known for his pioneering work in deep learning. He is also widely recognized for democratizing AI education through platforms like Coursera.", "Sam Altman is the CEO of OpenAI and has played a key role in advancing AI research and development. He is a strong advocate for creating safe and beneficial AI technologies.", "Demis Hassabis is the CEO of DeepMind and is celebrated for his innovative approach to artificial intelligence. He gained prominence for developing systems that can master complex games like AlphaGo.", "Sundar Pichai is the CEO of Google and Alphabet Inc., and he is praised for leading innovation across Google's vast product ecosystem. His leadership has significantly enhanced user experiences on a global scale.", "Arvind Krishna is the CEO of IBM and is recognized for transforming the company towards cloud computing and AI solutions. He focuses on providing cutting-edge technologies to address modern business challenges.", ] langchain_documents = [] for content in content_list: langchain_documents.append( Document( page_content=content, ) ) ``` ``` from ragas.embeddings import OpenAIEmbeddings from langchain_core.vectorstores import InMemoryVectorStore import openai openai_client = openai.OpenAI() embeddings = OpenAIEmbeddings(client=openai_client, model="text-embedding-3-small") vector_store = InMemoryVectorStore(embeddings) _ = vector_store.add_documents(langchain_documents) ``` 我们现在将构建一个基于RAG的系统,将检索器LLM集成,并提示到检索器QA链中。检索器会从知识库中获取相关文档。LLM将在检索到的文档中生成响应,使用“提示”来引导模型的反应,帮助模型理解上下文,并生成相关且一致的语言输出。 在 LangChain 中,我们可以使用它来从矢量商店创建检索器. `.as_retriever` 方法。详细情况请参见 [关于矢量存储检索器的 LangChain 文档](<https://python.langchain.com/docs/how_to/vectorstore_retriever/>). ``` retriever = vector_store.as_retriever(search_kwargs={"k": 1}) ``` ``` from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o-mini") ``` 我们将定义一个处理用户查询和检索相关数据的链条, 在结构化的提示中将其传递给模型。 然后对模型的输出进行解析, 以生成一个字符串的最终响应 。 ``` from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser template = """Answer the question based only on the following context: {context} Question: {query} """ prompt = ChatPromptTemplate.from_template(template) qa_chain = prompt | llm | StrOutputParser() ``` ``` def format_docs(relevant_docs): return "\n".join(doc.page_content for doc in relevant_docs) query = "Who is the CEO of OpenAI?" relevant_docs = retriever.invoke(query) qa_chain.invoke({"context": format_docs(relevant_docs), "query": query}) ``` 输出 : ``` 'The CEO of OpenAI is Sam Altman.' ``` ### 评价 ``` sample_queries = [ "Which CEO is widely recognized for democratizing AI education through platforms like Coursera?", "Who is Sam Altman?", "Who is Demis Hassabis and how did he gained prominence?", "Who is the CEO of Google and Alphabet Inc., praised for leading innovation across Google's product ecosystem?", "How did Arvind Krishna transformed IBM?", ] expected_responses = [ "Andrew Ng is the CEO of Landing AI and is widely recognized for democratizing AI education through platforms like Coursera.", "Sam Altman is the CEO of OpenAI and has played a key role in advancing AI research and development. He strongly advocates for creating safe and beneficial AI technologies.", "Demis Hassabis is the CEO of DeepMind and is celebrated for his innovative approach to artificial intelligence. He gained prominence for developing systems like AlphaGo that can master complex games.", "Sundar Pichai is the CEO of Google and Alphabet Inc., praised for leading innovation across Google's vast product ecosystem. His leadership has significantly enhanced user experiences globally.", "Arvind Krishna is the CEO of IBM and has transformed the company towards cloud computing and AI solutions. He focuses on delivering cutting-edge technologies to address modern business challenges.", ] ``` 为了评估QQA系统,我们需要对查询、expected_responses和其他具体指标要求进行结构分析。 [EvaluationDataset](<https://docs.ragas.io/en/stable/references/evaluation_schema/#ragas.dataset_schema.EvaluationDataset>). ``` from ragas import EvaluationDataset dataset = [] for query, reference in zip(sample_queries, expected_responses): relevant_docs = retriever.invoke(query) response = qa_chain.invoke({"context": format_docs(relevant_docs), "query": query}) dataset.append( { "user_input": query, "retrieved_contexts": [rdoc.page_content for rdoc in relevant_docs], "response": response, "reference": reference, } ) evaluation_dataset = EvaluationDataset.from_list(dataset) ``` 为了评估我们的“QQA”应用程序,我们将使用以下标准。 - `LLMContextRecall`:评价检索的背景如何与参考答复中的索赔相一致,在没有人工参考背景说明的情况下估计召回情况。 - `Faithfulness`: 评估生成的答案中的所有索赔是否可以直接从所提供的上下文推断出来. - `Factual Correctness`:通过使用基于索赔的评价和自然语言推论,将生成的回复与参考物进行比较,以检查生成回复的事实准确性. 关于这些衡量标准及其适用于评估RAG系统的详细情况,访问 [Ragas计量文档](<https://docs.ragas.io/en/stable/howtos/concepts/metrics/available_metrics/>). ``` from ragas import evaluate from ragas.llms import LangchainLLMWrapper from ragas.metrics import LLMContextRecall, Faithfulness, FactualCorrectness evaluator_llm = LangchainLLMWrapper(llm) result = evaluate( dataset=evaluation_dataset, metrics=[LLMContextRecall(), Faithfulness(), FactualCorrectness()], llm=evaluator_llm, ) result ``` 产出 ``` {'context_recall': 1.0000, 'faithfulness': 0.9000, 'factual_correctness': 0.9260} ``` 12月 16, 2025 12月 16, 2025
查看原始来源