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 Similarity Search,由 Meta AI 研究小组开发和维护),这是一个高效的相似性搜索和聚类库。这是一个非常有用的库,可以轻松处理大型数据集,并能够执行最近邻搜索等操作,这在检索增强生成 (RAG) 系统中至关重要。还有许多其他向量数据库解决方案可以执行类似功能;我们在此教程中使用 FAISS 是因为其简单性、易用性和出色的性能。
Notebook 兼容性
随着像 langchain
这样快速变化的库,示例可能会很快过时并且不再起作用。为了演示目的,以下是建议使用的关键依赖项,以便有效地运行此 notebook
包 | 版本 |
---|---|
langchain | 0.1.16 |
langchain-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。其他包的版本指定符保证与此 notebook 一起工作。由于其 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 元素的类)。 - 该函数处理网络请求、解析 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
函数,使用默认的chunk_size
和chunk_overlap
值,从保存的文档中创建 FAISS 数据库。 - 此数据库 (
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,
artifact_path="retrieval_qa",
loader_fn=load_retriever,
persist_dir=persist_dir,
)
重要提示:为了加载存储的向量存储实例(例如上面我们的 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": "What does the document say about trespassers?"}])
时,模型首先在数据库中搜索与有关擅自闯入者查询最相关的文档部分。
为何此响应不同?
- 特定上下文响应:与直接查询 GPT-3.5(它可能基于其训练数据生成响应而无需特定上下文)不同,RetrievalQA 模型提供直接源自数据库中特定文档的响应。
- 准确且相关:响应更准确且上下文相关,因为它基于被查询的特定文档的实际内容。
- 无泛化:响应中没有过多的泛化或假设。RetrievalQA 模型不是基于其训练进行“猜测”;它直接提供源自文档的信息。
关键要点:
- 此方法论展示了 MLflow 和 LangChain 如何促进复杂的 RAG 用例,在这种用例中,与历史或特定文本的直接交互产生的答案比通用语言模型预测更精确。
- 本教程强调了在需要将响应基于特定文本或文档的场景中,利用 RAG 如何特别有用,展示了检索和生成功能的强大结合。
分析马道查询响应
本教程的这一部分展示了 RetrievalQA 模型能力的一个有趣方面,特别是在处理既涉及特定信息检索又涉及额外上下文生成的查询时。
查询和响应细分:
- 查询:用户询问:“什么是马道?我能在黄石公园使用马道吗?”
- 响应:模型解释了什么是马道,并根据法案确认可以在黄石公园使用马道。
理解响应动态:
-
将文档数据与大型语言模型上下文结合:
- 关于马道的查询在《建立黄石公园法案》中没有直接答案。
- 模型利用其语言理解能力提供马道的定义。
- 然后,它将此信息与从 FAISS 数据库中检索到的有关该法案(特别是关于公园内道路和马道建设)的上下文合并。
-
增强的上下文理解:
- RetrievalQA 模型展示了通过其语言模型用额外上下文补充来自数据库的直接信息的能力。
- 这种方法提供了一个更全面的答案,与用户的查询一致,展示了文档特定数据和通用知识的融合。
-
为何值得关注:
- 与标准的大型语言模型响应不同,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.
一个非常严肃的问题
在教程的这一部分,我们将深入探讨一个异想天开的荒谬查询,以及我们的模型如何以准确性和一丝幽默感来处理它。
查询概述:
- 查询:“我可以从联邦政府购买黄石公园来设立一个以野牛为主题的日间水疗中心吗?”
- 响应:模型面不改色地回答:“不,您不能从联邦政府购买黄石公园来设立一个以野牛为主题的日间水疗中心。”
窥探模型的思维过程:
-
直接且一丝不苟的响应:
- 尽管查询带有喜剧色彩,模型仍然给出了直接而明确的响应。就像模型在说:“想得美,但不行,你不能那样做。”
- 这突出显示了模型即使面对明显比严肃更幽默的问题时,也能保持事实准确的能力。
-
理解法律界限:
- 响应尊重了国家公园的法律和监管神圣性。看来我们的模型对待黄石公园这样的国家宝藏的保护相当认真!
- 模型在法律和通用知识方面的训练有助于提供准确的响应,尽管问题有些滑稽。
-
与传统大型语言模型响应对比:
- 传统的通用大型语言模型可能会给出更通用的答案。相比之下,我们的模型配备了特定上下文数据,迅速驳斥了购买国家公园用于水疗的异想天开的想法。
学习中的一丝幽默:
- 这个查询虽然荒谬,但作为一个有趣的例子,展示了模型即使面对最牵强的查询也能提供上下文相关答案的能力。
- 这提醒我们,学习既可以是信息性的,也可以是娱乐性的。在这种情况下,模型扮演着面无表情的喜剧演员的角色,以坚定而滑稽的“不行”来回应一个充满想象力的商业提案。
所以,虽然您不能购买黄石公园来实现您的野牛主题水疗梦想,但您当然可以享受公园的自然美景……只是作为一个游客,而不是水疗中心老板!
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 应用的开发。我们的实践经验展示了在 MLflow 框架内管理文档的获取、处理和嵌入到 FAISS 数据库的整个过程。
-
高级查询处理:通过我们的测试,我们观察到 MLflow 封装的 LangChain RAG 模型如何娴熟地处理复杂查询,从多个文档中提取信息以提供上下文丰富且准确的响应。这展示了 RAG 模型在处理和理解需要多源数据集成的查询方面的潜力。
-
MLflow 在部署和管理中的作用:MLflow 的强大之处体现在它如何简化复杂模型的日志记录、部署和管理。其追踪实验、管理工件和简化部署过程的能力,突显了它在机器学习生命周期中的不可或缺性。
-
实际应用见解:我们的查询虽然有时很幽默,但却很好地说明了 RAG 模型的实际能力。从法律解释到假设情景,我们看到了这些模型如何在现实世界中应用,提供富有洞察力且上下文相关的响应。
-
RAG 和 MLflow 的未来:本教程强调了将 RAG 与 MLflow 流线型管理能力相结合的潜力。随着 RAG 的不断发展,MLflow 作为释放其力量的关键工具脱颖而出,使得高级自然语言处理 (NLP) 应用更加易于访问和高效。
总之,通过本教程的学习,我们不仅掌握了有效开发和部署 RAG 应用的知识,还开阔了眼界,看到了高级自然语言处理 (NLP) 领域未来巨大的可能性,而这一切都通过 MLflow 变得更加易于实现。
下一步是什么?
如果您想了解更多关于 MLflow 和 LangChain 如何集成的信息,请参阅 MLflow LangChain Flavor 的其他高级教程。