对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

使用MongoDB和 LangChain 构建本地 RAG 实施

除了在云上部署MongoDB Atlas之外,您还可以使用Atlas CLI在本地计算机上部署独立的MongoDB实例。LangChain MongoDB集成支持Atlas集群和本地部署。指定连接字符串参数时,可以指定本地部署连接字符串,而不是集群连接字符串。

本教程演示如何使用本地Atlas部署、本地模型和 LangChain MongoDB集成来实现检索增强生成 (RAG)。具体来说,您执行以下操作:

  1. 创建本地 Atlas 部署。

  2. 使用本地嵌入模型生成向量嵌入。

  3. 使用本地 Atlas 部署作为矢量存储。

  4. 使用当地的法学硕士来回答有关您的数据的问题。

要了解如何在本地实现 RAG 而不使用 LangChain,请参阅 使用 MongoDB 向量搜索构建本地 RAG 实现。

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

  • Python v3.10 或更高版本。

  • Docker 在本地运行。

  • 可以在本地运行的交互式 Python 笔记本。您可以在 VS Code 中运行交互式 Python 笔记本。

在本节中,您将为本教程设立环境。atlas-local-lib-py 库通过 Docker 自动创建和管理您的本地 MongoDB 部署,无需手动设置或 CLI 命令。

1

在终端中运行以下命令,创建一个名为 local-rag-langchain-mongodb 的新目录。

mkdir local-rag-langchain-mongodbcd local-rag-langchain-mongodb
2

以下命令将在名为 langchain-local-rag.ipynb 的目录中创建一个笔记本。

touch langchain-local-rag.ipynb
3

在笔记本中运行以下命令以安装 uv:

%pip install --quiet uv

在您的笔记本中运行以下命令,以安装所需的依赖项:

import sys!uv pip install --system --python "{sys.executable}" atlas-local-lib-py pymongo langchain langchain-classic langchain-mongodb langchain-pymupdf4llm langchain-text-splitters gpt4all langchain-huggingface==1.2.2 sentence-transformers==5.7.0 transformers==4.57.6
4

在笔记本中运行以下代码,以创建新的本地部署或重用具有匹配配置的现有部署。这还可以编程方式检索连接字符串。

from atlas_local import LocalDeployment # Create or reuse a local Atlas deploymentdeployment = LocalDeployment.get_or_create(name="local-atlas-deployment")deployment.start()MONGODB_URI = deployment.connection_string()print("Local deployment ready:", MONGODB_URI)

您可以将本地Atlas部署用作向量数据库(也称为向量存储)。将以下代码片段复制并粘贴到笔记本中。

1

以下代码使用针对MongoDB Vector Search 的 LangChain 集成,使用 langchain_db.local_rag命名空间将本地Atlas部署实例化为向量数据库(也称为向量存储)。

此示例指定了来自 Hugging Face 的 voyageai/voyage-4-nano 模型。

from langchain_mongodb import MongoDBAtlasVectorSearchfrom langchain_huggingface import HuggingFaceEmbeddings # Load the embedding model (https://huggingface.co/voyageai/voyage-4-nano)embedding_model = HuggingFaceEmbeddings( model_name="voyageai/voyage-4-nano", model_kwargs={"trust_remote_code": True, "truncate_dim": 2048}, encode_kwargs={"prompt_name": "document"}, query_encode_kwargs={"prompt_name": "query"},) # Instantiate vector storevector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string = MONGODB_URI, namespace = "langchain_db.local_rag", embedding=embedding_model, index_name="vector_index")
2

在笔记本中运行以下代码,从一个干净的 langchain_db.local_rag 集合开始,以防此教程上一个运行中出现问题:

from pymongo import MongoClient # Start from a clean collection, in case of previous runs of this tutorialMongoClient(MONGODB_URI)["langchain_db"]["local_rag"].drop()

在笔记本中粘贴并运行以下代码,以将包含最近MongoDB收益报告的示例PDF 导入向量存储中。

该代码使用文本拆分器将 PDF 数据分割成较小的父文档。它指定每个文档的数据块大小(字符数)和数据块重叠(连续数据块之间的重叠字符数)。

from langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_pymupdf4llm import PyMuPDF4LLMLoader # Load the PDFloader = PyMuPDF4LLMLoader("https://investors.mongodb.com/node/13176/pdf")data = loader.load() # Split PDF into documentstext_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20)docs = text_splitter.split_documents(data) # Add data to the vector storevector_store.add_documents(docs)

此代码可能需要几分钟才能运行。完成后,如果您使用的是Atlas ,则可以导航到Atlas 用户界面中的langchain_db.local_rag 命名空间来验证向量嵌入。

您还可以使用部署的连接字符串从 mongosh 或应用程序连接到本地部署,以查看向量嵌入。然后,您可以对 langchain_db.local_rag集合运行读取操作。

3

要在向量存储上启用向量搜索查询,请在 langchain_db.local_rag集合上创建MongoDB Vector Search索引。您可以使用 LangChain 辅助方法创建索引:

# Use helper method to create the vector search indexvector_store.create_vector_search_index( dimensions = 2048 # The dimensions of the vector embeddings to be indexed)

构建索引大约需要一分钟时间。在构建时,索引处于初始同步状态。构建完成后,您可以开始查询集合中的数据。

本节演示了一个示例 RAG 实现,您可以使用 MongoDB 向量搜索和 GPT4All 在本地运行该实现。

要学习;了解使用 LangChain 在本地运行LLM 的其他方法,请参阅在本地运行模型。

1
  1. 点击以下按钮从 GPT4All 下载 Mistral 7B 模型。要探索其他模型,请参阅 GPT4All 网站。

    立即下载
  2. 将此模型移动到 local-rag-langchain-mongodb 项目目录中。

  3. 将以下代码粘贴到笔记本中,配置 LLM。在运行之前,将 <path-to-model> 替换为您在本地保存 LLM 的路径。

    from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandlerfrom langchain_classic.llms import GPT4All # Configure the LLMlocal_path = "<path-to-model>" # Callbacks support token-wise streamingcallbacks = [StreamingStdOutCallbackHandler()] # Verbose is required to pass to the callback managerllm = GPT4All(model=local_path, callbacks=callbacks, verbose=True)
2

运行以下代码,完成 RAG 实现:

from langchain_core.prompts import PromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnablePassthroughimport pprint # Instantiate MongoDB Vector Search as a retrieverretriever = vector_store.as_retriever() # Define prompt templatetemplate = """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 chainrag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | custom_rag_prompt | llm | StrOutputParser()) # Prompt the chainquestion = "What was MongoDB's latest acquisition?"answer = rag_chain.invoke(question) # Return source documentsdocuments = 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-generationSource 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')]