除了在云上部署MongoDB Atlas之外,您还可以使用Atlas CLI在本地计算机上部署独立的MongoDB实例。LangChain MongoDB集成支持Atlas集群和本地部署。指定连接字符串参数时,可以指定本地部署连接字符串,而不是集群连接字符串。
本教程演示如何使用本地Atlas部署、本地模型和 LangChain MongoDB集成来实现检索增强生成 (RAG)。具体来说,您执行以下操作:
创建本地 Atlas 部署。
使用本地嵌入模型生成向量嵌入。
使用本地 Atlas 部署作为矢量存储。
使用当地的法学硕士来回答有关您的数据的问题。
使用本教程的可运行版本以作为 Python 笔记本。
要学习;了解如何在不使用 LangChain 的情况下在本地实现RAG,请参阅 使用MongoDB Vector Search 构建本地 RAG 实施。
先决条件
如要完成本教程,您必须具备以下条件:
创建本地 Atlas 部署
要创建本地部署,请在终端中运行 atlas deployments setup,然后按照提示完成部署。
有关详细说明,请参阅创建本地 Atlas 部署。
您可以使用Atlas CLI创建本地Atlas部署。Atlas CLI是MongoDB Atlas的命令行界面,您可以使用Atlas CLI从终端与Atlas交互,以执行各种任务,包括创建本地Atlas部署。这些是完全本地部署,不需要连接到云。
本地 Atlas 部署仅用于测试。对于生产环境,部署一个集群。
设置环境
在本节中,您将为本教程设置环境。
将您的本地部署用作向量存储
您可以将本地Atlas部署用作向量数据库(也称为向量存储)。将以下代码片段复制并粘贴到笔记本中。
实例化向量存储。
以下代码使用针对MongoDB Vector Search 的 LangChain 集成,使用 langchain_db.local_rag命名空间将本地Atlas部署实例化为向量数据库(也称为向量存储)。
此示例指定了 Huugging Face 中的Mixedbread-ai/mxbai-embed-large-v1 模型。
from langchain_mongodb import MongoDBAtlasVectorSearch from langchain_huggingface import HuggingFaceEmbeddings # Load the embedding model (https://huggingface.co/mixedbread-ai/mxbai-embed-large-v1) embedding_model = HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1") # Instantiate vector store vector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string = MONGODB_URI, namespace = "langchain_db.local_rag", embedding=embedding_model, index_name="vector_index" )
将文档添加到向量存储中。
在笔记本中粘贴并运行以下代码,以将包含最近MongoDB收益报告的示例PDF 导入向量存储中。
该代码使用文本拆分器将 PDF 数据分割成较小的父文档。它指定每个文档的数据块大小(字符数)和数据块重叠(连续数据块之间的重叠字符数)。
from langchain_community.document_loaders import PyPDFLoader from langchain_text_splitters import RecursiveCharacterTextSplitter # Load the PDF loader = PyPDFLoader("https://investors.mongodb.com/node/13176/pdf") data = loader.load() # Split PDF into documents text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20) docs = text_splitter.split_documents(data) # Add data to the vector store vector_store.add_documents(docs)
此代码可能需要几分钟才能运行。完成后,如果您使用的是Atlas ,则可以导航到Atlas 用户界面中的langchain_db.local_rag 命名空间来验证向量嵌入。
您还可以使用部署的连接字符串从 mongosh 或应用程序连接到本地部署,以查看向量嵌入。然后,您可以对 langchain_db.local_rag集合运行读取操作。
创建MongoDB Vector Search索引。
要在向量存储上启用向量搜索查询,请在 langchain_db.test集合上创建MongoDB Vector Search索引。您可以使用 LangChain 辅助方法创建索引:
# Use helper method to create the vector search index vector_store.create_vector_search_index( dimensions = 1024 # The dimensions of the vector embeddings to be indexed )
构建索引大约需要一分钟时间。在建立索引时,索引处于初始同步状态。 构建完成后,您可以开始查询集合中的数据。
使用本地法学硕士回答问题
本部分演示了一个示例RAG实施,您可以使用MongoDB Vector Search 和 GPT4All 在本地运行该实施。
要学习;了解使用 LangChain 在本地运行LLM 的其他方法,请参阅在本地运行模型。
加载本地 LLM。
点击以下按钮从 GPT4All 下载 Mistral 7B 模型。要探索其他模型,请参阅 GPT4All 网站。
立即下载将此模型移动到
local-rag-mongodb项目目录中。将以下代码粘贴到您的笔记本中以配置 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 实现:
from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough # Instantiate MongoDB 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 = "What was MongoDB's latest acquisition?" answer = rag_chain.invoke(question) # Return source documents documents = retriever.invoke(question) print("\nSource documents:") pprint.pprint(documents)
Answer: MongoDB's latest acquisition was Voyage AI, a pioneer in state-of-the-art embedding and reranking models that power next-generation Source documents: [Document(id='680a98187685ddb66d29ed88', metadata={'_id': '680a98187685ddb66d29ed88', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 1, 'page_label': '2'}, page_content='Measures."\nFourth Quarter Fiscal 2025 and Recent Business Highlights\nMongoDB acquired Voyage AI, a pioneer in state-of-the-art embedding and reranking models that power next-generation'), Document(id='680a98187685ddb66d29ed8c', metadata={'_id': '680a98187685ddb66d29ed8c', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 1, 'page_label': '2'}, page_content='conjunction with the acquisition of Voyage, MongoDB is announcing a stock buyback program of $200 million, to offset the\ndilutive impact of the acquisition consideration.'), Document(id='680a98187685ddb66d29ee3f', metadata={'_id': '680a98187685ddb66d29ee3f', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 8, 'page_label': '9'}, page_content='View original content to download multimedia:https://www.prnewswire.com/news-releases/mongodb-inc-announces-fourth-quarter-and-full-\nyear-fiscal-2025-financial-results-302393702.html'), Document(id='680a98187685ddb66d29edde', metadata={'_id': '680a98187685ddb66d29edde', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 3, 'page_label': '4'}, page_content='distributed database on the market. With integrated capabilities for operational data, search, real-time analytics, and AI-powered retrieval, MongoDB')]