MongoDB Atlas
本筆記本涵蓋如何在 LangChain 中使用 MongoDB Atlas 向量搜尋,使用 langchain-mongodb
套件。
MongoDB Atlas 是一個完全託管的雲端資料庫,可在 AWS、Azure 和 GCP 中使用。它支援原生向量搜尋、全文檢索 (BM25) 以及在您的 MongoDB 文件資料上進行混合搜尋。
MongoDB Atlas Vector Search 允許您將嵌入儲存在 MongoDB 文件中、建立向量搜尋索引,並使用近似最近鄰演算法 (
Hierarchical Navigable Small Worlds
) 執行 KNN 搜尋。它使用 $vectorSearch MQL Stage。
設定
*執行 MongoDB 版本 6.0.11、7.0.2 或更高版本(包括 RC)的 Atlas 叢集。
若要使用 MongoDB Atlas,您必須先部署叢集。我們提供永久免費層級的叢集,可在您選擇的雲端上使用。若要開始使用,請前往 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 Vector Search 支援使用 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 文件網站
- 此功能已正式發布,可供生產部署使用。
- 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