使用 Atlas Vector Search 进行检索增强生成 (RAG)
检索增强生成 (RAG) 是一种架构,用于使用额外数据增强大型语言模型 (LLM),以便生成更准确的响应。您可以将 法学硕士 与由 Atlas Vector Search 提供支持的检索系统相结合,在生成式 AI 应用程序中实施 RAG 。
为何使用 RAG?
使用法学硕士时,您可能会遇到以下限制:
过时数据: LLM在特定时间点之前的静态数据集上进行训练。这意味着他们的知识库有限,可能会使用过时的数据。
无权访问本地数据:法学硕士无权访问本地或个性化数据。因此,他们可能缺乏特定领域的知识。
幻觉:当训练数据不完整或已过期时,法学硕士可能会生成不准确的信息。
您可以通过以下步骤实施RAG来解决这些限制:
摄取:将自定义数据作为向量嵌入存储在向量数据库(例如 MongoDB Atlas)中。这样,您就可以创建最新的个性化数据知识库。
检索:使用搜索解决方案(例如 Atlas Vector Search)根据用户的问题从数据库中检索语义相似的文档。这些文档通过额外的相关数据丰富了法学硕士课程。
生成:提示LLM 。法学硕士使用检索到的文档作为上下文,生成更准确、更相关的响应,从而减少幻觉。
由于RAG支持问答和文本生成等任务,因此它是构建 AI 聊天机器人的有效架构,可提供个性化、特定领域的响应。要创建可投入生产的聊天机器人,您必须配置服务器来路由请求,并在RAG实施的基础上构建用户界面。
附带 Atlas Vector Search 的 RAG
要使用 Atlas Vector Search 实施RAG ,您需要将数据提取到 Atlas 中,使用 Atlas Vector Search 检索文档,并使用LLM生成响应。本节介绍使用 Atlas Vector Search 进行基本或原生RAG实施的组件。有关分步说明,请参阅入门。
摄取
RAG的数据摄取涉及处理自定义数据并将其存储在向量数据库中以准备检索。要使用 Atlas 作为向量数据库创建基本摄取管道,请执行以下操作:
检索
构建检索系统涉及从向量数据库中搜索并返回最相关的文档,以增强法学硕士学位。要使用 Atlas Vector Search 检索相关文档,您可以将用户的问题转换为向量嵌入,并对 Atlas 中的数据运行向量搜索查询,以查找嵌入最相似的文档。
要使用 Atlas Vector Search 执行基本检索,请执行以下操作:
在包含向量嵌入的集合上定义Atlas Vector Search 索引。
根据用户的问题选择以下方法之一来检索文档:
将Atlas Vector Search 与常用框架或服务集成。这些集成包括内置库和工具,使您能够使用 Atlas Vector Search 轻松构建检索系统。
构建自己的检索系统。您可以定义自己的函数和管道来运行特定于您使用案例的Atlas Vector Search 查询。
一代
要生成回复,请将您的检索系统与LLM相结合。执行向量搜索以检索相关文档后,您将用户的问题以及相关文档作为上下文提供给LLM ,以便它可以生成更准确的响应。
选择以下方法之一连接到LLM :
将Atlas Vector Search 与常用框架或服务集成。这些集成包括内置库和工具,可帮助您以最少的设置连接到LLM 。
调用法学硕士的API 。大多数 AI 提供商都为其生成模型提供API ,可用于生成响应。
加载开源LLM 。如果您没有API密钥或信用额度,您可以通过从应用程序本地加载开源LLM来使用。
开始体验
以下示例演示了使用 MongoDB LangChain 集成 和 Huugging Face 进行 Atlas Vector Search 的基本 RAG 实施 以轻松加载和访问嵌入和生成模型。
先决条件
要完成此示例,您必须具备以下条件:
具有运行 MongoDB 6版本的集群的Atlas 帐户。 0 。 11或7 。 0 。 2及更高版本。要了解更多信息,请参阅创建集群。
拥抱面部访问令牌 具有读取访问权限。
运行交互式 Python 笔记本(例如 Colab)的环境。
步骤
将数据导入 Atlas。
在本部分中,您将把法学硕士无权访问的样本数据导入到 Atlas 中。以下代码使用LangChain 集成和PyMongo 驱动程序执行以下操作:
将数据拆分为数据段,并指定数据段大小(字符数)和数据段重叠(连续数据段之间的重叠字符数)。
加载 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 用户界面中查看向量嵌入。
使用 Atlas Vector Search 检索文档。
在本部分中,您将设置 Atlas Vector Search 以从向量数据库中检索文档。完成以下步骤:
在向量嵌入上创建 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) 将 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.')]
使用 LLM 生成回复。
在本部分中,您将通过提示 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教程,请使用以下资源:
要了解如何使用流行的 法学硕士 框架和 AI 服务实施 RAG ,请参阅 将向量搜索与 AI 技术集成。
要了解如何使用本地 Atlas 部署和本地模型来实施RAG ,请参阅使用 Atlas Vector Search 构建本地 RAG 实施。
有关基于用例的教程和交互式 Python 笔记本,请参阅 生成式 AI 用例存储库。
要开始使用 Atlas Vector Search 构建可立即投入生产的聊天机器人,您可以使用 MongoDB 聊天机器人框架 。此框架提供了一组库,使您能够快速构建 AI 聊天机器人应用程序。
微调
要优化和微调RAG应用程序,您可以尝试不同的嵌入模型、分块策略和LLM 。要了解详情,请参阅以下资源:
此外,Atlas Vector Search 支持高级检索系统。由于您可以在 Atlas 中将矢量数据与其他数据一起无缝索引,因此您可以对集合中的其他字段进行预过滤或执行混合搜索以将语义搜索与全文搜索结果相结合来微调检索结果。