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

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

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

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

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

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

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

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

LangChain を使用せずにローカルで RAG を実装する方法を学ぶには、「MongoDB ベクトル検索を使用してローカル RAG 実装をビルドする」を参照してください。

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

  • Python v3.10 以降。

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

  • ローカルで実行できる対話型 Python ノートブック。VS Code で対話型 Python ノートブックを実行できます。

このセクションでは、このチュートリアルの環境を設定します。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

ノートブックで次のコマンドを実行して、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 deployment
deployment = LocalDeployment.get_or_create(name="local-atlas-deployment")
deployment.start()
MONGODB_URI = deployment.connection_string()
print("Local deployment ready:", MONGODB_URI)

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

1

次のコードでは、 MongoDB ベクトル検索の LgChallenge 統合を使用して、 名前空間を使用して、ベクトルデータベース(ベクトルストアとも呼ばれる)としてローカルlangchain_db.local_rag Atlas 配置をインスタンス化します。

この例では、Hugging Faceの voyageai/voyage-4-nano モデルを指定しています。

from langchain_mongodb import MongoDBAtlasVectorSearch
from 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 store
vector_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 tutorial
MongoClient(MONGODB_URI)["langchain_db"]["local_rag"].drop()

次のコードをノートに貼り付けて実行し、最近のMongoDB収益レポートを含むサンプルPDF をベクトルストアに取り込みます。

このコードは、テキストスプリッターを使用して、PDFデータを小さな親ドキュメントに分割します。各ドキュメントのチャンクサイズ(文字数)とチャンクオーバーラップ(連続するチャンク間で重なる文字数)を指定します。

from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_pymupdf4llm import PyMuPDF4LLMLoader
# Load the PDF
loader = PyMuPDF4LLMLoader("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で 名前空間に移動すると、ベクトル埋め込みを確認できます。

また、配置の接続文字列を使用して、mongosh またはアプリケーションからローカル配置に接続することで、ベクトル埋め込みを表示することもできます。その後、langchain_db.local_rag コレクションに対して読み取り操作を実行できます。

3

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

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

インデックスのビルドするには約 1 分かかります。構築中、インデックスは最初の同期状態になります。構築が完了したら、コレクション内のデータのクエリを開始できます。

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

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

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

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

  3. 次のコードをノートブックに貼り付けて、LLM を構成します。実行前に、<path-to-model> を LLM をローカルに保存したパスで置き換えます。

    from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
    from langchain_classic.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
import pprint
# 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')]