使用 MLflow 和 LangChain 实现 RAG 入门
教程概述
欢迎来到本教程,我们将探讨检索增强生成 (RAG) 与 MLflow 和 LangChain 的集成。 我们的重点是演示如何创建高级 RAG 系统,并展示 MLflow 在这些应用中实现的独特功能。
了解 RAG 以及如何使用 MLflow 开发 RAG
检索增强生成 (RAG) 结合了语言模型生成和信息检索的能力,使语言模型能够访问和整合外部数据。 这种方法通过详细的、特定于上下文的信息,显著丰富了模型的响应。
MLflow 在此过程中发挥了重要作用。 作为一个开源平台,它促进了复杂模型的日志记录、跟踪和部署,包括 RAG 链。 借助 MLflow,集成 LangChain 变得更加精简,从而增强了 RAG 模型的开发、评估和部署过程。
注意:在本教程中,我们将使用 GPT-3.5 作为我们的基础语言模型。 重要的是要注意,从 RAG 系统获得的结果将不同于直接与 GPT 模型交互获得的结果。 RAG 将外部数据检索与语言模型生成相结合的独特方法,可以创建更细致且上下文丰富的响应。
学习成果
在本教程结束时,您将学习
- 如何使用 LangChain 和 MLflow 建立 RAG 链。
- 用于抓取和处理文档以馈送到 RAG 系统的技术。
- 部署和使用 RAG 模型来回答复杂查询的最佳实践。
- 了解与直接语言模型交互相比,使用 RAG 时响应的实际影响和差异。
设置我们的检索器依赖项
为了有一个地方来存储我们经过审查的数据(我们将要检索的信息),我们将使用向量数据库。 我们选择使用的框架(由于其简单性、功能和免费使用特性)是来自 Meta 的 FAISS。
本教程的 FAISS 安装
了解 FAISS
在本教程中,我们将使用 FAISS(Facebook AI 相似性搜索,由 Meta AI 研究组开发和维护),这是一个高效的相似性搜索和聚类库。 这是一个非常有用的库,可以轻松处理大型数据集,并且能够执行诸如最近邻搜索之类的操作,这些操作在检索增强生成 (RAG) 系统中至关重要。 还有许多其他向量数据库解决方案可以执行类似的功能; 在本教程中,我们使用 FAISS 是因为它简单、易用且性能出色。
Notebook 兼容性
对于诸如 langchain
之类的快速变化的库,示例可能很快就会过时并且无法再工作。 为了演示的目的,以下是建议使用的关键依赖项,以有效地运行此笔记本
软件包 | 版本 |
---|---|
langchain | 0.1.16 |
lanchain-community | 0.0.33 |
langchain-openai | 0.0.8 |
openai | 1.12.0 |
tiktoken | 0.6.0 |
mlflow | 2.12.1 |
faiss-cpu | 1.7.4 |
如果您尝试使用不同的版本执行此 Notebook,它可能可以正常运行,但建议使用上述精确版本,以确保您的代码正确执行。
安装要求
在继续本教程之前,请确保您已通过 pip
安装了 FAISS 和 Beautiful Soup。 其他软件包的版本说明符保证与此笔记本配合使用。 由于其 API 中的重大更改,这些软件包的其他版本可能无法正常工作。
pip install beautifulsoup4 faiss-cpu==1.7.4 langchain==0.1.16 langchain-community==0.0.33 langchain-openai==0.0.8 openai==1.12.0 tiktoken==0.6.0
注意:如果您想使用 GPU 运行它,您可以安装
faiss-gpu
。
import os
import shutil
import tempfile
import requests
from bs4 import BeautifulSoup
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import FAISS
from langchain_openai import OpenAI, OpenAIEmbeddings
import mlflow
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
注意:如果您想将 Azure OpenAI 与 LangChain 一起使用,您需要安装
openai>=1.10.0
和langchain-openai>=0.0.6
,以及指定以下凭据和参数
from langchain_openai import AzureOpenAI, AzureOpenAIEmbeddings
# Set this to `azure`
os.environ["OPENAI_API_TYPE"] = "azure"
# The API version you want to use: set this to `2023-05-15` for the released version.
os.environ["OPENAI_API_VERSION"] = "2023-05-15"
assert "AZURE_OPENAI_ENDPOINT" in os.environ, (
"Please set the AZURE_OPENAI_ENDPOINT environment variable. It is the base URL for your Azure OpenAI resource. You can find this in the Azure portal under your Azure OpenAI resource."
)
assert "OPENAI_API_KEY" in os.environ, (
"Please set the OPENAI_API_KEY environment variable. It is the API key for your Azure OpenAI resource. You can find this in the Azure portal under your Azure OpenAI resource."
)
azure_openai_llm = AzureOpenAI(
deployment_name="<your-deployment-name>",
model_name="gpt-4o-mini",
)
azure_openai_embeddings = AzureOpenAIEmbeddings(
azure_deployment="<your-deployment-name>",
)
抓取用于 RAG 处理的联邦文档
在本教程的这一部分中,我们将演示如何从联邦文档网页中抓取内容以用于我们的 RAG 系统。 我们将专注于从网页的特定部分提取成绩单,然后将其用于输入我们的检索增强生成 (RAG) 模型。 此过程对于为 RAG 系统提供相关的外部数据至关重要。
函数概述
- 函数
fetch_federal_document
旨在抓取并返回特定联邦文档的成绩单。 - 它接受两个参数:
url
(网页 URL)和div_class
(包含成绩单的 div 元素的类)。 - 该函数处理 Web 请求、解析 HTML 内容并提取所需的成绩单文本。
此步骤是构建依赖于外部、特定于上下文的数据的 RAG 系统的组成部分。 通过有效地获取和处理此数据,我们可以使用直接来自权威文档的准确信息来丰富模型的响应。
注意:在实际场景中,您的特定文本数据将位于某个磁盘上(无论是本地还是在您的云提供商处),并且将嵌入数据加载到向量搜索数据库的过程将完全独立于下面显示的此活动获取。 我们只是在这里展示整个过程以进行演示,以展示与 RAG 模型交互的整个端到端工作流程。
def fetch_federal_document(url, div_class): # noqa: D417
"""
Scrapes the transcript of the Act Establishing Yellowstone National Park from the given URL.
Args:
url (str): URL of the webpage to scrape.
Returns:
str: The transcript text of the Act.
"""
# Sending a request to the URL
response = requests.get(url)
if response.status_code == 200:
# Parsing the HTML content of the page
soup = BeautifulSoup(response.text, "html.parser")
# Finding the transcript section by its HTML structure
transcript_section = soup.find("div", class_=div_class)
if transcript_section:
transcript_text = transcript_section.get_text(separator="
", strip=True)
return transcript_text
else:
return "Transcript section not found."
else:
return f"Failed to retrieve the webpage. Status code: {response.status_code}"
文档获取和 FAISS 数据库创建
在接下来的部分中,我们将重点关注两个关键过程
-
文档获取:
- 我们使用
fetch_and_save_documents
从指定的 URL 检索文档。 - 此函数采用 URL 列表和文件路径作为输入。
- 从 URL 获取的每个文档都会附加到给定路径的单个文件中。
- 我们使用
-
FAISS 数据库创建:
create_faiss_database
负责从上一步中保存的文档创建 FAISS 数据库。- 该函数利用
TextLoader
加载文本,利用CharacterTextSplitter
进行文档拆分,并利用OpenAIEmbeddings
生成嵌入。 - 生成的 FAISS 数据库有助于高效的相似性搜索,并保存到指定的目录中并返回以供进一步使用。
这些函数简化了收集相关文档和设置 FAISS 数据库的过程,这对于在 MLflow 中实现高级检索增强生成 (RAG) 应用程序至关重要。 通过模块化这些步骤,我们可以确保代码的可重用性和可维护性。
def fetch_and_save_documents(url_list, doc_path):
"""
Fetches documents from given URLs and saves them to a specified file path.
Args:
url_list (list): List of URLs to fetch documents from.
doc_path (str): Path to the file where documents will be saved.
"""
for url in url_list:
document = fetch_federal_document(url, "col-sm-9")
with open(doc_path, "a") as file:
file.write(document)
def create_faiss_database(document_path, database_save_directory, chunk_size=500, chunk_overlap=10):
"""
Creates and saves a FAISS database using documents from the specified file.
Args:
document_path (str): Path to the file containing documents.
database_save_directory (str): Directory where the FAISS database will be saved.
chunk_size (int, optional): Size of each document chunk. Default is 500.
chunk_overlap (int, optional): Overlap between consecutive chunks. Default is 10.
Returns:
FAISS database instance.
"""
# Load documents from the specified file
document_loader = TextLoader(document_path)
raw_documents = document_loader.load()
# Split documents into smaller chunks with specified size and overlap
document_splitter = CharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
document_chunks = document_splitter.split_documents(raw_documents)
# Generate embeddings for each document chunk
embedding_generator = OpenAIEmbeddings()
faiss_database = FAISS.from_documents(document_chunks, embedding_generator)
# Save the FAISS database to the specified directory
faiss_database.save_local(database_save_directory)
return faiss_database
设置工作环境和 FAISS 数据库
本教程的这一部分涉及我们检索增强生成 (RAG) 应用程序的设置。 我们将建立工作环境并创建必要的 FAISS 数据库
-
临时目录创建:
- 使用
tempfile.mkdtemp()
创建临时目录。 此目录用作存储我们的文档和 FAISS 数据库的工作区。
- 使用
-
文档路径和 FAISS 索引目录:
- 用于存储获取的文档和 FAISS 数据库的路径在此临时目录中定义。
-
文档获取:
- 我们有一个 URL 列表 (
url_listings
),其中包含我们需要获取的文档。 fetch_and_save_documents
函数用于从这些 URL 检索文档并将其保存到位于doc_path
的单个文件中。
- 我们有一个 URL 列表 (
-
FAISS 数据库创建:
- 然后调用
create_faiss_database
函数以从已保存的文档创建 FAISS 数据库,使用默认的chunk_size
和chunk_overlap
值。 - 此数据库 (
vector_db
) 对于 RAG 过程至关重要,因为它支持对加载的文档进行高效的相似性搜索。
- 然后调用
在此过程结束时,我们将所有文档合并到一个位置,并且 FAISS 数据库已准备好在我们的 MLflow 支持的 RAG 应用程序中用于检索目的。
temporary_directory = tempfile.mkdtemp()
doc_path = os.path.join(temporary_directory, "docs.txt")
persist_dir = os.path.join(temporary_directory, "faiss_index")
url_listings = [
"https://www.archives.gov/milestone-documents/act-establishing-yellowstone-national-park#transcript",
"https://www.archives.gov/milestone-documents/sherman-anti-trust-act#transcript",
]
fetch_and_save_documents(url_listings, doc_path)
vector_db = create_faiss_database(doc_path, persist_dir)
建立 RetrievalQA 链并使用 MLflow 进行日志记录
在此最终设置阶段,我们将重点关注创建 RetrievalQA 链并将其与 MLflow 集成
-
初始化 RetrievalQA 链:
- 使用 OpenAI 语言模型 (
llm
) 和来自我们先前创建的 FAISS 数据库的检索器 (vector_db.as_retriever()
) 初始化RetrievalQA
链。 - 此链将使用 OpenAI 模型生成响应,并使用 FAISS 检索器进行基于文档的信息检索。
- 使用 OpenAI 语言模型 (
-
检索的加载器函数:
- 定义了一个
load_retriever
函数,用于从保存在指定目录中的 FAISS 数据库加载检索器。 - 此函数对于稍后使用该模型时重新加载检索器至关重要。
- 定义了一个
-
使用 MLflow 记录模型:
- 使用
mlflow.langchain.log_model
记录 RetrievalQA 链。 - 此过程包括指定
artifact_path
、检索器的loader_fn
和存储 FAISS 数据库的persist_dir
。 - 使用 MLflow 记录模型可确保对其进行跟踪,并可以轻松检索以供将来使用。
- 使用
通过这些步骤,我们成功地将复杂的 RAG 应用程序与 MLflow 集成,展示了其处理高级 NLP 任务的能力。
mlflow.set_experiment("Legal RAG")
retrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=vector_db.as_retriever())
# Log the retrievalQA chain
def load_retriever(persist_directory):
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.load_local(
persist_directory,
embeddings,
allow_dangerous_deserialization=True, # This is required to load the index from MLflow
)
return vectorstore.as_retriever()
with mlflow.start_run() as run:
model_info = mlflow.langchain.log_model(
retrievalQA,
name="retrieval_qa",
loader_fn=load_retriever,
persist_dir=persist_dir,
)
重要:为了加载存储的 vectorstore 实例(例如上面的 FAISS 实例),我们需要在加载函数中指定参数
allow_dangeous_deserialization
为True
,以便加载成功。 这是因为langchain
中引入了一个安全警告,用于加载使用pickle
或cloudpickle
序列化的对象。 虽然使用 MLflow 不存在远程代码执行的问题,因为序列化和反序列化完全通过 API 发生并在您的环境中发生,但必须设置参数以防止在加载时引发异常。
我们在 MLflow UI 中的 RAG 应用程序
测试我们的 RAG 模型
现在我们已将模型存储在 MLflow 中,我们可以将其作为 pyfunc
重新加载,并查看它如何回答关于美国国会的这些法案的一些至关重要的问题。
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)
def print_formatted_response(response_list, max_line_length=80):
"""
Formats and prints responses with a maximum line length for better readability.
Args:
response_list (list): A list of strings representing responses.
max_line_length (int): Maximum number of characters in a line. Defaults to 80.
"""
for response in response_list:
words = response.split()
line = ""
for word in words:
if len(line) + len(word) + 1 <= max_line_length:
line += word + " "
else:
print(line)
line = word + " "
print(line)
让我们确保这东西有效
让我们通过向其发送一个相当简单但有目的地含糊的问题来试用我们的检索器模型。
answer1 = loaded_model.predict([{"query": "What does the document say about trespassers?"}])
print_formatted_response(answer1)
The document states that all persons who shall locate or settle upon or occupy the land reserved for the public park, except as provided, shall be considered trespassers and removed from the park.
了解 RetrievalQA 响应
使用此模型,我们的方法结合了从数据库检索文本和语言模型生成,以回答特定查询。
其工作方式:
- RetrievalQA 模型:此模型是 LangChain 套件的一部分,旨在首先从预定义的数据库中检索相关信息,然后使用语言模型根据此信息生成响应。
- 数据库集成:在此示例中,我们从历史文档(例如《建立黄石国家公园法案》)创建了一个 FAISS 数据库。 此数据库由 RetrievalQA 模型用于查找文本的相关部分。
- 查询处理:当我们执行
loaded_model.predict([{"query": "该文档对非法入侵者有何规定?"}])
时,该模型首先在数据库中搜索与关于非法入侵者的查询最相关的文档部分。
为什么此响应不同?
- 特定于上下文的答案:与直接查询 GPT-3.5(可能基于其训练数据生成答案而没有特定上下文)不同,RetrievalQA 模型提供直接从数据库中的特定文档派生的响应。
- 准确且相关:响应更准确且在上下文中更相关,因为它基于被查询的特定文档的实际内容。
- 没有泛化:响应中的泛化或假设较少。 RetrievalQA 模型不是基于其训练“猜测”; 而是提供直接来自文档的信息。
主要结论:
- 此方法演示了 MLflow 和 LangChain 如何促进复杂的 RAG 用例,在这种用例中,与历史文本或特定文本的直接交互比通用语言模型预测产生更精确的答案。
- 该教程重点介绍了在需要将响应基于特定文本或文档的场景中,利用 RAG 尤其有用,展示了检索和生成功能的强大融合。
分析 Bridle-Path 查询响应
本教程的这一部分展示了 RetrievalQA 模型的有趣方面,尤其是在处理涉及特定信息检索和其他上下文生成的查询时。
查询和响应分解:
- 查询:用户问:“什么是 Bridle-Path,我可以在黄石公园使用它吗?”
- 响应:该模型通过解释什么是 Bridle-Path,并根据该法案确认可以在黄石公园使用 Bridle-Path 来响应。
了解响应动态:
-
将文档数据与 LLM 上下文相结合:
- 关于 Bridle-Path 的查询没有在建立黄石公园的法案中直接回答。
- 该模型使用其语言理解能力来提供 Bridle-Path 的定义。
- 然后,它将此信息与它从 FAISS 数据库中检索到的关于该法案的上下文合并,特别是关于在公园中修建道路和 Bridle-Path 的信息。
-
增强的上下文理解:
- RetrievalQA 模型展示了通过其语言模型补充来自数据库的直接信息的能力。
- 这种方法提供了一个更全面的答案,该答案与用户的查询保持一致,显示了特定于文档的数据和一般知识的融合。
-
为什么这值得注意:
- 与标准 LLM 响应不同,RetrievalQA 模型不完全依赖于其训练数据进行一般响应。
- 它有效地将特定的文档信息与更广泛的上下文理解相结合,从而提供了更细致的答案。
主要结论:
- 此示例重点介绍了 MLflow 和 LangChain 如何通过 RetrievalQA 模型促进复杂的响应机制。 该模型不仅检索相关的文档信息,而且还智能地使用其自己的语言理解能力来填补空白。
- 当处理需要特定文档参考和其他上下文信息的查询时,这种响应机制尤其有用,展示了 RAG 在实际应用中的高级功能。
answer2 = loaded_model.predict(
[{"query": "What is a bridle-path and can I use one at Yellowstone?"}]
)
print_formatted_response(answer2)
A bridle-path is a narrow path or trail designed for horseback riding. Yes, you can use a bridle-path at Yellowstone as it is designated for the enjoyment and benefit of the people visiting the park. However, it may be subject to certain regulations and restrictions set by the Secretary of the Interior.
最严肃的问题
在本教程的这一部分中,我们将深入探讨一个异想天开的荒谬查询,以及我们的模型如何以准确性和一丝幽默来处理它。
查询概述:
- 查询:“我可以从联邦政府购买黄石公园来建立一个以水牛为主题的日间水疗中心吗?”
- 响应:该模型面无表情地响应说:“不,您不能从联邦政府购买黄石公园来建立一个以水牛为主题的日间水疗中心。”
对模型思维过程的窥视:
-
直接且毫不含糊的响应:
- 尽管查询带有喜剧色彩,但该模型给出了直接而明确的响应。 就像该模型在说,“不错的尝试,但是,不,您不能这样做。”
- 这突出了模型在面对显然比严肃更幽默的问题时,保持事实的能力。
-
了解法律界限:
- 该响应尊重国家公园的法律和监管神圣性。 看来我们的模型非常重视像黄石公园这样的国家珍宝的保护!
- 该模型在法律和一般知识方面的训练有助于提供准确的响应,尽管该问题是一个开玩笑的问题。
-
与传统 LLM 响应的对比:
- 传统的 LLM 可能会给出更通用的答案。 相比之下,我们的模型配备了特定于上下文的数据,立即驳斥了购买国家公园用于水疗的异想天开的想法。
学习中的一丝幽默:
- 该查询虽然荒谬,但可以作为模型提供与上下文相关的答案(即使是最牵强的问题)的能力的一个有趣的例子。
- 它提醒人们,学习既可以提供信息又可以娱乐。 在这种情况下,该模型扮演着面无表情的喜剧演员的角色,以坚定而滑稽的“不”回应了一个极富想象力的商业计划。
因此,虽然您不能购买黄石公园来实现您以水牛为主题的水疗梦想,但您当然可以欣赏公园的自然美景……只是作为游客,而不是作为水疗中心老板!
answer3 = loaded_model.predict(
[
{
"query": "Can I buy Yellowstone from the Federal Government to set up a buffalo-themed day spa?"
}
]
)
print_formatted_response(answer3)
No, you cannot buy Yellowstone from the Federal Government to set up a buffalo-themed day spa. The land near the headwaters of the Yellowstone River has been reserved and withdrawn from settlement, occupancy, or sale under the laws of the United States and dedicated and set apart as a public park for the benefit and enjoyment of the people. The Secretary of the Interior has control over the park and is responsible for making and publishing rules and regulations for its management. Leases for building purposes are only granted for small parcels of ground for the accommodation of visitors, and the proceeds are used for the management of the park and the construction of roads and bridle-paths. Additionally, the wanton destruction of fish and game within the park is prohibited. Furthermore, the Act to protect trade and commerce against unlawful restraints and monopolies (approved July 2, 1890) states that any contract, combination, or conspiracy in restraint of trade or commerce in any Territory or the District of Columbia is illegal. Thus, buying land to set up a buffalo-themed day spa would likely be considered a violation of this act.
保持镇定:回答另一个异想天开的查询
在本教程的这一部分中,我们将探讨另一个关于在黄石公园租赁土地以建立一个以水牛为主题的日间水疗中心的有趣问题。 让我们看看我们的模型如何以沉着冷静的态度回应这个古怪的询问。
查询和响应:
- 查询:“我可以从联邦政府租赁一小块土地,用于为公园游客建立一个小型的以水牛为主题的日间水疗中心吗?”
- 响应:“不,您不能从联邦政府租赁一小块土地,用于为公园游客建立一个小型的以水牛为主题的日间水疗中心……”
对模型响应的见解:
-
事实且坚定不移:
- 尽管持续提出古怪的问题,但我们的模型仍然像黄瓜一样冷静。 它耐心地解释了租赁黄石公园土地的限制和实际用途。
- 该响应引用了该法案的第 2 节,为反驳增添了法律上的精确性。
-
律师的耐心是否受到了考验?:
- 想象一下,如果将这个问题提给真正的律师。 到目前为止,他们可能正在揉搓他们的太阳穴! 但是我们的模型并没有受到干扰,并且继续提供事实性的答案。
- 这展示了模型处理重复和不寻常查询而不会失去“冷静”的能力。
总而言之,虽然我们的模型坚决关上了以水牛为主题的日间水疗梦想的大门,但它以信息丰富的优雅方式做到了这一点,展示了它在查询变得多么富有想象力的情况下保持在航线上的能力。
answer4 = loaded_model.predict(
[
{
"query": "Can I lease a small parcel of land from the Federal Government for a small "
"buffalo-themed day spa for visitors to the park?"
}
]
)
print_formatted_response(answer4)
No, according to the context provided, the Secretary of the Interior may grant leases for building purposes for terms not exceeding ten years, but only for the accommodation of visitors. It does not specifically mention a buffalo-themed day spa as a possible use for the leased land.
再次尝试以水牛为主题的日间水疗梦想
再一次,我们向我们的模型提出了一个富有想象力的问题,这次是在以水牛为主题的日间水疗情景中增加了一家酒店。 进行此修改的原因是评估 RAG 应用程序是否可以识别我们加载的两项法案的有意模糊措辞的细微元素。 让我们看看响应,以确定它是否可以解决这两条信息!
快速要点:
- 该模型秉承其信息性的本质,根据该法案的规定阐明了租赁方面的内容。
- 有趣的是,它将查询连接到另一项与贸易和商业相关的法案,表明了其交叉引用相关法律文件的能力。
- 此响应展示了模型提供详细、相关信息的能力,即使在面对古怪和假设性情景时也是如此。
answer5 = loaded_model.predict(
[
{
"query": "Can I lease a small parcel of land from the Federal Government for a small "
"buffalo-themed day spa and hotel for visitors to stay in and relax at while visiting the park?"
}
]
)
print_formatted_response(answer5)
No, it is not possible to lease land from the Federal Government for a commercial purpose within the designated park area. The Secretary of the Interior may grant leases for building purposes for terms not exceeding ten years, but only for small parcels of ground for the accommodation of visitors. Additionally, all proceeds from leases and other revenues must be used for the management of the park and the construction of roads and bridle-paths.
那么,我可以做什么呢?
要点:
- 该响应令人安心地确认,人们可以欣赏黄石公园的自然美景,前提是尊重公园的规章制度。
- 这说明了该模型在响应简单、真实世界问题时提供直接、实用建议的能力。 它清楚地了解原始法案的背景,并且能够推断出什么是允许的(欣赏保留地)。
answer6 = loaded_model.predict(
[{"query": "Can I just go to the park and peacefully enjoy the natural splendor?"}]
)
print_formatted_response(answer6)
Yes, according to the context, the park was set apart as a public park or pleasuring-ground for the benefit and enjoyment of the people. However, the park is under the exclusive control of the Secretary of the Interior who has the authority to make and publish rules and regulations for the care and management of the park. Therefore, it is important to follow any rules or regulations set by the Secretary to ensure the preservation and protection of the park for future enjoyment.
评估 RetrievalQA 模型对法律背景的集成
本教程的这一部分展示了 RetrievalQA 模型综合和解释来自多个法律文件的背景信息的高级能力。 该模型面临着一个需要从不同来源综合信息的查询。 此测试因其演示了模型的熟练程度而特别有趣
-
背景信息集成:该模型熟练地从不同的文件中提取相关的法律细节,说明了其在多个信息来源中导航的能力。
-
法律解释:它解释了与查询相关的法律含义,突出了模型对复杂法律语言和概念的理解。
-
跨文档推理:该模型从多个文档池中识别和提取最相关信息的能力证明了其在多文档情景中的高级功能。
此评估提供了模型在处理需要对不同数据来源进行深入和细致理解的复杂查询方面的潜力的清晰示例。
answer7 = loaded_model.predict(
[
{
"query": "Can I start a buffalo themed day spa outside of Yellowstone National Park and stifle any competition?"
}
]
)
print_formatted_response(answer7)
No, according to the context, any attempt to monopolize trade or commerce in the Yellowstone area or in any territory of the United States is considered illegal. Additionally, the park is under the exclusive control of the Secretary of the Interior, who may grant leases for building purposes but is expected to prevent the destruction of natural resources and the exploitation of fish and game for profit. Therefore, it would not be possible to start a buffalo themed day spa outside of Yellowstone National Park and stifle competition without violating the law and risking consequences from the Secretary of the Interior.
清理:删除临时目录:
- 在我们完成向我们的检索器模型提出一堆愚蠢问题后,使用
shutil.rmtree
清理先前创建的临时目录。
# Clean up our temporary directory that we created with our FAISS instance
shutil.rmtree(temporary_directory)
结论:使用 MLflow 掌握 RAG
在本教程中,我们探讨了检索增强生成 (RAG) 应用程序的深度,这些应用程序由 MLflow 启用和简化。 以下是我们旅程的回顾和主要要点
-
开发 RAG 应用程序的便捷性:我们学习了 MLflow 如何通过简化将大型语言模型与外部数据来源集成的过程来促进 RAG 应用程序的开发。 我们的实践经验展示了获取、处理和将文档嵌入到 FAISS 数据库中的过程,所有这些都在 MLflow 框架内进行管理。
-
高级查询处理:通过我们的测试,我们观察到 MLflow 包装的 LangChain RAG 模型如何巧妙地处理复杂查询,从多个文档中提取信息以提供上下文丰富且准确的响应。 这展示了 RAG 模型在处理和理解需要多源数据集成的查询方面的潜力。
-
MLflow 在部署和管理中的作用:MLflow 的强大功能体现在它如何简化复杂模型的日志记录、部署和管理。 它跟踪实验、管理工件和简化部署过程的能力突出了其在机器学习生命周期中的不可或缺性。
-
实际应用见解:我们的查询虽然有时很幽默,但有助于说明 RAG 模型的实际功能。 从法律解释到假设情景,我们看到了这些模型如何在现实世界的情景中应用,提供有见地且在上下文中相关的响应。
-
RAG 和 MLflow 的未来:本教程强调了将 RAG 与 MLflow 的流线型管理能力相结合的潜力。随着 RAG 的不断发展,MLflow 成为利用其强大功能的关键工具,使高级 NLP 应用程序更易于访问和高效。
总之,我们通过本教程的学习,不仅掌握了有效开发和部署 RAG 应用程序的知识,而且让我们看到了高级 NLP 领域中未来的巨大可能性,而 MLflow 使这一切更容易实现。
下一步是什么?
如果您想了解更多关于 MLflow 和 LangChain 如何集成的信息,请参阅其他 MLflow 的 LangChain 口味的高级教程。