AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

MongoDBと Lgachein でローカル RAG 実装を構築

MongoDB Atlas をクラウドに配置するだけでなく、Atlas CLI を使用して自己整合型MongoDBインスタンスをローカル マシンに配置します。LgChuin MongoDB統合は、Atlas クラスターとローカル配置の両方をサポートします。接続文字列パラメーターを指定する場合、 クラスター接続文字列の代わりにローカル配置の接続文字列を指定できます。

このチュートリアルでは、ローカル Atlas 配置、ローカル モデル、およびMongoDB統合を使用して、検索拡張生成 (RAG)(RAG)を実装する方法を説明します。具体的には、次のアクションを実行します。

  1. Atlas のローカル配置の作成。

  2. ローカル埋め込みモデルを使用してベクトル埋め込みを生成します。

  3. Atlas のローカル配置をベクトルストアとして使用します。

  4. ローカル LVM を使用して、データに関する質問に答えます。

To learn how to implement RAG locally without using LangChain, see Build a Local RAG Implementation with MongoDB Vector Search.

Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。

  • Python v3.10 以降。

  • Docker はローカルで実行されます。

  • An interactive Python notebook that you can run locally. You can run interactive Python notebooks in VS Code.

このチュートリアルでは、atlas-local-lib-py Pythonライブラリを使用してローカル Atlas 配置を作成および管理します。ライブラリは Docker コンテナをラップして、クラウドに接続する必要のない完全なローカル配置を提供します。ライブラリは配置ライフサイクル、接続文字列の取得を自動的に取り扱い、Jupyter Notebook セッション間での配置の再利用性を確保します。

Atlas のローカル配置はテスト専用です。 本番環境には、 クラスターをデプロイします。

このセクションでは、このチュートリアルの環境を設定します。atlas-local-lib-py ライブラリは、Docker を介してローカル MongoDB 配置を自動的に作成および管理するため、手動での設定や CLI コマンドは不要です。

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 atlas-local-lib-py
4

ノートブックで次のコードを実行して、新しいローカル配置を作成するか、一致する構成で既存の配置を再利用します。これにより、接続文字列もプログラムで取得されます。

from atlas_local import LocalDeployment
deployment = LocalDeployment.get_or_create(name="local-atlas-deployment")
MONGODB_URI = deployment.connection_string()

Atlas のローカル配置は、ベクトルデータベースとして、またはベクトルストア として使用できます。次のコード スニペットをコピーして、ノートに貼り付けます。

1

The following code uses the LangChain integration for MongoDB Vector Search to instantiate your local Atlas deployment as a vector database, also called a vector store, using the langchain_db.local_rag namespace.

1この例では、Hugingface の bios を使用して埋め込みを生成し、

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)

このコードの実行には数分かかる場合があります。Atlaslangchain_db.local_rag を使用している場合は、Atlas UIで 名前空間に移動すると、ベクトル埋め込みを確認できます。

You can also view your vector embeddings by connecting to your local deployment from mongosh or your application using your deployment's connection string. Then you can run read operations on the langchain_db.local_rag collection.

3

ベクトルストアでベクトル検索クエリを有効にするには、langchain_db.testコレクションにMongoDB ベクトル検索インデックスを作成します。インデックスは、Lgacheinヘルパーメソッドを使用して作成できます。

# 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
)

The index should take about one minute to build. While it builds, the index is in an initial sync state. When it finishes building, you can start querying the data in your collection.

このセクションでは、 MongoDB ベクトル検索と GPT4All を使用してローカルで実行できるサンプルRG実装を示します。

LangChain を使用してLLMをローカルで実行する他の方法については、「モデルをローカルで実行」を参照してください。

1
  1. 7次のボタンをクリックして、GPT4 All から Misttal B モデルをダウンロードします。他のモデルを確認するには、「 GPT4 すべてのウェブサイト 」を参照してください。

    ダウンロード
  2. このモデルをlocal-rag-mongodbプロジェクト ディレクトリに移動します。

  3. Paste the following code in your notebook to configure the LLM. Before running, replace <path-to-model> with the path where you saved the LLM locally.

    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')]