注意
このチュートリアルでは、Lgachein のPythonライブラリ を使用します。JavaScriptライブラリを使用するチュートリアルについては、「 Lgachein JavaScript/ Typescript統合を使い始める 」を参照してください。
MongoDB ベクトル検索 をLgChuin と統合して、LM アプリケーションを構築し、検索拡張生成 (RAG)(RAG)を実装できます。 このチュートリアルでは、Lgachein とMongoDB ベクトル検索 の使用を開始し、データのセマンティック検索を実行し、RAG実装を構築する方法を説明します。具体的には、次のアクションを実行します。
環境を設定します。
カスタム データをMongoDBに保存します。
データにMongoDB ベクトル検索インデックスを作成します。
次のベクトル検索クエリを実行します。
セマンティック検索。
スコア付きのセマンティック検索。
メタデータの事前フィルタリングによるセマンティック検索。
MongoDB ベクトル検索を使用してデータの質問に答え、RAG を実装します。
バックグラウンド
LgChuin は、「チェーン」の使用を通じて LVM アプリケーションの作成を簡素化するオープンソースのフレームワークです。 チェーンは 、RAG を含むさまざまなAIユースケースで組み合わせることができる Lgachein 固有のコンポーネントです。
MongoDB ベクトル検索を LangChain と統合することで、MongoDB をベクトルデータベースとして利用し、MongoDB ベクトル検索を使用して、データから意味的に類似したドキュメントを検索し、RAG を実装することができます。RAG の詳細については、「MongoDB による検索拡張生成(RAG)」を参照してください。
前提条件
Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。
次のいずれかのMongoDBクラスター タイプ
MongoDB バージョン 6.0.11 を実行している Atlas クラスター、7.0.2以降。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認します。
Python と Docker を使用して作成されたローカル Atlas 配置。
atlas-local-lib-py(pip install atlas-local-lib-py) をインストールして、ローカル配置をプログラムで作成および管理します。詳細については、atlas-local-lib-py リポジトリを参照してください。検索とベクトル検索がインストールされた MongoDB Community クラスター。
Voyage AI API キー。API キーを作成するには、Voyage AI モデル API キーの管理を参照してください。
OpenAI APIキー。APIリクエストに使用できるクレジットを持つ OpenAI アカウントが必要です。OpenAI アカウントの登録の詳細については、OpenAI APIウェブサイト を参照してください。
Colab などのインタラクティブPythonノートを実行するための環境。
環境を設定する
このチュートリアルの環境を設定します。 .ipynb 拡張機能のファイルを保存して、インタラクティブPythonノートを作成します。 このノートはPythonコード スニペットを個別に実行でき、このチュートリアルのコードを実行するために使用します。
ノートク環境を設定するには、次の手順に従います。
依存関係をインストールしてインポートします。
次のコマンドを実行します:
pip install --quiet --upgrade langchain langchain-community langchain-core langchain-mongodb langchain-voyageai langchain-openai langchain-text-splitters pymongo pypdf次に、次のコードを実行して必要なパッケージをインポートします。
import os, pymongo, pprintfrom langchain_community.document_loaders import PyPDFLoaderfrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnablePassthroughfrom langchain_mongodb import MongoDBAtlasVectorSearchfrom langchain_voyageai import VoyageAIEmbeddingsfrom langchain_openai import ChatOpenAIfrom langchain.prompts import PromptTemplatefrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom pymongo import MongoClientfrom pymongo.operations import SearchIndexModel環境変数を定義してください。
次のコードを実行し、プレースホルダーを次の値に置き換えます。
投票AIと OpenAI APIキー
MongoDBクラスターの接続文字列。
os.environ["VOYAGE_API_KEY"] = "<voyage-api-key>"os.environ["OPENAI_API_KEY"] = "<openai-api-key>"MONGODB_URI = "<connection-string>"注意
<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。
接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net重要:接続文字列にデータベースユーザーの認証情報が含まれていることを確認します。接続文字列の検索方法の詳細については、クライアント ライブラリ経由でクラスターに接続する を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true詳細については、「接続文字列 」を参照してください。
MongoDB をベクトル ストアとして使用
次に、カスタム データをMongoDBにロードし、 MongoDBクラスターをベクトルデータベースとしてインスタンス化します。これはベクトルストアとも呼ばれます。次のコード スニペットをコピーして、ノートに貼り付けます。
サンプル データをロードします。
このチュートリアルでは、ベクトルストアのデータソースとして、最新のMongoDB収益レポートに関する一般にアクセス可能な PDFドキュメントを使用します。
サンプル データをロードするには、次のコード スニペットを実行します。 この処理では、次の処理が行われます。
指定された URL から PDF を検索し、未加工のテキスト データを読み込みます。
テキストスプリット を使用して、データを小さなドキュメントに分裂。
各ドキュメントの文字数と連続する 2 つのドキュメント間で重複する文字数を決定する チャンク パラメータを指定します。
# Load the PDFloader = PyPDFLoader("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)
# Print the first documentdocs[0]Document(metadata={'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': 0, 'page_label': '1'}, page_content='MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results\nMarch 5, 2025\nFourth Quarter Fiscal 2025 Total Revenue of $548.4 million, up 20% Year-over-Year')ベクトル ストアをインスタンス化します。
次のコードを実行して、サンプル ドキュメントから vector_store という名前のベクトル ストア インスタンスを作成します。このスニペットによって次の内容が指定されます。
MongoDBクラスターへの接続文字列。
langchain_db.testは、ドキュメントを保存するためのMongoDB名前空間です。Vyage AIの
voyage-3-large埋め込みモデル。テキストをembeddingフィールドのベクトル埋め込みに変換する。vector_indexベクトル ストアをクエリするために使用するインデックスとして 。
# Instantiate the vector store using your MongoDB connection stringvector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string = MONGODB_URI, namespace = "langchain_db.test", embedding = VoyageAIEmbeddings(model="voyage-3-large"), index_name = "vector_index")
# Add documents to the vector storevector_store.add_documents(documents=docs)Atlaslangchain_db.test を使用している場合は、サンプルコードの実行中後、Atlas UIの 名前空間に移動することでベクトル埋め込みを検証できます。
MongoDB ベクトル検索インデックスの作成
ベクトルストアでベクトル検索クエリを有効にするには、L SheinヘルパーメソッドまたはPyMongoドライバー メソッドを使用して、langchain_db.testコレクションにMongoDB ベクトル検索インデックスを作成します。
ノートブックで次のコードを、お好みの方法で実行します。インデックス定義では、次のフィールドのインデックス作成を指定します。
embeddingベクトル型としてのフィールド。embeddingフィールドには、Voyage AI のvoyage-3-large埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、1024ベクトル次元を指定し、cosineを使用して類似性を測定します。page_labelPDF 内のページ番号でデータを事前にフィルタリングするためのフィルター タイプとしてのフィールド。
# Use helper method to create the vector search indexvector_store.create_vector_search_index( dimensions = 1024, # The number of vector dimensions to index filters = [ "page_label" ])# Connect to your clusterclient = MongoClient(MONGODB_URI)collection = client["langchain_db"]["test"]
# Create your vector search index model, then create the indexsearch_index_model = SearchIndexModel( definition={ "fields": [ { "type": "vector", "path": "embedding", "numDimensions": 1024, "similarity": "cosine" }, { "type": "filter", "path": "page_label" } ] }, name="vector_index", type="vectorSearch")
collection.create_search_index(model=search_index_model)インデックスのビルドするには約 1 分かかります。構築中、インデックスは最初の同期状態になります。構築が完了したら、コレクション内のデータのクエリを開始できます。
ベクトル検索クエリの実行
MongoDB がインデックスを構築 したら、データに対してベクトル検索クエリを実行します。次の例は、ベクトル化されたデータに対して実行できるさまざまなクエリを示しています。
次のクエリは、 similarity_searchメソッドを使用して、string MongoDB acquisitionの基本的なセマンティック検索を実行します。 関連性順にランク付けされたドキュメントのリストが返されます。
query = "MongoDB acquisition"results = vector_store.similarity_search(query)
pprint.pprint(results)[Document(id='67f0259b8bb2babc06924409', metadata={ ... }, page_content='SOURCE MongoDB, Inc.'), Document(id='67f0259b8bb2babc0692432f', metadata={ ... }, page_content='MongoDB platform. In fiscal year 2026 we expect to see stable consumption growth in Atlas, our main growth driver," said Dev Ittycheria, President\nand Chief Executive Officer of MongoDB .'), Document(id='67f0259b8bb2babc06924355', metadata={ ... }, 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='67f0259b8bb2babc069243a6', metadata={ ... }, page_content="MongoDB's unified, intelligent data platform was built to power the next generation of applications, and MongoDB is the most widely available, globally")]次のクエリは、 similarity_search_with_scoreメソッドを使用して string MongoDB acquisitionのセマンティック検索を実行し、返されるドキュメント数を3に制限するためにkパラメーターを指定します。
注意
この例のkパラメータは、同名のknnBeta演算子オプションではなく、 similarity_search_with_scoreメソッド オプションを参照します。
最も関連性の高い 3 つのドキュメントと、0と1の間の関連性スコアが返されます。
query = "MongoDB acquisition"results = vector_store.similarity_search_with_score( query = query, k = 3)
pprint.pprint(results)[(Document(id='67f0259b8bb2babc06924409', metadata={ ... }, page_content='SOURCE MongoDB, Inc.'), 0.8193451166152954), (Document(id='67f0259b8bb2babc0692432f', metadata={ ... }, page_content='MongoDB platform. In fiscal year 2026 we expect to see stable consumption growth in Atlas, our main growth driver," said Dev Ittycheria, President\nand Chief Executive Officer of MongoDB .'), 0.7815237045288086), (Document(id='67f0259b8bb2babc06924355', metadata={ ... }, 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.'), 0.7788857221603394)]コレクション内の別の値とインデックス付きフィールドを比較する MQL 一致式を使用して、データを事前にフィルター処理できます。フィルターするメタデータフィールドはすべて、filter タイプとしてインデックスを付ける必要があります。学ぶには、「ベクトル検索のフィールドにインデックスを付ける方法」を参照してください。
次のクエリは、 similarity_search_with_scoreメソッドを使用して string MongoDB acquisitionのセマンティック検索を実行します。 また、次の項目も指定します。
返されるドキュメント数を
3に制限するkパラメーター。$eq演算子を使用して2ページにのみ表示されるドキュメントを照合するpage_labelフィールドの事前フィルタリング。
ページ2から最も関連性の高いドキュメント 3 つと、 0と1の間の関連性スコアが返されます。
query = "MongoDB acquisition"
results = vector_store.similarity_search_with_score( query = query, k = 3, pre_filter = { "page_label": { "$eq": 2 } })
pprint.pprint(results)[(Document(id='67f0259b8bb2babc06924355', metadata={ ... '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.'), 0.7788857221603394), (Document(id='67f0259b8bb2babc06924351', metadata={ ... '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'), 0.7606035470962524), (Document(id='67f0259b8bb2babc06924354', metadata={ ... 'page_label': '2'}, page_content='data.\nMongoDB completed the redemption of 2026 Convertible Notes, eliminating all debt from the balance sheet. Additionally, in'), 0.7583936452865601)]Tip
セマンティック検索メソッドの完全なリストについては、API参照を参照してください。
データに関する質問に答えます
このセクションでは、 MongoDB ベクトル検索と Lgachein を使用してアプリケーションに RG を実装する方法を説明します。MongoDB ベクトル検索 を使用してセマンティックに類似したドキュメントを検索したので、次のコード例を実行して、それらのドキュメントに基づいて質問に答えるように LM に指示します。
この例では、次の処理を行います。
これらのドキュメントをクエリのコンテキストとして使用するように LM に指示する Lgachein プロンプト テンプレート を定義します。LgChart はこれらのドキュメントを
{context}入力変数に渡し、クエリを{question}変数に渡します。次の内容を指定するチェーンを構築します。
コンテキストとして使用するドキュメントを検索するためのリージョンとしてのMongoDB ベクトル検索 。
定義した プロンプト テンプレート。
コンテキストに応じた応答を生成する OpenAI の
gpt-4oチャットモデル。
サンプル クエリを使用してチェーンを呼び出します。
LLMの応答とコンテキストとして使用されたドキュメントを返します。 生成される応答は異なる場合があります。
# Instantiate MongoDB Vector Search as a retrieverretriever = vector_store.as_retriever( search_type = "similarity", search_kwargs = { "k": 10 })
# Define a prompt templatetemplate = """ Use the following pieces of context to answer the question at the end. {context} Question: {question}"""prompt = PromptTemplate.from_template(template)model = ChatOpenAI(model="gpt-4o")
# Construct a chain to answer questions on your datachain = ( { "context": retriever, "question": RunnablePassthrough()} | prompt | model | StrOutputParser())
# Prompt the chainquestion = "What was MongoDB's latest acquisition?"answer = chain.invoke(question)
print("Question: " + question)print("Answer: " + answer)
# Return source documentsdocuments = retriever.invoke(question)print("\nSource documents:")pprint.pprint(documents)Question: What was MongoDB's latest acquisition?Answer: MongoDB's latest acquisition was Voyage AI, a pioneer in state-of-the-art embedding and reranking models.
Source documents:[Document(id='67f0259b8bb2babc06924409', metadata={'_id': '67f0259b8bb2babc06924409', ... 'page_label': '9'}, page_content='SOURCE MongoDB, Inc.'), Document(id='67f0259b8bb2babc06924351', metadata={'_id': '67f0259b8bb2babc06924351', ... '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='67f0259b8bb2babc0692432f', metadata={'_id': '67f0259b8bb2babc0692432f', ... 'page_label': '1'}, page_content='MongoDB platform. In fiscal year 2026 we expect to see stable consumption growth in Atlas, our main growth driver," said Dev Ittycheria, President\nand Chief Executive Officer of MongoDB .'), Document(id='67f0259b8bb2babc06924355', metadata={'_id': '67f0259b8bb2babc06924355', ... '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='67f0259b8bb2babc069243a6', metadata={'_id': '67f0259b8bb2babc069243a6', ... 'page_label': '4'}, page_content="MongoDB's unified, intelligent data platform was built to power the next generation of applications, and MongoDB is the most widely available, globally"), Document(id='67f0259b8bb2babc06924329', metadata={'_id': '67f0259b8bb2babc06924329', ... 'page_label': '1'}, page_content='MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results\nMarch 5, 2025\nFourth Quarter Fiscal 2025 Total Revenue of $548.4 million, up 20% Year-over-Year'), Document(id='67f0259b8bb2babc069243a7', metadata={'_id': '67f0259b8bb2babc069243a7', ... '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'), Document(id='67f0259b8bb2babc069243a5', metadata={'_id': '67f0259b8bb2babc069243a5', ... 'page_label': '4'}, page_content="Headquartered in New York, MongoDB's mission is to empower innovators to create, transform, and disrupt industries with software and data."), Document(id='67f0259b8bb2babc06924354', metadata={'_id': '67f0259b8bb2babc06924354', ... 'page_label': '2'}, page_content='data.\nMongoDB completed the redemption of 2026 Convertible Notes, eliminating all debt from the balance sheet. Additionally, in'), Document(id='67f0259b8bb2babc069243a9', metadata={'_id': '67f0259b8bb2babc069243a9', ... 'page_label': '4'}, page_content='50,000 customers across almost every industry—including 70% of the Fortune 100—rely on MongoDB for their most important applications. To learn\nmore, visit mongodb.com .\nInvestor Relations')]この例では、次の処理を行います。
次の任意パラメータを含む、類似したドキュメントを検索するための検索バーとしてMongoDB ベクトル検索 をインスタンス化します。
k最も関連性の高い10のみを検索するにはscore_threshold関連性スコアが0.75を超えるドキュメントのみを使用するようにします。注意
このパラメータは、LangChain が結果を正規化するために使用する関連度スコアを指します。MongoDB Search クエリで使用される 関連度スコア ではありません。あなたの RAG 実装で MongoDB Search スコアを使用するには、
similarity_search_with_scoreメソッドを使用し、MongoDB Search スコアでフィルターするカスタム リトリーバーを定義します。pre_filterページ2にのみ表示されるドキュメントをpage_labelフィールドでフィルタリングします。
これらのドキュメントをクエリのコンテキストとして使用するように LM に指示する Lgachein プロンプト テンプレート を定義します。LgChart はこれらのドキュメントを
{context}入力変数に渡し、クエリを{question}変数に渡します。次の内容を指定するチェーンを構築します。
コンテキストとして使用するドキュメントを検索するためのリージョンとしてのMongoDB ベクトル検索 。
定義した プロンプト テンプレート。
コンテキストに応じた応答を生成する OpenAI の
gpt-4oチャットモデル。
サンプル クエリを使用してチェーンを呼び出します。
LLMの応答とコンテキストとして使用されたドキュメントを返します。 生成される応答は異なる場合があります。
# Instantiate MongoDB Vector Search as a retrieverretriever = vector_store.as_retriever( search_type = "similarity", search_kwargs = { "k": 10, "score_threshold": 0.75, "pre_filter": { "page_label": { "$eq": 2 } } })
# Define a prompt templatetemplate = """ Use the following pieces of context to answer the question at the end. {context} Question: {question}"""prompt = PromptTemplate.from_template(template)model = ChatOpenAI(model="gpt-4o")
# Construct a chain to answer questions on your datachain = ( { "context": retriever, "question": RunnablePassthrough()} | prompt | model | StrOutputParser())
# Prompt the chainquestion = "What was MongoDB's latest acquisition?"
answer = rag_chain.invoke(question)
print("Question: " + question)print("Answer: " + answer)
# Return source documentsdocuments = retriever.invoke(question)print("\nSource documents:")pprint.pprint(documents)Question: What was MongoDB's latest acquisition?Answer: MongoDB's latest acquisition was Voyage AI, a pioneer in state-of-the-art embedding and reranking models.
Source documents:[Document(id='67f0259b8bb2babc06924351', metadata={'_id': '67f0259b8bb2babc06924351', ... '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='67f0259b8bb2babc06924355', metadata={'_id': '67f0259b8bb2babc06924355', ... '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='67f0259b8bb2babc06924354', metadata={'_id': '67f0259b8bb2babc06924354', ... 'page_label': '2'}, page_content='data.\nMongoDB completed the redemption of 2026 Convertible Notes, eliminating all debt from the balance sheet. Additionally, in'), Document(id='67f0259b8bb2babc06924358', metadata={'_id': '67f0259b8bb2babc06924358', ... 'page_label': '2'}, page_content='Lombard Odier, a Swiss private bank, partnered with MongoDB to migrate and modernize its legacy banking technology'), Document(id='67f0259b8bb2babc06924352', metadata={'_id': '67f0259b8bb2babc06924352', ... 'page_label': '2'}, page_content="AI applications. Integrating Voyage AI's technology with MongoDB will enable organizations to easily build trustworthy,"), Document(id='67f0259b8bb2babc0692435a', metadata={'_id': '67f0259b8bb2babc0692435a', ... 'page_label': '2'}, page_content='applications from a legacy relational database to MongoDB 20 times faster than previous migrations.\nFirst Quarter and Full Year Fiscal 2026 Guidance'), Document(id='67f0259b8bb2babc06924356', metadata={'_id': '67f0259b8bb2babc06924356', ... 'page_label': '2'}, page_content='For the third consecutive year, MongoDB was named a Leader in the 2024 Gartner® Magic Quadrant™ for Cloud'), Document(id='67f0259b8bb2babc0692434d', metadata={'_id': '67f0259b8bb2babc0692434d', ... 'page_label': '2'}, page_content='compared to $121.5 million of cash from operations in the year-ago period. MongoDB used $29.6 million of cash in capital'), Document(id='67f0259b8bb2babc0692434c', metadata={'_id': '67f0259b8bb2babc0692434c', ... 'page_label': '2'}, page_content='Cash Flow: During the year ended January 31, 2025, MongoDB generated $150.2 million of cash from operations,'), Document(id='67f0259b8bb2babc06924364', metadata={'_id': '67f0259b8bb2babc06924364', ... 'page_label': '2'}, page_content='MongoDB will host a conference call today, March 5, 2025, at 5:00 p.m. (Eastern Time) to discuss its financial results and business outlook. A live')]ビデオで学ぶ
このビデオチュートリアルで、LangChain と MongoDB を使用したセマンティック検索および RAG について詳しく学べます。
所要時間: 8分