跳到主要内容

RAG 与 MLflow 和 LangChain 入门

下载此笔记本

教程概述

欢迎参加本教程,我们将探索检索增强生成 (RAG) 与 MLflow 和 LangChain 的集成。我们的重点是演示如何创建高级 RAG 系统,并展示 MLflow 在这些应用中实现的独特功能。

理解 RAG 以及如何使用 MLflow 进行开发

检索增强生成 (RAG) 将语言模型生成能力与信息检索相结合,使语言模型能够访问和整合外部数据。这种方法通过详细的、特定于上下文的信息极大地丰富了模型的响应。

MLflow 在此过程中发挥了重要作用。作为一个开源平台,它能够促进包括 RAG 链在内的复杂模型的日志记录、跟踪和部署。有了 MLflow,集成 LangChain 变得更加 streamlined,从而增强了 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 这样的库变化迅速,示例会很快过时,并且不再起作用。出于演示目的,以下是有效运行此笔记本推荐的关键依赖项

软件包版本
langchain0.1.16
lanchain-community0.0.33
langchain-openai0.0.8
openai1.12.0
tiktoken0.6.0
mlflow2.12.1
faiss-cpu1.7.4

如果您尝试使用不同的版本执行此 Notebook,它可能可以正常运行,但建议使用上述精确版本,以确保您的代码正确执行。

安装要求

在继续本教程之前,请确保您已通过 pip 安装了 FAISS 和 Beautiful Soup。其他软件包的版本说明符保证可以与此笔记本一起使用。这些软件包的其他版本可能由于其 API 的重大更改而无法正常工作。

bash
    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

python
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."

注意:如果您想在 LangChain 中使用 Azure OpenAI,您需要安装 openai>=1.10.0langchain-openai>=0.0.6,并指定以下凭证和参数

python
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 模型交互的完整端到端工作流程。

python
def fetch_federal_document(url, div_class):
"""
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
if transcript_section := soup.find("div", class_=div_class):
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 数据库创建

在接下来的部分中,我们将重点关注两个关键过程

  1. 文档抓取:

    • 我们使用 fetch_and_save_documents 从指定 URL 检索文档。
    • 此函数接受 URL 列表和文件路径作为输入。
    • 从 URL 抓取的每个文档都将被追加到给定路径的单个文件中。
  2. FAISS 数据库创建:

    • create_faiss_database 负责从上一步保存的文档创建 FAISS 数据库。
    • 该函数利用 TextLoader 加载文本,利用 CharacterTextSplitter 进行文档拆分,并利用 OpenAIEmbeddings 生成嵌入。
    • 生成的 FAISS 数据库(方便高效的相似性搜索)将被保存到指定目录并返回供进一步使用。

这些函数简化了收集相关文档和设置 FAISS 数据库的过程,这对于在 MLflow 中实现高级检索增强生成 (RAG) 应用至关重要。通过模块化这些步骤,我们确保了代码的可重用性和可维护性。

python
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 数据库

  1. 临时目录创建:

    • 使用 tempfile.mkdtemp() 创建一个临时目录。此目录用作存储文档和 FAISS 数据库的工作区。
  2. 文档路径和 FAISS 索引目录:

    • 在此临时目录中定义用于存储抓取的文档和 FAISS 数据库的路径。
  3. 文档抓取:

    • 我们有一个 URL 列表 (url_listings),其中包含我们需要抓取的文档。
    • fetch_and_save_documents 函数用于从这些 URL 检索文档并将其保存到位于 doc_path 的单个文件中。
  4. FAISS 数据库创建:

    • 然后调用 create_faiss_database 函数,使用默认的 chunk_sizechunk_overlap 值,根据保存的文档创建 FAISS 数据库。
    • 此数据库 (vector_db) 对于 RAG 过程至关重要,因为它能够对加载的文档进行高效的相似性搜索。

通过这个过程,我们将所有文档整合到一个位置,并准备好 FAISS 数据库,以便在我们的 MLflow 驱动的 RAG 应用中用于检索。

python
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 集成

  1. 初始化 RetrievalQA 链:

    • 使用 OpenAI 语言模型 (llm) 和来自我们先前创建的 FAISS 数据库的检索器 (vector_db.as_retriever()) 初始化 RetrievalQA 链。
    • 此链将使用 OpenAI 模型生成响应,并使用 FAISS 检索器进行基于文档的信息检索。
  2. 用于检索的加载器函数:

    • 定义了一个 load_retriever 函数,用于从指定目录中保存的 FAISS 数据库加载检索器。
    • 此函数对于模型以后使用时重新加载检索器至关重要。
  3. 使用 MLflow 记录模型:

    • 使用 mlflow.langchain.log_model 记录 RetrievalQA 链。
    • 此过程包括指定 artifact_path、检索器的 loader_fn 和存储 FAISS 数据库的 persist_dir
    • 使用 MLflow 记录模型可确保其被跟踪,并且可以轻松检索以供将来使用。

通过这些步骤,我们成功地将一个复杂的 RAG 应用与 MLflow 集成,展示了其处理高级 NLP 任务的能力。

python
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,
)

**重要提示**:为了加载上面存储的向量存储实例(如我们的 FAISS 实例),我们需要在加载函数中指定参数 allow_dangeous_deserializationTrue,以便加载成功。这是因为 langchain 在加载使用 picklecloudpickle 序列化的对象时引入了安全警告。虽然远程代码执行问题使用 MLflow 不存在风险,因为序列化和反序列化完全通过 API 并在您的环境中进行,但在加载时为了防止出现异常,必须设置此参数。

我们在 MLflow UI 中的 RAG 应用

Our Model in the UI

测试我们的 RAG 模型

现在模型已存储在 MLflow 中,我们可以将其加载为 pyfunc,看看它如何很好地回答关于这些美国国会法案的几个至关重要的问题。

python
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)
python
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)

让我们确保这个东西能正常工作

让我们通过发送一个相当简单但故意含糊不清的问题来试用我们的检索器模型。

python
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 模型在处理涉及特定信息检索和附加上下文生成查询方面的有趣功能。

查询和响应细分:

  • 查询:用户询问,“什么是马道,我可以在黄石公园使用马道吗?”
  • 响应:模型通过解释什么是马道并确认根据法案可以在黄石公园使用马道来回应。

理解响应动态:

  1. 结合文档数据和 LLM 上下文:

    • 关于马道的查询并未直接在建立黄石公园的法案中回答。
    • 模型使用其语言理解能力来提供马道的定义。
    • 然后,它将此信息与从 FAISS 数据库中检索到的关于该法案的上下文合并,特别是关于公园内道路和马道的修建。
  2. 增强的上下文理解:

    • RetrievalQA 模型展示了通过其语言模型补充数据库直接信息的附加上下文的能力。
    • 这种方法提供了一个更全面的答案,与用户的查询相符,显示了文档特定数据和一般知识的结合。
  3. 为什么这值得注意:

    • 与标准的 LLM 响应不同,RetrievalQA 模型不完全依赖其训练数据来生成通用响应。
    • 它有效地将特定的文档信息与更广泛的上下文理解相结合,提供了一个更细致的答案。

关键要点:

  • 这个例子突出了 MLflow 和 LangChain 如何通过 RetrievalQA 模型实现复杂的响应机制。该模型不仅检索相关的文档信息,还通过其语言理解能力智能地填补空白。
  • 这种响应机制在处理需要特定文档引用和附加上下文信息查询时特别有用,展示了 RAG 在实际应用中的高级功能。
python
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.

一个非常严肃的问题

在本教程的这一部分,我们将深入探讨一个异想天开的荒谬查询,以及我们的模型如何以准确性和一丝幽默感来处理它。

查询概述:

  • 查询:“我能从联邦政府购买黄石公园来开设一个以野牛为主题的水疗中心吗?”
  • 响应:模型一本正经地回答:“不,您不能从联邦政府购买黄石公园来开设一个以野牛为主题的水疗中心。”

一窥模型的思维过程:

  1. 直接且不含糊的响应:

    • 尽管查询带有喜剧色彩,但模型给出了直接而明确的回答。就像模型在说:“试得不错,但不行,你不能这样做。”
    • 这凸显了模型即使面对一个明显更幽默而非严肃的问题,也能保持事实的能力。
  2. 理解法律界限:

    • 该响应尊重国家公园的法律和监管神圣性。看来我们的模型非常重视保护黄石公园等国家宝藏!
    • 模型在法律和一般知识方面的训练有助于提供准确的响应,尽管这个问题是虚构的。
  3. 与传统 LLM 响应的对比:

    • 传统的 LLM 可能会给出更通用的答案。相比之下,我们的模型配备了特定于上下文的数据,迅速驳斥了购买国家公园用于水疗中心的异想天开的想法。

学习中的一丝幽默:

  • 这个查询虽然荒谬,但却是一个有趣的例子,说明了模型即使面对最离谱的问题也能提供与上下文相关的答案。
  • 这提醒我们,学习既可以信息丰富,又可以娱乐。在这种情况下,模型扮演着一本正经的喜剧演员的角色,以坚定而滑稽的“不”来回应一个极其富有想象力的商业提议。

所以,虽然您不能为了您的野牛主题水疗中心梦想而购买黄石公园,但您绝对可以享受公园的自然美景……仅作为游客,而不是水疗中心老板!

python
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.

保持镇定:回答另一个异想天开的查询

在本教程的这一部分,我们将探讨另一个关于在黄石公园租赁土地以开设以野牛为主题的水疗中心的有趣问题。让我们看看我们的模型如何以不可动摇的镇定态度来回应这个古怪的询问。

查询和响应:

  • 查询:“我能从联邦政府租赁一小块土地为公园游客开设一个小型野牛主题水疗中心吗?”
  • 响应:“不,您不能从联邦政府租赁一小块土地为公园游客开设一个小型野牛主题水疗中心……”

对模型响应的见解:

  1. 事实且坚定不移:

    • 尽管连续不断地提出不着边际的问题,我们的模型仍然像黄瓜一样冷静。它耐心解释了在黄石公园租赁土地的限制和实际目的。
    • 该响应引用了法案的第 2 条,为其反驳增加了法律精确性。
  2. 律师的耐心受到考验?:

    • 想象一下,如果这个问题是问一个真正的律师。到那时,他们可能已经揉太阳穴了!但我们的模型毫不动摇,继续提供事实答案。
    • 这展示了模型在不失去“冷静”的情况下处理重复和不寻常查询的能力。

总之,虽然我们的模型坚决关闭了野牛主题水疗中心梦想的大门,但它以信息丰富的优雅方式这样做,展示了其在面对多么富有想象力的查询时也能保持正轨的能力。

python
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 应用是否能够区分我们加载的两个法案故意含糊的措辞的细微差别。让我们看看响应,以确定它是否可以解决这两个信息点!

快速要点:

  • 模型坚持其信息丰富的本质,根据法案的规定澄清了租赁方面的问题。
  • 它有趣地将查询与另一项关于贸易和商业的法案联系起来,显示了其交叉引用相关法律文件的能力。
  • 此响应展示了模型即使在面对古怪和假设场景时,也能提供详细、相关信息的能力。
python
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.

那么,我能做什么呢?

要点:

  • 响应令人欣慰地确认,只要遵守公园规则和规定,人们就可以享受黄石公园的自然美景。
  • 这说明了模型能够针对简单、现实世界的问题提供直接、实用的建议。它显然拥有原始法案的上下文,并且能够推断出什么是允许的(享受保留地)。
python
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 模型在整合和解释来自多个法律文档的上下文方面的复杂能力。模型面临一个需要综合来自不同来源信息的查询。这项测试特别有趣,因为它展示了模型在以下方面的熟练程度:

  1. 上下文集成:模型熟练地从不同文档中提取相关的法律细节,展示了其导航多个信息源的能力。

  2. 法律解释:它解释与查询相关的法律含义,突显了模型对复杂法律语言和概念的理解。

  3. 跨文档推理:模型从多个文档池中辨别和提取最相关信息的能力,证明了其在多文档场景下的高级功能。

这次评估清楚地展示了模型在处理需要深入、细致地理解不同数据源的复杂查询方面的潜力。

python
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 清理了之前创建的临时目录。
python
# Clean up our temporary directory that we created with our FAISS instance
shutil.rmtree(temporary_directory)

结论:掌握 MLflow 的 RAG

在本教程中,我们深入探讨了由 MLflow 实现和简化的检索增强生成 (RAG) 应用。以下是我们旅程的回顾和关键要点

  1. RAG 应用开发的便捷性:我们学习了 MLflow 如何通过简化将大型语言模型与外部数据源集成的过程来促进 RAG 应用的开发。我们的实践经验展示了在 MLflow 框架内管理文档的抓取、处理和嵌入到 FAISS 数据库的过程。

  2. 高级查询处理:通过我们的测试,我们观察到 MLflow 包装的 LangChain RAG 模型如何巧妙地处理复杂查询,从多个文档中提取信息,提供丰富且准确的响应。这展示了 RAG 模型在处理和理解需要多源数据集成查询方面的潜力。

  3. MLflow 在部署和管理中的作用:MLflow 的稳健性体现在它如何简化复杂模型的日志记录、部署和管理。其跟踪实验、管理工件以及简化部署过程的能力,突显了它在机器学习生命周期中不可或缺的作用。

  4. 实际应用见解:我们的查询虽然有时很幽默,但却说明了 RAG 模型在实践中的能力。从法律解释到假设场景,我们看到了这些模型如何应用于现实世界的情况,提供有见地且与上下文相关的响应。

  5. RAG 和 MLflow 的未来:本教程强调了将 RAG 与 MLflow 的简化管理功能相结合的潜力。随着 RAG 的不断发展,MLflow 作为利用其强大功能的重要工具脱颖而出,使高级 NLP 应用更加易于访问和高效。

总而言之,我们通过本教程的旅程不仅使我们具备了有效开发和部署 RAG 应用的知识,还让我们看到了高级 NLP 领域广阔的可能性,而 MLflow 使这一切更加触手可及。

下一步是什么?

如果您想了解有关 MLflow 和 LangChain 如何集成的更多信息,请参阅 MLflow LangChain flavor 的其他 高级教程