MongoDB Atlas
本筆記本涵蓋如何使用 langchain-mongodb
套件在 LangChain 中使用 MongoDB Atlas 向量搜尋。
MongoDB Atlas 是一個完全託管的雲端資料庫,可在 AWS、Azure 和 GCP 中使用。 它支援原生向量搜尋、全文搜尋 (BM25) 以及 MongoDB 文件資料的混合搜尋。
MongoDB Atlas 向量搜尋 允許將您的嵌入儲存在 MongoDB 文件中、建立向量搜尋索引,並使用近似最近鄰演算法 (
Hierarchical Navigable Small Worlds
) 執行 KNN 搜尋。 它使用 $vectorSearch MQL Stage。
設定
*執行 MongoDB 版本 6.0.11、7.0.2 或更高版本(包括 RC)的 Atlas 叢集。
要使用 MongoDB Atlas,您必須先部署一個叢集。 我們在您選擇的雲端上提供 Forever-Free 層級的叢集。 若要開始使用,請前往 Atlas:快速入門。
您需要安裝 langchain-mongodb
和 pymongo
才能使用此整合。
pip install -qU langchain-mongodb pymongo
憑證
對於本筆記本,您需要找到您的 MongoDB 叢集 URI。
有關查找叢集 URI 的資訊,請閱讀本指南。
import getpass
MONGODB_ATLAS_CLUSTER_URI = getpass.getpass("MongoDB Atlas Cluster URI:")
如果您想要獲得一流的自動化追蹤模型呼叫,您也可以透過取消註解下方內容來設定您的 LangSmith API 金鑰
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
初始化
pip install -qU langchain-openai
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
from langchain_mongodb import MongoDBAtlasVectorSearch
from pymongo import MongoClient
# initialize MongoDB python client
client = MongoClient(MONGODB_ATLAS_CLUSTER_URI)
DB_NAME = "langchain_test_db"
COLLECTION_NAME = "langchain_test_vectorstores"
ATLAS_VECTOR_SEARCH_INDEX_NAME = "langchain-test-index-vectorstores"
MONGODB_COLLECTION = client[DB_NAME][COLLECTION_NAME]
vector_store = MongoDBAtlasVectorSearch(
collection=MONGODB_COLLECTION,
embedding=embeddings,
index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,
relevance_score_fn="cosine",
)
# Create vector search index on the collection
# Since we are using the default OpenAI embedding model (ada-v2) we need to specify the dimensions as 1536
vector_store.create_vector_search_index(dimensions=1536)
[可選] 除了上面的 vector_store.create_vector_search_index
指令外,您也可以使用 Atlas UI 和以下索引定義來建立向量搜尋索引
{
"fields":[
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "cosine"
}
]
}
管理向量儲存
建立向量儲存後,我們可以透過新增和刪除不同的項目來與其互動。
將項目新增至向量儲存
我們可以使用 add_documents
函式將項目新增至我們的向量儲存。
from uuid import uuid4
from langchain_core.documents import Document
document_1 = Document(
page_content="I had chocalate chip pancakes and scrambled eggs for breakfast this morning.",
metadata={"source": "tweet"},
)
document_2 = Document(
page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
metadata={"source": "news"},
)
document_3 = Document(
page_content="Building an exciting new project with LangChain - come check it out!",
metadata={"source": "tweet"},
)
document_4 = Document(
page_content="Robbers broke into the city bank and stole $1 million in cash.",
metadata={"source": "news"},
)
document_5 = Document(
page_content="Wow! That was an amazing movie. I can't wait to see it again.",
metadata={"source": "tweet"},
)
document_6 = Document(
page_content="Is the new iPhone worth the price? Read this review to find out.",
metadata={"source": "website"},
)
document_7 = Document(
page_content="The top 10 soccer players in the world right now.",
metadata={"source": "website"},
)
document_8 = Document(
page_content="LangGraph is the best framework for building stateful, agentic applications!",
metadata={"source": "tweet"},
)
document_9 = Document(
page_content="The stock market is down 500 points today due to fears of a recession.",
metadata={"source": "news"},
)
document_10 = Document(
page_content="I have a bad feeling I am going to get deleted :(",
metadata={"source": "tweet"},
)
documents = [
document_1,
document_2,
document_3,
document_4,
document_5,
document_6,
document_7,
document_8,
document_9,
document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]
vector_store.add_documents(documents=documents, ids=uuids)
['03ad81e8-32a0-46f0-b7d8-f5b977a6b52a',
'8396a68d-f4a3-4176-a581-a1a8c303eea4',
'e7d95150-67f6-499f-b611-84367c50fa60',
'8c31b84e-2636-48b6-8b99-9fccb47f7051',
'aa02e8a2-a811-446a-9785-8cea0faba7a9',
'19bd72ff-9766-4c3b-b1fd-195c732c562b',
'642d6f2f-3e34-4efa-a1ed-c4ba4ef0da8d',
'7614bb54-4eb5-4b3b-990c-00e35cb31f99',
'69e18c67-bf1b-43e5-8a6e-64fb3f240e52',
'30d599a7-4a1a-47a9-bbf8-6ed393e2e33c']
從向量儲存刪除項目
vector_store.delete(ids=[uuids[-1]])
True
查詢向量儲存
建立向量儲存並新增相關文件後,您很可能希望在鏈或代理程式執行期間查詢它。
直接查詢
相似度搜尋
可以如下執行簡單的相似度搜尋
results = vector_store.similarity_search(
"LangChain provides abstractions to make working with LLMs easy", k=2
)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'_id': 'e7d95150-67f6-499f-b611-84367c50fa60', 'source': 'tweet'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'_id': '7614bb54-4eb5-4b3b-990c-00e35cb31f99', 'source': 'tweet'}]
具有分數的相似度搜尋
您也可以使用分數進行搜尋
results = vector_store.similarity_search_with_score("Will it be hot tomorrow?", k=1)
for res, score in results:
print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")
* [SIM=0.784560] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'_id': '8396a68d-f4a3-4176-a581-a1a8c303eea4', 'source': 'news'}]
使用相似度搜尋進行預先篩選
Atlas 向量搜尋支援使用 MQL 運算子進行預先篩選。 下面是一個索引範例和對上述相同資料的查詢,允許您對「page」欄位進行元資料篩選。 您可以使用定義的篩選更新現有索引,並使用向量搜尋進行預先篩選。
若要啟用預先篩選,您需要更新索引定義以包含篩選欄位。 在此範例中,我們將使用 source
欄位作為篩選欄位。
可以使用 MongoDBAtlasVectorSearch.create_vector_search_index
方法以程式設計方式完成此操作。
vectorstore.create_vector_search_index(
dimensions=1536,
filters=[{"type":"filter", "path":"source"}],
update=True
)
或者,您也可以使用具有以下索引定義的 Atlas UI 更新索引
{
"fields":[
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "cosine"
},
{
"type": "filter",
"path": "source"
}
]
}
然後,您可以執行帶有篩選器的查詢,如下所示
results = vector_store.similarity_search(query="foo", k=1, pre_filter={"source": {"$eq": "https://example.com"}})
for doc in results:
print(f"* {doc.page_content} [{doc.metadata}]")
其他搜尋方法
除了本筆記本中涵蓋的搜尋方法之外,還有許多其他的搜尋方法,例如 MMR 搜尋或依向量搜尋。如需 MongoDBAtlasVectorStore
提供的完整搜尋功能列表,請查看API 參考文件。
將向量儲存轉為檢索器來查詢
您也可以將向量儲存轉換為檢索器,以便在您的鏈中使用。
以下是如何將您的向量儲存轉換為檢索器,然後使用簡單的查詢和篩選器來調用檢索器。
retriever = vector_store.as_retriever(
search_type="similarity_score_threshold",
search_kwargs={"k": 1, "score_threshold": 0.2},
)
retriever.invoke("Stealing from the bank is a crime")
[Document(metadata={'_id': '8c31b84e-2636-48b6-8b99-9fccb47f7051', 'source': 'news'}, page_content='Robbers broke into the city bank and stole $1 million in cash.')]
用於檢索增強生成的使用方式
如需了解如何使用此向量儲存進行檢索增強生成 (RAG) 的指南,請參閱以下章節
其他注意事項
- 更多文件可在 MongoDB 的 LangChain 文件網站上找到
- 此功能已正式推出 (Generally Available),可供生產環境部署。
- langchain 版本 0.0.305 (發布說明) 引入了對 $vectorSearch MQL stage 的支援,該功能適用於 MongoDB Atlas 6.0.11 和 7.0.2。 使用較早版本的 MongoDB Atlas 的使用者需要將其 LangChain 版本固定為 <=0.0.304
API 參考
如需所有 MongoDBAtlasVectorSearch
功能和配置的詳細文件,請前往 API 參考:https://langchain-python.dev.org.tw/api_reference/mongodb/index.html