Docs 菜单
Docs 主页
/
MongoDB 阿特拉斯
/

使用 Atlas Vector Search 进行检索增强生成 (RAG)

在此页面上

  • 为何使用 RAG?
  • 附带 Atlas Vector Search 的 RAG
  • 摄取
  • 检索
  • 一代
  • 开始体验
  • 先决条件
  • 步骤
  • 后续步骤
  • 微调

检索增强生成 (RAG) 是一种架构,用于使用额外数据增强大型语言模型 (LLM),以便生成更准确的响应。您可以将 法学硕士 与由 Atlas Vector Search 提供支持的检索系统相结合,在生成式 AI 应用程序中实施 RAG 。

开始体验

使用法学硕士时,您可能会遇到以下限制:

  • 过时数据: LLM在特定时间点之前的静态数据集上进行训练。这意味着他们的知识库有限,可能会使用过时的数据。

  • 无权访问本地数据:法学硕士无权访问本地或个性化数据。因此,他们可能缺乏特定领域的知识。

  • 幻觉:当训练数据不完整或已过期时,法学硕士可能会生成不准确的信息。

您可以通过以下步骤实施RAG来解决这些限制:

  1. 摄取:将自定义数据作为向量嵌入存储在向量数据库(例如 MongoDB Atlas)中。这样,您就可以创建最新的个性化数据知识库。

  2. 检索:使用搜索解决方案(例如 Atlas Vector Search)根据用户的问题从数据库中检索语义相似的文档。这些文档通过额外的相关数据丰富了法学硕士课程

  3. 生成:提示LLM法学硕士使用检索到的文档作为上下文,生成更准确、更相关的响应,从而减少幻觉。

由于RAG支持问答和文本生成等任务,因此它是构建 AI 聊天机器人的有效架构,可提供个性化、特定领域的响应。要创建可投入生产的聊天机器人,您必须配置服务器来路由请求,并在RAG实施的基础上构建用户界面。

要使用 Atlas Vector Search 实施RAG ,您需要将数据提取到 Atlas 中,使用 Atlas Vector Search 检索文档,并使用LLM生成响应。本节介绍使用 Atlas Vector Search 进行基本或原生RAG实施的组件。有关分步说明,请参阅入门。

带有 Atlas Vector Search 的 RAG 流程图
点击放大

RAG的数据摄取涉及处理自定义数据并将其存储在向量数据库中以准备检索。要使用 Atlas 作为向量数据库创建基本摄取管道,请执行以下操作:

  1. 加载数据。您可以使用 文档加载 器 等工具 或 数据连接器 从不同数据格式和位置加载数据。

  2. 处理(Process)或分块( Chunk )您的数据。分块是将数据分割成更小的部分以提高性能。

  3. 使用 嵌入模型 将数据转换为 向量嵌入 。要了解更多信息,请参阅 如何创建向量嵌入。

  4. 将这些嵌入存储在 Atlas 中。您可以将嵌入作为一个字段与其他数据一起存储在集合中。

构建检索系统涉及从向量数据库中搜索并返回最相关的文档,以增强法学硕士学位。要使用 Atlas Vector Search 检索相关文档,您可以将用户的问题转换为向量嵌入,并对 Atlas 中的数据运行向量搜索查询,以查找嵌入最相似的文档。

要使用 Atlas Vector Search 执行基本检索,请执行以下操作:

  1. 在包含向量嵌入的集合上定义Atlas Vector Search 索引

  2. 根据用户的问题选择以下方法之一来检索文档:

要生成回复,请将您的检索系统与LLM相结合。执行向量搜索以检索相关文档后,您将用户的问题以及相关文档作为上下文提供给LLM ,以便它可以生成更准确的响应。

选择以下方法之一连接到LLM

  • Atlas Vector Search 与常用框架或服务集成。这些集成包括内置库和工具,可帮助您以最少的设置连接到LLM

  • 调用法学硕士API 。大多数 AI 提供商都为其生成模型提供API ,可用于生成响应。

  • 加载开源LLM 。如果您没有API密钥或信用额度,您可以通过从应用程序本地加载开源LLM来使用。

以下示例演示了使用 MongoDB LangChain 集成 Huugging Face 进行 Atlas Vector Search 的基本 RAG 实施 以轻松加载和访问嵌入和生成模型。

要完成此示例,您必须具备以下条件:

1

通过保存扩展名为 .ipynb的文件来创建交互式 Python 笔记本,然后在笔记本中运行以下代码以安装依赖项:

pip install --quiet pymongo langchain langchain_community langchain_mongodb langchain_huggingface pypdf sentence_transformers
2

在本部分中,您将把法学硕士无权访问的样本数据导入到 Atlas 中。以下代码使用LangChain 集成PyMongo 驱动程序执行以下操作:

  • 加载包含MongoDB 最新收益报告的 PDF。

  • 将数据拆分为数据段,并指定数据段大小(字符数)和数据段重叠(连续数据段之间的重叠字符数)。

  • 加载 nomic-embed-text-v1 嵌入来自 Huugging Face 模型中心的模型。

  • 从数据创建向量嵌入,并将这些嵌入存储在 Atlas 集群的rag_db.test集合中。

在笔记本中粘贴并运行以下代码,将<connection-string>替换为您的 Atlas连接字符串:

from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_mongodb import MongoDBAtlasVectorSearch
from pymongo import MongoClient
# Load the PDF
loader = PyPDFLoader("https://investors.mongodb.com/node/12236/pdf")
data = loader.load()
# Split the data into chunks
text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=20)
docs = text_splitter.split_documents(data)
# Load the embedding model (https://huggingface.co/nomic-ai/nomic-embed-text-v1")
model = HuggingFaceEmbeddings(model_name="nomic-ai/nomic-embed-text-v1", model_kwargs={ "trust_remote_code": True })
# Connect to your Atlas cluster
client = MongoClient("<connection-string>")
collection = client["rag_db"]["test"]
# Store the data as vector embeddings in Atlas
vector_store = MongoDBAtlasVectorSearch.from_documents(
documents = docs,
embedding = model,
collection = collection,
index_name = "vector_index"
)

提示

运行代码后,您可以导航到集群中的rag_db.test集合,在 Atlas 用户界面中查看向量嵌入。

3

在本部分中,您将设置 Atlas Vector Search 以从向量数据库中检索文档。完成以下步骤:

  1. 在向量嵌入上创建 Atlas Vector Search 索引。

    对于免费和共享集群,请按照步骤通过 Atlas 用户界面创建索引。将索引命名为vector_index并使用以下索引定义:

    {
    "fields": [
    {
    "type": "vector",
    "path": "embedding",
    "numDimensions": 768,
    "similarity": "euclidean"
    }
    ]
    }

    对于专用集群,您可以使用 PyMongo 驱动程序直接从应用程序创建索引。在笔记本中粘贴并运行以下代码:

    pymongo.operations import SearchIndexModel
    # Create your index model, then create the search index
    search_index_model = SearchIndexModel(
    definition = {
    "fields": [
    {
    "type": "vector",
    "numDimensions": 768,
    "path": "embedding",
    "similarity": "cosine"
    }
    ]
    },
    name = "vector_index",
    type = "vectorSearch"
    )
    collection.create_search_index(model=search_index_model)
  2. 将 Atlas Vector Search 配置为检索器。

    在您的笔记本中,运行以下代码以设置检索系统,并使用LangChain 集成运行示例语义搜索查询:

    # Instantiate Atlas Vector Search as a retriever
    retriever = vector_store.as_retriever(
    search_type = "similarity"
    )
    # Run a sample query in order of relevance
    retriever.invoke("AI technology")
    [Document(metadata={'_id': '66a910ba7f78f7ec6760ceba', 'source': 'https://investors.mongodb.com/node/12236/pdf', 'page': 0}, page_content="more of our customers. We also see a tremendous opportunity to win more legacy workloads, as AI has now become a catalyst to modernize these\napplications. MongoDB's document-based architecture is particularly well-suited for the variety and scale of data required by AI-powered applications."),
    Document(metadata={'_id': '66a910ba7f78f7ec6760ced6', 'source': 'https://investors.mongodb.com/node/12236/pdf', 'page': 1}, page_content='artificial intelligence, in our offerings or partnerships; the growth and expansion of the market for database products and our ability to penetrate that\nmarket; our ability to integrate acquired businesses and technologies successfully or achieve the expected benefits of such acquisitions; our ability to'),
    Document(metadata={'_id': '66a910ba7f78f7ec6760cec3', 'source': 'https://investors.mongodb.com/node/12236/pdf', 'page': 0}, page_content='MongoDB continues to expand its AI ecosystem with the announcement of the MongoDB AI Applications Program (MAAP),'),
    Document(metadata={'_id': '66a910ba7f78f7ec6760cec4', 'source': 'https://investors.mongodb.com/node/12236/pdf', 'page': 1}, page_content='which provides customers with reference architectures, pre-built partner integrations, and professional services to help\nthem quickly build AI-powered applications. Accenture will establish a center of excellence focused on MongoDB projects,\nand is the first global systems integrator to join MAAP.')]
4

在本部分中,您将通过提示 LLM 使用检索到的文档作为上下文来 生成 响应。以下代码使用 LangChain 执行以下操作:

  • 访问 Mistral7 B 指令 来自 Huging Face 模型中心的模型。

  • 使用 提示模板 指示 法学硕士 在提示中包含用户的问题和检索到的文档 和 链。

  • 法学硕士提示 MongoDB 的最新 AI 公告。

在笔记本中粘贴并运行以下代码,将<token>替换为您的 Huging Face 访问令牌。生成的响应可能会有所不同。

from langchain_huggingface import HuggingFaceEndpoint
from langchain.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
import os
# Authenticate to your Hugging Face account
os.environ["HF_TOKEN"] = "<token>"
# Access the LLM (https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2)
llm = HuggingFaceEndpoint(repo_id="mistralai/Mistral-7B-Instruct-v0.2")
# Create prompt and RAG workflow
prompt = PromptTemplate.from_template("""
Answer the following question based on the given context.
Question: {question}
Context: {context}
""")
rag_chain = (
{ "context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
# Prompt the LLM
question = "In a few sentences, what are MongoDB's latest AI announcements?"
answer = rag_chain.invoke(question)
print(answer)
Answer: MongoDB recently announced the MongoDB AI Applications Program
(MAAP) as part of their efforts to expand their AI ecosystem.
The document-based architecture of MongoDB is particularly well-suited
for AI-powered applications, offering an opportunity to win more legacy
workloads. These announcements were made at MongoDB.local NYC.

有关更详细的RAG教程,请使用以下资源:

要开始使用 Atlas Vector Search 构建可立即投入生产的聊天机器人,您可以使用 MongoDB 聊天机器人框架 。此框架提供了一组库,使您能够快速构建 AI 聊天机器人应用程序。

要优化和微调RAG应用程序,您可以尝试不同的嵌入模型、分块策略和LLM 。要了解详情,请参阅以下资源:

此外,Atlas Vector Search 支持高级检索系统。由于您可以在 Atlas 中将矢量数据与其他数据一起无缝索引,因此您可以对集合中的其他字段进行预过滤或执行混合搜索以将语义搜索与全文搜索结果相结合来微调检索结果。

后退

创建和运行查询

来年

查看部署选项