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

使用 Atlas Vector Search 构建本地 RAG 实施

在此页面上

  • 背景
  • 先决条件
  • 创建本地 Atlas 部署
  • 设置环境
  • 使用本地模型生成嵌入
  • 创建 Atlas Vector Search 索引
  • 与当地法学硕士一起回答问题

本教程演示如何在本地实施检索增强生成 (RAG),而无需 API密钥或信用。要了解有关RAG的更多信息,请参阅使用 Atlas Vector Search 进行检索增强生成 (RAG)。

具体来说,您需要执行以下操作:

  1. 创建本地 Atlas 部署。

  2. 设置环境。

  3. 使用局部嵌入模型生成向量嵌入。

  4. 在您的数据上创建一个 Atlas Vector Search 索引。

  5. 部署本地法学硕士来回答有关数据的问题。

要完成本教程,您可以使用Atlas CLI创建本地 Atlas 部署,也可以在云上部署集群。 Atlas CLI 是 MongoDB Atlas 的命令行界面,您可以使用 Atlas CLI 从终端与 Atlas 交互,以执行各种任务,包括创建本地 Atlas 部署。要了解更多信息,请参阅从 Atlas CLI 管理本地和云部署。

注意

本地 Atlas 部署仅用于测试。对于生产环境,请部署集群。

您还可以在本教程中使用以下开源模型:

可通过多种方法在本地下载和部署 LLM 。在本教程中,您将使用7 GPT4 All 下载 Mistral B 模型 ,一个用于本地 法学硕士 开发的开源生态系统。

本教程还使用 LangChain ,一种流行的开源 LLM 框架,用于连接到这些模型并将其与 Atlas Vector Search 集成。如果您更喜欢不同的模型或不同的框架,您可以调整本教程,将模型名称和特定于 LangChain 的组件替换为您首选设置的等效组件。

要了解有关如何在RAG应用程序中利用 LangChain 的更多信息,请参阅开始使用 LangChain 集成。要详细了解可与 Atlas Vector Search 一起使用的其他框架,请参阅将向量搜索与 AI 技术集成。

如要完成本教程,您必须具备以下条件:

  • 已安装Atlas CLI并正在运行 v 1 。 14 。 3或更高版本。

  • 可以在本地运行的交互式 Python 笔记本。您可以在 VS Code 中运行交互式 Python 笔记本 。确保您的环境运行 Python v 。3 10或更高版本。

    注意

    如果您使用托管服务,例如 Colab ,确保您有足够的 RAM 来运行本教程。否则,可能会遇到性能问题。

在本部分中,您将创建一个本地 Atlas 部署以用作向量数据库。如果您有一个运行 MongoDB 6版本的 Atlas 集群。 0 。 11 、 7 。 0 。 2或更高版本(加载了样本数据)后,您可以跳过此步骤。

要创建本地部署,请执行以下操作:

1

在终端中,运行 atlas auth login以使用您的 Atlas 登录档案进行身份验证。要了解更多信息,请参阅从 Atlas CLI 连接。

注意

如果您没有 Atlas 帐户,请运行atlas setup创建一个新帐户。

2

运行atlas deployments setup并按照提示创建本地部署。

有关详细说明,请参阅创建本地 Atlas 部署。

3
  1. 在终端中运行以下命令以下载示例数据:

    curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive
  2. 运行以下命令,将数据加载到部署中,并将<port-number>替换为托管部署的端口:

    mongorestore --archive=sampledata.archive --port=<port-number>

在本部分中,您将为本教程设置环境。通过保存扩展名为.ipynb的文件来创建交互式 Python 笔记本,然后在笔记本中运行以下代码片段。

1

运行以下命令:

pip install --quiet langchain langchain_community langchain_huggingface langchain-mongodb pymongo sentence-transformers gpt4all
2

如果使用的是本地 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))

此代码需要一些时间才能运行。完成后,您可以使用部署的连接字符串从mongosh或应用程序连接到本地部署。然后,要查看向量嵌入,请对sample_airbnb.listingsAndReviews集合运行读取操作

此代码需要一些时间才能运行。完成后,您可以在 Atlas 用户界面中查看向量嵌入,方法是导航到集群中的sample_airbnb.listingsAndReviews集合并展开文档中的字段。

要在sample_airbnb.listingsAndReviews集合上启用向量搜索,请创建 Atlas Vector Search 索引。

如果使用的是本地 Atlas 部署,请完成以下步骤:

1

创建一个名为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"
}
]
}
2
  1. 保存文件,然后在终端中运行以下命令,将<path-to-file>替换为您创建的vector-index.json文件的路径。

    atlas deployments search indexes create --file <path-to-file>

注意

要创建 Atlas Vector Search 索引,您必须对 Atlas 项目具有Project Data Access Admin或更高访问权限。

如果您使用的是 Atlas 集群,请完成以下步骤:

1
  1. 如果尚未显示,请选择包含所需项目的组织导航栏中的Organizations菜单。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。

    此时会显示“集群”页面。

2

您可以从侧边栏、 Data Explorer或集群详细信息页面转到 Atlas Search 页面。

  1. 在侧边栏中,单击Services标题下的Atlas Search

  2. Select data source下拉列表中,选择您的集群并单击Go to Atlas Search

    显示Atlas Search页面。

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击集合的Search Indexes标签页。

    显示Atlas Search页面。

  1. 单击集群名称。

  2. 单击 Atlas Search 标签页。

    显示Atlas Search页面。

3
  1. 单击 Create Search Index(连接)。

  2. Atlas Vector Search下,选择JSON Editor ,然后单击Next

  3. Database and Collection(数据库和集合)部分中找到 sample_airbnb 数据库,然后选择 listingsAndReviews 集合。

  4. Index Name 字段中输入 vector_index

  5. 将默认定义替换为以下索引定义,然后单击 Next

    此索引定义指定为sample_airbnb.listingsAndReviews集合的vectorSearch类型的索引中的embeddings字段建立索引。该字段包含使用bge-large-en-v1.5嵌入模型创建的嵌入。索引定义指定了1024向量维度,并使用cosine来衡量相似性。

    {
    "fields":[
    {
    "type": "vector",
    "path": "embeddings",
    "numDimensions": 1024,
    "similarity": "cosine"
    }
    ]
    }
4

此时将显示一个模态窗口,让您知道索引正在构建中。

5

构建索引大约需要一分钟时间。在构建时,Status 列显示 Initial Sync。构建完成后,Status 列显示 Active

本部分演示了一个示例RAG实施,您可以使用 Atlas Vector Search、LangChain 和 GPT 4 All 在本地运行该实施。在交互式 Python 笔记本中,运行以下代码片段:

1

以下代码使用 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', ... }]})]

提示

另请参阅:

2
  1. 单击以下按钮可从7 GPT4 All 下载 Mistral B 模型。要探索其他模型,请参阅 GPT4 All 网站。

    立即下载
  2. 将以下代码粘贴到您的笔记本中以配置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)
3

运行以下代码以完成RAG实施。此代码执行以下操作:

  • 将 Atlas Vector Search 实例化为 检索器 查询相似文档。

  • 创建以下特定于 LangChain 的组件:

    • 提示模板 指示 法学硕士 使用检索到的文档作为查询的上下文。 LangChain 将这些文档传递给{context} 输入变量,并将您的查询传递给{question} 变量。

    • 一条 将 Atlas Vector Search 指定为检索器、您编写的提示模板以及您配置为生成上下文感知响应的本地 LLM

  • 使用样本查询提示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', ... }]})]

后退

混合搜索

来年

AI 集成