跳到主要内容

MLflow RAG 与 LangChain 简介

下载此笔记本

教程概述

欢迎阅读本教程,我们将探讨检索增强生成 (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 等库的快速变化,示例可能会很快过时并停止工作。为了演示目的,以下是建议用于有效运行此笔记本的关键依赖项

软件包版本
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 的重大更改,这些包的其他版本可能无法正常运行。

    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.0langchain-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):
"""
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 数据库创建

在下一部分中,我们重点关注两个关键过程

  1. 文档获取:

    • 我们使用 fetch_and_save_documents 从指定的 URL 检索文档。
    • 此函数将 URL 列表和文件路径作为输入。
    • 从 URL 获取的每个文档都附加到给定路径上的单个文件。
  2. 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 数据库

  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 应用程序中用于检索目的。

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 任务的能力。

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,看看它在回答有关美国国会法案的几个关键问题方面的表现如何。

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 如何特别有用,展示了检索和生成能力的强大结合。

分析马道查询响应

本教程的这一部分展示了 RetrievalQA 模型功能的一个有趣方面,特别是在处理涉及特定信息检索和额外上下文生成这两种情况的查询时。

查询和响应分解:

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

理解响应动态:

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

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

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

    • 与标准 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.

一个非常严肃的问题

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

查询概述:

  • 查询:“我能从联邦政府那里购买黄石国家公园来建立一个以水牛为主题的日间水疗中心吗?”
  • 响应:模型面无表情地回答:“不,你不能从联邦政府那里购买黄石国家公园来建立一个以水牛为主题的日间水疗中心。”

模型思考过程一瞥:

  1. 直接而毫不含糊的回答:

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

    • 该响应尊重国家公园的法律和法规神圣性。看来我们的模型对黄石国家公园等国家宝藏的保护非常重视!
    • 模型在法律和通用知识方面的训练有助于提供准确的响应,尽管问题是玩笑性质的。
  3. 与传统 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.

保持沉着:回答另一个异想天开的查询

在本教程的这一部分,我们将探讨另一个关于在黄石公园租赁土地以建造水牛主题日间水疗中心的有趣问题。让我们看看我们的模型如何以沉着的态度回应这个古怪的询问。

查询与响应:

  • 查询:“我能否向联邦政府租赁一小块土地,用于在公园内为游客建造一个小型水牛主题日间水疗中心?”
  • 响应:“不,你不能向联邦政府租赁一小块土地,用于在公园内为游客建造一个小型水牛主题日间水疗中心……”

模型响应的洞察:

  1. 事实且坚定:

    • 尽管持续出现离奇的提问,我们的模型依然冷静自若。它耐心地解释了在黄石国家公园租赁土地的限制和实际用途。
    • 响应引用了该法案的第 2 节,为其驳斥增添了法律精确性。
  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 模型集成和解释来自多个法律文档的上下文的复杂能力。该模型面临一个需要综合来自不同来源信息的查询。此测试特别有趣,因为它展示了模型在以下方面的熟练程度:

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

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

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

此评估为模型处理需要对不同数据源有深入细致理解的复杂查询的潜力提供了清晰的示例。

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 启用和简化。以下是我们的旅程和主要收获的回顾:

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

  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 风格的其他高级教程