LangChain 集成
本教程演示如何用 Ragas 评测基于 LangChain 构建的 RAG 问答应用。此外,我们还会探索 Ragas App 如何帮助分析和提升应用表现。
构建一个简单的问答应用
要构建问答系统,我们先创建一个小数据集,并用其 embeddings 在向量数据库中建立索引。
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 的系统,把 retriever、LLM 和 prompt 集成到 Retrieval QA Chain 中。retriever 从知识库中获取相关文档。LLM 会基于检索到的文档生成回答,Prompt 则引导模型的响应,帮助它理解上下文并生成相关、连贯的语言输出。
在 LangChain 中,可以通过向量存储的 .as_retriever 方法创建 retriever。更多细节见 LangChain 关于 vector store retrievers 的文档。
retriever = vector_store.as_retriever(search_kwargs={"k": 1})
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
我们将定义一个 Chain,处理用户查询和检索到的相关数据,并在结构化 prompt 中传给模型。模型输出随后被解析,生成最终的字符串响应。
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})
Output:
'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.",
]
要评测问答系统,需要把 queries、expected_responses 以及其他指标特定要求整理成 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)
我们将使用以下指标评测问答应用。
LLMContextRecall:评测检索到的上下文与参考答案中的主张对齐得如何,无需人工标注参考上下文即可估计召回。Faithfulness:评估生成答案中的所有主张是否都能直接从所给上下文推断出来。Factual Correctness:通过与参考答案比较,使用基于主张的评测和自然语言推理,检查生成响应的事实准确性。
关于这些指标的更多细节以及它们如何用于评测 RAG 系统,请访问 Ragas Metrics Documentation。
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
Output
{'context_recall': 1.0000, 'faithfulness': 0.9000, 'factual_correctness': 0.9260}