LangChain 統合を使用して親ドキュメントを取得する
Atlas Vector Search を LangChain と統合して、親ドキュメントの取得を実行できます。このチュートリアルでは、以下の手順を完了します:
環境を設定します。
データを準備してください。
親ドキュメントリトリーバーをインスタンス化します。
Atlas Vector Search インデックスを作成します。
RAG パイプラインでレトリーバーを使用します。
このチュートリアルの実行可能なバージョンを Python のエディタ として作業してください。
バックグラウンド
親ドキュメントの取得は、大きなドキュメントを小さなチャンクに分割する取得手法です。この手法では、親ドキュメント全体を LLM に返す前に、小さいチャンクをクエリします。これにより、LLM に親文書の完全なコンテキストを提供しながら、より小さなチャンクでより詳細な検索が可能になるため、RAG エージェントとアプリケーションの応答を向上させることができます。
MongoDB で親ドキュメントを取得すると、親ドキュメントと子ドキュメントの両方を 1 つのコレクションに保存できるため、子ドキュメントの埋め込みを計算してインデックスだけで効率的な取得が可能になります。
前提条件
Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。
Atlas アカウントで、クラスターが MongoDB バージョン 6.0.11、または7.0.2 以降(RCs を含む)のクラスターを実行している。IP アドレスが Atlas プロジェクトの アクセスリストに含まれていることを確認してください。詳細については、クラスターの作成を参照してください。
OpenAI API キー。API リクエストに使用できるクレジットを持つ OpenAI アカウントが必要です。OpenAI アカウントの登録について詳しく知りたい場合は、 OpenAI API ウェブサイトをご覧ください。
Comb などのインタラクティブ Python ノートを実行するための環境。
環境を設定する
このチュートリアルの環境を設定します。 .ipynb
拡張子を持つファイルを保存して、インタラクティブPythonノートを作成します。 このノートはPythonコード スニペットを個別に実行でき、このチュートリアルのコードを実行するために使用します。
ノートク環境を設定するには、次の手順に従います。
環境変数を定義します。
次のコードを実行し、プレースホルダーを次の値に置き換えます。
OpenAI API キー。
Atlas クラスターのSRV接続文字列。
import os os.environ["OPENAI_API_KEY"] = "<api-key>" ATLAS_CONNECTION_STRING = "<connection-string>"
注意
接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
データの準備
ノートブックに次のコードを貼り付けて実行し、最新の MongoDB の収益レポートを含むサンプル PDF を読み込み、チャンクします。
このコードは、テキストスプリッターを使用して、PDFデータを小さな親ドキュメントに分割します。各ドキュメントのチャンクサイズ(文字数)とチャンクオーバーラップ(連続するチャンク間で重なる文字数)を指定します。
from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.document_loaders import PyPDFLoader # Load the PDF loader = PyPDFLoader("https://investors.mongodb.com/node/12881/pdf") data = loader.load() # Chunk into parent documents parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=20) docs = parent_splitter.split_documents(data) # Print a document docs[0]
Document(metadata={'source': 'https://investors.mongodb.com/node/12881/pdf', 'page': 0, 'page_label': '1'}, page_content='MongoDB, Inc. Announces Third Quarter Fiscal 2025 Financial Results\nDecember 9, 2024\nThird Quarter Fiscal 2025 Total Revenue of $529.4 million, up 22% Year-over-Year\nContinued Strong Customer Growth with Over 52,600 Customers as of October 31, 2024\nMongoDB Atlas Revenue up 26% Year-over-Year; 68% of Total Q3 Revenue\nNEW YORK , Dec. 9, 2024 /PRNewswire/ -- MongoDB, Inc. (NASDAQ: MDB) today announced its financial results for the third quarter ended October\n31, 2024.\n\xa0\n \xa0\n"MongoDB\'s third quarter results were significantly ahead of expectations on the top and bottom line, driven by better-than-expected EA performance\nand 26% Atlas revenue growth.\xa0 We continue to see success winning new business due to the superiority of MongoDB\'s developer data platform in\naddressing a wide variety of mission-critical use cases," said Dev Ittycheria, President and Chief Executive Officer of MongoDB .\n"We continue to invest in our legacy app modernization and AI offerings as our document model and distributed architecture are exceptionally well\nsuited for customers looking to build highly-performant, modern applications.\xa0 MongoDB is in a great position to be a central pillar of the emerging AI\ntech stack and benefit from the next wave of application development in the years ahead."\nThird Quarter Fiscal 2025 Financial Highlights\nRevenue: Total revenue was $529.4 million for the third quarter of fiscal 2025, an increase of 22% year-over-year.\nSubscription revenue was $512.2 million, an increase of 22% year-over-year, and services revenue was $17.2 million, an\nincrease of 18% year-over-year.\nGross Profit: Gross profit was $394.0 million for the third quarter of fiscal 2025, representing a 74% gross margin\ncompared to 75% in the year-ago period. Non-GAAP gross profit was $405.7 million, representing a 77% non-GAAP gross\nmargin, consistent with a non-GAAP gross margin of 77% in the year-ago period.')
レトリーバーのインスタンス化
このセクションでは、親ドキュメントのレトリーバーをインスタンス化し、それを使用して Atlas にデータを取り込みます。
MongoDBAtlasParentDocumentRetriever
親ドキュメントを小さな子ドキュメントにチャンクし、子ドキュメントを埋め込み、親ドキュメントと子ドキュメントの両方を Atlas の同じコレクションに取り込みます。内部的には、このレトリーバーは以下を作成します。
子ドキュメントへのベクトル検索クエリを処理するベクトル ストアである
MongoDBAtlasVectorSearch
のインスタンス。親ドキュメントの保存と取得を処理するドキュメント ストアである
MongoDBDocStore
のインスタンス。
レトリーバーをインスタンス化します。
MongoDBAtlasParentDocumentRetriever
を構成する最も速い方法は、from_connection_string
メソッドを使用することです。このコードは、次のパラメーターを指定します。
connection_string
: クラスターに接続するための Atlas 接続文字列。child_splitter
: 親ドキュメントを小さな子ドキュメントに分割するために使用するテキストスプリッター。embedding_model
: 子ドキュメントを埋め込むために使用する埋め込みモデル。database_name
およびcollection_name
: ドキュメントを取り込むためのデータベースおよびコレクション名。MongoDBAtlasVectorSearch
ベクトルストアを構成するための、次の任意のパラメーター。text_key
: 埋め込むテキストを含むドキュメント内のフィールドrelevance_score
: ベクトル検索クエリに使用する関連性スコアsearch_kwargs
: 最初の検索で取得する子ドキュメントの数
from langchain_mongodb.retrievers import MongoDBAtlasParentDocumentRetriever from langchain_openai import OpenAIEmbeddings # Define the embedding model to use embedding_model = OpenAIEmbeddings(model="text-embedding-3-small") # Define the chunking method for the child documents child_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20) # Specify the database and collection name database_name = "langchain_db" collection_name = "parent_document" # Create the parent document retriever parent_doc_retriever = MongoDBAtlasParentDocumentRetriever.from_connection_string( connection_string = ATLAS_CONNECTION_STRING, child_splitter = child_splitter, embedding_model = embedding_model, database_name = database_name, collection_name = collection_name, text_key = "page_content", relevance_score_fn = "dotProduct", search_kwargs = { "k": 10 }, )
(任意)ドキュメントを確認します。
サンプルコードを実行した後、クラスターの langchain_db.parent_document
コレクションに移動すると、Atlas UI でドキュメントを表示できます。
親ドキュメントと子ドキュメントの両方に page_content
フィールドがあり、チャンクされたテキストが入っています。子ドキュメントには、チャンクされたテキストのベクトル埋め込みが入った追加の embedding
フィールドと、親ドキュメントの _id
に対応する doc_id
フィールドがあります。
Atlas UI で次のクエリを実行し、<id>
プレースホルダーを有効なドキュメント ID に置き換えます。
同じ親ドキュメントIDを共有する子ドキュメントを表示するには、次のように行います。
{ doc_id: "<id>" } それらの子ドキュメントの親ドキュメントを表示するには、以下の手順に従ってください。
{ _id: "<id>" }
Atlas Vector Search インデックスの作成
注意
Atlas Vector Search インデックスを作成するには、Atlas プロジェクトに対するProject Data Access Admin
以上のアクセス権が必要です。
langchain_db.parent_document
コレクションでベクトル検索クエリを有効にするには、Atlas Vector Search インデックスを作成する必要があります。LangChain ヘルパー メソッドまたは PyMongo ドライバー メソッドのいずれかを使用できます。ノートブックで次のコードを、お好みの方法で実行します。
# Get the vector store instance from the retriever vector_store = parent_doc_retriever.vectorstore # Use helper method to create the vector search index vector_store.create_vector_search_index( dimensions = 1536 # The dimensions of the vector embeddings to be indexed )
from pymongo import MongoClient from pymongo.operations import SearchIndexModel # Connect to your cluster client = MongoClient(ATLAS_CONNECTION_STRING) collection = client[database_name][collection_name] # Create your vector search index model, then create the index vector_index_model = SearchIndexModel( definition={ "fields": [ { "type": "vector", "path": "embedding", "numDimensions": 1536, "similarity": "dotProduct" } ] }, name="vector_index", type="vectorSearch" ) collection.create_search_index(model=vector_index_model)
インデックスの構築には約 1 分かかります。 構築中、インデックスは最初の同期状態になります。 構築が完了したら、コレクション内のデータのクエリを開始できます。
RAG パイプラインでのレトリーバーの使用
Atlas がインデックスをビルドした後、データに対して検索クエリを実行し、RAG パイプラインでリトリーバーを使用できます。以下のコードをノートブックに貼り付けて実行し、親ドキュメントの検索を行うサンプル RAG パイプラインを実装します:
ベクトル検索クエリを実行する。
特定のクエリに最も関連性の高いドキュメントを表示するには、次のコードを貼り付けて実行し、コレクションでサンプルベクトル検索クエリを実行します。レトリーバーは、文字列 AI technology
に意味的に類似した関連する子ドキュメントを検索し、その子ドキュメントに対応する親ドキュメントを返します。
parent_doc_retriever.invoke("AI technology")
[Document(metadata={'_id': '492a138c-1309-4791-a0d0-282d34ea1e55', 'source': 'https://investors.mongodb.com/node/12881/pdf', 'page': 1, 'page_label': '2'}, page_content='downturns and/or the effects of rising interest rates, inflation and volatility in the global economy and financial markets on our business and future\noperating results; our potential failure to meet publicly announced guidance or other expectations about our business and future operating results; our\nlimited operating history; our history of losses; failure of our platform to satisfy customer demands; the effects of increased competition; our\ninvestments in new products and our ability to introduce new features, services or enhancements; our ability to effectively expand our sales and\nmarketing organization; our ability to continue to build and maintain credibility with the developer community; our ability to add new customers or\nincrease sales to our existing customers; our ability to maintain, protect, enforce and enhance our intellectual property; the effects of social, ethical and\nregulatory issues relating to the use of new and evolving technologies, such as artificial intelligence, in our offerings or partnerships; the growth and\nexpansion of the market for database products and our ability to penetrate that market; our ability to integrate acquired businesses and technologies\nsuccessfully or achieve the expected benefits of such acquisitions; our ability to maintain the security of our software and adequately address privacy\nconcerns; our ability to manage our growth effectively and successfully recruit and retain additional highly-qualified personnel; and the price volatility of'), Document(metadata={'_id': 'a937204a-0e85-4827-ac63-124735529d51', 'source': 'https://investors.mongodb.com/node/12881/pdf', 'page': 1, 'page_label': '2'}, page_content='that it obtained the AWS Modernization Competency designation and launched a MongoDB University course focused on\nbuilding AI applications with MongoDB and AWS. At Microsoft Ignite, MongoDB announced new technology integrations for\nAI, data analytics, and automating database deployments across on-premises, cloud, and edge environments.\nLaunched in July 2024, the MongoDB AI Applications Program (MAAP) is designed to help companies unleash the power\nof their data and to take advantage of rapidly advancing AI technologies. We recently announced that Capgemini,\nConfluent, IBM, Unstructured, and QuantumBlack, AI by McKinsey have joined the MAAP ecosystem, offering customers\nadditional integration and solution options.\nExecutive Leadership Update\nMichael Gordon, MongoDB\'s Chief Operating Officer and Chief Financial Officer, will be stepping down at the end of the Company\'s fiscal year on\nJanuary 31, 2025, and afterwards will serve as an advisor to ensure a smooth transition. The Company has commenced an executive search process\nfor a new CFO and will evaluate internal and external candidates.\xa0 Serge Tanjga, MongoDB\'s Senior Vice President of Finance, will serve as interim\nCFO starting February 1st if a permanent successor has not been named by that date.\nDev Ittycheria commented, "On behalf of everyone at MongoDB , I want to thank Michael for everything he has done to contribute to our success in his\nnearly 10 years with the company.\xa0 In Michael\'s time here, MongoDB had a successful IPO, has grown revenue nearly 50x and has successfully\nscaled the business model to generate meaningful operating leverage. Michael has also built out a world-class finance team that I am confident will\ndeliver a smooth transition to a new CFO in the coming months."\nMichael Gordon said, "I am incredibly proud of what we have accomplished as a team in my almost ten years with the company.\xa0 While we have')]
LangChain を使用したベクトル検索クエリの例について詳しくは、「ベクトル検索クエリの実行」を参照してください。
RAG パイプラインを作成して実行する。
親ドキュメントのレトリーバーを使用してRAGパイプラインを作成し実行するには、次のコードを貼り付けて実行してください。このコードは、次の処理を行います。
LangChain プロンプト テンプレートを定義し、検索された親ドキュメントをクエリのコンテキストとして使用するように LLM に指示します。LangChart はこれらのドキュメントを
{context}
入力変数に渡し、クエリを{query}
変数に渡します。連鎖 を構築します は、以下を指定します。
関連する親ドキュメントを検索するために構成した親ドキュメントのレトリーバー。
定義した プロンプト テンプレート。
コンテキストを認識する応答を生成するための OpenAI による LM。デフォルトでは 、これは
gpt-3.5-turbo
モデルです。
サンプルクエリでチェーンをプロンプし、応答を返します。 生成される応答は異なる場合があります。
from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import PromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI # Define a prompt template template = """ Use the following pieces of context to answer the question at the end. {context} Question: {query}? """ prompt = PromptTemplate.from_template(template) model = ChatOpenAI() # Construct a chain to answer questions on your data chain = ( {"context": parent_doc_retriever, "query": RunnablePassthrough()} | prompt | model | StrOutputParser() ) # Prompt the chain query = "In a list, what are MongoDB's latest AI announcements?" answer = chain.invoke(query) print(answer)
1. MongoDB obtained the AWS Modernization Competency designation. 2. MongoDB launched a MongoDB University course focused on building AI applications with MongoDB and AWS. 3. MongoDB announced new technology integrations for AI, data analytics, and automating database deployments across various environments. 4. MongoDB launched the MongoDB AI Applications Program (MAAP) to help companies harness the power of data and future AI technologies. 5. Capgemini, Confluent, IBM, Unstructured, and QuantumBlack joined the MAAP ecosystem to offer customers additional integration and solution options.