Docs 菜单
Docs 主页
/ /

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

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

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

  1. 创建本地 Atlas 部署。

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

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

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

使用本教程的可运行版本以作为 Python 笔记本

要学习;了解如何在不使用 LangChain 的情况下在本地实现RAG,请参阅 使用MongoDB Vector Search 构建本地 RAG 实施。

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

  • 已安装并运行 v1.14.3 或更高版本的 Atlas CLI

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

要创建本地部署,请在终端中运行 atlas deployments setup,然后按照提示完成部署。

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

在本节中,您将为本教程设置环境。

1

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

mkdir local-rag-langchain-mongodb
cd local-rag-langchain-mongodb
2

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

touch langchain-local-rag.ipynb
3

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

pip install --quiet --upgrade pymongo langchain langchain-community langchain-huggingface gpt4all pypdf
4

在您的笔记本中运行以下代码,将 <port-number> 替换为本地部署的端口。

MONGODB_URI = ("mongodb://localhost:<port-number>/?directConnection=true")

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

1

以下代码使用针对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"
)
2

在笔记本中粘贴并运行以下代码,以将包含最近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集合运行读取操作。

3

要在向量存储上启用向量搜索查询,请在 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 的其他方法,请参阅在本地运行模型。

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

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

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

运行以下代码,完成 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')]

后退

自查询检索

在此页面上