使用 Atlas Vector Search 构建本地 RAG 实施
本教程演示如何在本地实施检索增强生成 (RAG),而无需 API密钥或信用。要了解有关RAG的更多信息,请参阅使用 Atlas Vector Search 进行检索增强生成 (RAG)。
具体来说,您需要执行以下操作:
创建本地 Atlas 部署。
设置环境。
使用局部嵌入模型生成向量嵌入。
在您的数据上创建一个 Atlas Vector Search 索引。
部署本地法学硕士来回答有关数据的问题。
背景
要完成本教程,您可以使用Atlas CLI创建本地 Atlas 部署,也可以在云上部署集群。 Atlas CLI 是 MongoDB Atlas 的命令行界面,您可以使用 Atlas CLI 从终端与 Atlas 交互,以执行各种任务,包括创建本地 Atlas 部署。要了解更多信息,请参阅从 Atlas CLI 管理本地和云部署。
注意
本地 Atlas 部署仅用于测试。对于生产环境,请部署集群。
您还可以在本教程中使用以下开源模型:
bge-large-en-v1 。5 嵌入模型
米斯特拉尔7 B 生成模型
可通过多种方法在本地下载和部署 LLM 。在本教程中,您将使用7 GPT4 All 下载 Mistral B 模型 ,一个用于本地 法学硕士 开发的开源生态系统。
本教程还使用 LangChain ,一种流行的开源 LLM 框架,用于连接到这些模型并将其与 Atlas Vector Search 集成。如果您更喜欢不同的模型或不同的框架,您可以调整本教程,将模型名称和特定于 LangChain 的组件替换为您首选设置的等效组件。
要了解有关如何在RAG应用程序中利用 LangChain 的更多信息,请参阅开始使用 LangChain 集成。要详细了解可与 Atlas Vector Search 一起使用的其他框架,请参阅将向量搜索与 AI 技术集成。
先决条件
如要完成本教程,您必须具备以下条件:
创建本地 Atlas 部署
在本部分中,您将创建一个本地 Atlas 部署以用作向量数据库。如果您有一个运行 MongoDB 6版本的 Atlas 集群。 0 。 11 、 7 。 0 。 2或更高版本(加载了样本数据)后,您可以跳过此步骤。
要创建本地部署,请执行以下操作:
从 Atlas CLI 连接。
在终端中,运行 atlas auth login
以使用您的 Atlas 登录档案进行身份验证。要了解更多信息,请参阅从 Atlas CLI 连接。
注意
如果您没有 Atlas 帐户,请运行atlas setup
或创建一个新帐户。
使用 Atlas CLI 创建本地部署。
运行atlas deployments setup
并按照提示创建本地部署。
有关详细说明,请参阅创建本地 Atlas 部署。
设置环境
在本部分中,您将为本教程设置环境。通过保存扩展名为.ipynb
的文件来创建交互式 Python 笔记本,然后在笔记本中运行以下代码片段。
定义 Atlas 连接字符串。
如果使用的是本地 Atlas 部署,请在笔记本中运行以下代码,将<port-number>
替换为本地部署的端口。
ATLAS_CONNECTION_STRING = ("mongodb://localhost:<port-number>/?directConnection=true")
如果您使用的是 Atlas 集群,请在 Notebook 中运行以下代码,并将<connection-string>
替换为 Atlas 集群的SRV连接字符串:
ATLAS_CONNECTION_STRING = ("<connection-string>")
注意
连接字符串应使用以下格式:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
使用本地模型生成嵌入
在本部分中,您将在本地加载嵌入模型,并使用sample_airbnb数据库中的数据创建向量嵌入,该数据库包含一个名为listingsAndReviews
的集合。以下代码片段执行以下操作:
建立与本地 Atlas 部署或 Atlas 集群和
sample_airbnb.listingsAndReviews
集合的连接。从 LangChain 的
HuggingFaceEmbeddings
库加载bge-large-en-v1.5
嵌入模型。创建筛选器以仅包含具有
summary
字段但没有embeddings
字段的文档。对于集合中满足筛选条件的每个文档:
使用
bge-large-en-v1.5
嵌入模型从文档的summary
字段生成嵌入。通过创建包含嵌入的名为
embeddings
的新字段来更新文档。
在笔记本中运行以下代码:
from langchain_huggingface import HuggingFaceEmbeddings from pymongo import MongoClient # Connect to your local Atlas deployment or Atlas Cluster client = MongoClient(ATLAS_CONNECTION_STRING) # Select the sample_airbnb.listingsAndReviews collection collection = client["sample_airbnb"]["listingsAndReviews"] # Specify local embedding model (https://huggingface.co/sentence-transformers/baai/bge-large-en-v1.5) model = HuggingFaceEmbeddings(model_name="baai/bge-large-en-v1.5") # Filters for only documents with a summary field and without an embeddings field filter = { '$and': [ { 'summary': { '$exists': True, '$ne': None } }, { 'embeddings': { '$exists': False } } ] } count = 0 totalCount = collection.count_documents(filter) # Creates embeddings and updates the documents in the collection for document in collection.find(filter): text = document['summary'] embedding = model.embed_query(text) collection.update_one({ '_id': document['_id'] }, { "$set": { 'embeddings': embedding } }, upsert = True) count+=1 print("Documents updated: {}/{} ".format(count, totalCount))
此代码需要一些时间才能运行。完成后,您可以在 Atlas 用户界面中查看向量嵌入,方法是导航到集群中的sample_airbnb.listingsAndReviews
集合并展开文档中的字段。
创建 Atlas Vector Search 索引
要在sample_airbnb.listingsAndReviews
集合上启用向量搜索,请创建 Atlas Vector Search 索引。
如果使用的是本地 Atlas 部署,请完成以下步骤:
定义 Atlas Vector Search 索引。
创建一个名为vector-index.json
的文件,并将以下索引定义粘贴到该文件中。
此索引定义指定为sample_airbnb.listingsAndReviews
集合的vectorSearch类型的索引中的embeddings
字段建立索引。该字段包含使用bge-large-en-v1.5
嵌入模型创建的嵌入。索引定义指定了1024
向量维度,并使用cosine
来衡量相似性。
{ "database": "sample_airbnb", "collectionName": "listingsAndReviews", "type": "vectorSearch", "name": "vector_index", "fields": [ { "type": "vector", "path": "embeddings", "numDimensions": 1024, "similarity": "cosine" } ] }
注意
要创建 Atlas Vector Search 索引,您必须对 Atlas 项目具有Project Data Access Admin
或更高访问权限。
如果您使用的是 Atlas 集群,请完成以下步骤:
在 AtlasClusters 中,转到项目的 页面。
如果尚未显示,请选择包含所需项目的组织导航栏中的Organizations菜单。
如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。
如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。
此时会显示“集群”页面。
转到集群的 Atlas Search 页面。
您可以从侧边栏、 Data Explorer或集群详细信息页面转到 Atlas Search 页面。
在侧边栏中,单击Services标题下的Atlas Search 。
从Select data source下拉列表中,选择您的集群并单击Go to Atlas Search 。
显示Atlas Search页面。
单击集群的对应 Browse Collections 按钮。
展开数据库并选择集合。
单击集合的Search Indexes标签页。
显示Atlas Search页面。
单击集群名称。
单击 Atlas Search 标签页。
显示Atlas Search页面。
定义 Atlas Vector Search 索引。
单击 Create Search Index(连接)。
在Atlas Vector Search下,选择JSON Editor ,然后单击Next 。
在 Database and Collection(数据库和集合)部分中找到
sample_airbnb
数据库,然后选择listingsAndReviews
集合。在 Index Name 字段中输入
vector_index
。将默认定义替换为以下索引定义,然后单击 Next。
此索引定义指定为
sample_airbnb.listingsAndReviews
集合的vectorSearch类型的索引中的embeddings
字段建立索引。该字段包含使用bge-large-en-v1.5
嵌入模型创建的嵌入。索引定义指定了1024
向量维度,并使用cosine
来衡量相似性。{ "fields":[ { "type": "vector", "path": "embeddings", "numDimensions": 1024, "similarity": "cosine" } ] }
与当地法学硕士一起回答问题
本部分演示了一个示例RAG实施,您可以使用 Atlas Vector Search、LangChain 和 GPT 4 All 在本地运行该实施。在交互式 Python 笔记本中,运行以下代码片段:
将 Atlas 实例化为向量数据库。
以下代码使用 Atlas Vector Search 的 LangChain 集成将本地 Atlas 部署或 Atlas 集群实例化为向量数据库(也称为 向量存储)。
from langchain_mongodb import MongoDBAtlasVectorSearch # Instantiate vector store vector_store = MongoDBAtlasVectorSearch( collection=collection, embedding=model, index_name="vector_index", embedding_key="embeddings", text_key="summary")
您还可以运行以下代码来执行示例语义搜索查询:
import pprint query = "beach house" results = vector_store.similarity_search(query) pprint.pprint(results)
[Document(page_content='Beach house with contemporary interior', metadata={'_id': '22123688', 'listing_url': 'https://www.airbnb.com/rooms/22123688', 'name': 'Bungan Beach House', ... }), Document(page_content="Well done !!! you won't find a better location in Manly. The “Beach House” Apartments overlook Cabbage Tree Bay Aquatic Reserve between Manly and Shelly Beach, in one of Manly's premier locations Swim, dive, snorkel, surf, paddle board, coastal walkways, ocean pool, restaurants, all literally at your doorstep, or simply chill and unwind. Manly is amazing, I look forward to welcoming you", metadata={'_id': '18917022', 'listing_url': 'https://www.airbnb.com/rooms/18917022', 'name': 'Beach House Manly Apartment 4', ... }]}), Document(page_content='Beautiful spacious two story beach house that has an amazing private gated grass area fronting Makaha beach. Perfect for family BBQ,s while watching the sun set into the ocean. Room for 10 people. Four night minimum stay required', metadata={'_id': '7099038', 'listing_url': 'https://www.airbnb.com/rooms/7099038', 'name': 'Ocean front Beach House in Makaha', ... }]}), Document(page_content='Beautifully finished, newly renovated house with pool. The ultimate in indoor/outdoor living. Excellent finishes and a short stroll to the beach.', metadata={'_id': '19768051', 'listing_url': 'https://www.airbnb.com/rooms/19768051', 'name': 'Ultra Modern Pool House Maroubra', ... }]})]
下载并配置本地 LLM 。
单击以下按钮可从7 GPT4 All 下载 Mistral B 模型。要探索其他模型,请参阅 GPT4 All 网站。
立即下载将以下代码粘贴到您的笔记本中以配置LLM 。运行之前,将
<path-to-model>
替换为在本地保存LLM的路径。from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain_community.llms import GPT4All # Configure the LLM local_path = "<path-to-model>" # Callbacks support token-wise streaming callbacks = [StreamingStdOutCallbackHandler()] # Verbose is required to pass to the callback manager llm = GPT4All(model=local_path, callbacks=callbacks, verbose=True)
回答有关数据的问题。
运行以下代码以完成RAG实施。此代码执行以下操作:
将 Atlas Vector Search 实例化为 检索器 查询相似文档。
创建以下特定于 LangChain 的组件:
使用样本查询提示LLM并返回响应。生成的响应可能会有所不同。
from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough # Instantiate Atlas Vector Search as a retriever retriever = vector_store.as_retriever() # Define prompt template template = """ Use the following pieces of context to answer the question at the end. {context} Question: {question} """ custom_rag_prompt = PromptTemplate.from_template(template) def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs) # Create chain rag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | custom_rag_prompt | llm | StrOutputParser() ) # Prompt the chain question = "Can you recommend me a few AirBnBs that are beach houses? Include a link to the listings." answer = rag_chain.invoke(question) # Return source documents documents = retriever.invoke(question) print("\nSource documents:") pprint.pprint(documents)
Answer: Yes, I can recommend a few AirBnBs that are beach houses. Here are some links to their respective listings: 1. Oceanfront home on private, gated property - https://www.airbnb.com/rooms/15073739 2. Ground Floor, Oceanfront condo with complete remodeling - https://www.airbnb.com/rooms/14687148 3. 4 bedroom house in a great location with ocean views and free salt water pool - https://www.airbnb.ca/s?host_id=740644 Source documents: [Document(page_content='Please look for Airbnb numb (Phone number hidden by Airbnb) to book with us. We do not take bookings through this one. It is live for others to read reviews. Oceanfront home on private, gated property. This unique property offers year-round swimming, private beach access and astounding ocean and mountain views. Traveling with a large group? Another 3 bedroom home is available for rent on this spacious property. Visit https://www.airbnb.com/rooms/15073739 or contact us for more information.', metadata={'_id': '14827972', 'listing_url': 'https://www.airbnb.com/rooms/14827972', 'name': 'Oceanfront Beach House Makai', ... }]}), Document(page_content='This GROUND FLOOR, OCEANFRONT condo is just feet from ocean access. Completely remodeled kitchen, bathroom and living room, with queen size bed in the bedroom, and queen size convertible sofa bed in the living room. Relax with the 55" SMART blue ray DVD, cable, and free WiFi. With ceiling fans in each room and trade winds, this condo rarely need the air conditioning unit in the living room. Airbnb charges a reservation fee to all guests at the time of booking. Please see "Other Things to Note"', metadata={'_id': '18173803', 'listing_url': 'https://www.airbnb.com/rooms/18173803', 'name': 'Papakea A108', ... }]}), Document(page_content='2 minutes to bus stop, beach - Cafes, Sun, Surf & Sand. 4 Secure rooms in older style, 4 bedroom house. Can squeeze in up to 15 guests (9 beds, 2 sofa beds in lounge & a single sofa mattress) BUT is best suited to 10-12 people Wireless Internet, under cover parking, unlimited street parking.', metadata={'_id': '2161945', 'listing_url': 'https://www.airbnb.com/rooms/2161945', 'name': 'Sand Sun Surf w Parking. City 9km', ... }]}), Document(page_content='High Quality for a third of the price! Great Location & Ocean Views! FREE Salt Water Roof-Deck Pool, Activities & Rental Car Desk! Hassle-Free Self Check-In via Lockbox. Located In Famous Waikiki: Easily walk to Beaches, Shops/all Restaurants! Hawaiian Convention Center is only 2 Blocks Away! On-Site Garage $. See my similar listings if your dates are not available. https://www.airbnb.ca/s?host_id=740644', metadata={'_id': '13146333', 'listing_url': 'https://www.airbnb.com/rooms/13146333', 'name': '~TROPICAL DREAM VACATION~ Ocean View', ... }]})]