注意
このチュートリアルでは、Lgachein の JavaScriptライブラリ を使用します。Pythonライブラリを使用するチュートリアルについては、 LangChain Python を参照してください。
MongoDB ベクトル検索 をLgChuin と統合して、LM アプリケーションを構築し、検索拡張生成 (RAG)(RAG)を実装できます。このチュートリアルでは、Lgachein とMongoDB ベクトル検索の使用を開始し、データのセマンティック検索を実行し、 RAG実装を構築する方法を説明します。具体的には、次のアクションを実行します。
環境を設定します。
カスタム データをMongoDBに保存します。
データにMongoDB ベクトル検索インデックスを作成します。
次のベクトル検索クエリを実行します。
セマンティック検索。
メタデータの事前フィルタリングによるセマンティック検索。
最大マージナル関連性(MMR)検索。
MongoDB ベクトル検索を使用してデータの質問に答え、RAG を実装します。
バックグラウンド
LgChuin は、「チェーン」の使用を通じて LVM アプリケーションの作成を簡素化するオープンソースのフレームワークです。 チェーンは 、RAG を含むさまざまなAIユースケースで組み合わせることができる Lgachein 固有のコンポーネントです。
MongoDB ベクトル検索 をLgachein と統合することで、 MongoDB をベクトルデータベースとして使用し、 MongoDB ベクトル検索を使用してセマンティックで類似したドキュメントを検索して RG を実装することができます。RG の詳細については、 MongoDBによる検索拡張生成(RAG) を参照してください。
前提条件
Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。
次のいずれかのMongoDBクラスター タイプ
MongoDB バージョン 6.0.11、7.0.2、またはそれ以降を実行している Atlas クラスター。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認する。
Atlas CLI を使用して作成されたローカル Atlas 配置。詳細については、「Atlas 配置のローカル配置の作成」を参照してください。
Search とベクトル検索がインストールされたMongoDB Community または Enterprise クラスター。
投票AI APIキー。アカウントとAPIキーを作成するには、Vyage AI のウェブサイト を参照してください。
OpenAI APIキー。APIリクエストに使用できるクレジットを持つ OpenAI アカウントが必要です。OpenAI アカウントの登録の詳細については、OpenAI APIウェブサイト を参照してください。
Node.js プロジェクトを実行するためのターミナルとコード エディター。
npmとNode.jsがインストールされました。
環境を設定する
このチュートリアルの環境を設定します。 環境を設定するには、次の手順を実行します。
package.json ファイルを更新します。
ES モジュール を使用するようにプロジェクトを構成するには、"type": "module" を package.jsonファイルに追加して保存します。
{ "type": "module", // other fields... }
get-started.js というファイルを作成し、次のコードを貼り付けます。
プロジェクトで、 get-started.jsという名前のファイルを作成し、次のコードをコピーしてファイルに貼り付けます。 チュートリアル全体でこのファイルにコードを追加します。
この最初のコード スニペットは、このチュートリアルに必要なパッケージをインポートし、環境変数を定義して、 MongoDBクラスターへの接続を確立します。
import { formatDocumentsAsString } from "langchain/util/document"; import { MongoClient } from "mongodb"; import { MongoDBAtlasVectorSearch } from "@langchain/mongodb"; import { ChatOpenAI } from "@langchain/openai"; import { VoyageEmbeddings } from "@langchain/community/embeddings/voyage"; import { PDFLoader } from "@langchain/community/document_loaders/fs/pdf"; import { PromptTemplate } from "@langchain/core/prompts"; import { RecursiveCharacterTextSplitter } from "langchain/text_splitter"; import { RunnableSequence, RunnablePassthrough } from "@langchain/core/runnables"; import { StringOutputParser } from "@langchain/core/output_parsers"; import * as fs from 'fs'; process.env.VOYAGEAI_API_KEY = "<api-key>" process.env.OPENAI_API_KEY = "<api-key>"; process.env.MONGODB_URI = "<connection-string>"; const client = new MongoClient(process.env.MONGODB_URI);
プレースホルダー値を置き換えます。
環境の設定を完了するには、get-started.js の <api-key> と <connection-string> のプレースホルダー値をそれぞれ、Vyage AI APIキー、OpenAI APIキー、MongoDBクラスターの SRV 接続文字列 に置き換えます。接続文字列には、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
MongoDB をベクトル ストアとして使用
このセクションでは、カスタム データをMongoDBにロードし、 MongoDBクラスターをベクトルデータベースとしてインスタンス化するための非同期関数を定義します。これはベクトルストアとも呼ばれます。次のコードを get-started.jsファイルに追加します。
注意
このチュートリアルでは、ベクトルストアのデータソースとして、MongoDB Atlasベストプラクティスというタイトルの一般にアクセス可能な PDFドキュメントを使用します。このドキュメントでは、 MongoDB配置を管理するためのさまざまな推奨事項と主要概念について説明します。
このコードは、次のアクションを実行します。
次のパラメータを指定してMongoDBコレクションを構成します。
langchain_db.testドキュメントを保存するMongoDBコレクションとして 。vector_indexベクトル ストアをクエリするために使用するインデックスとして 。text未加工のテキスト コンテンツを含むフィールドの名前:embeddingベクトル埋め込みを含むフィールドの名前として。
カスタム データを準備するには、次の手順を実行します。
指定された URL から未加工データを検索し、 PDF として保存します。
テキストスプリット を使用して、データを小さなドキュメントに分裂。
各ドキュメントの文字数と連続する 2 つのドキュメント間で重複する文字数を決定する チャンク パラメータを指定します。
MongoDBAtlasVectorSearch.fromDocumentsメソッドを呼び出して、サンプル ドキュメントからベクトル ストアを作成します。 このメソッドでは、次のパラメーターを指定します。ベクトルデータベースに保存する サンプル ドキュメント 。
embeddingフィールドのベクトル埋め込みにテキストを変換するために使用されるモデルとして、AI の埋め込みモデルを使用します。MongoDBクラスターの構成。
async function run() { try { // Configure your MongoDB collection const database = client.db("langchain_db"); const collection = database.collection("test"); const dbConfig = { collection: collection, indexName: "vector_index", // The name of the MongoDB Search index to use. textKey: "text", // Field name for the raw text content. Defaults to "text". embeddingKey: "embedding", // Field name for the vector embeddings. Defaults to "embedding". }; // Ensure that the collection is empty const count = await collection.countDocuments(); if (count > 0) { await collection.deleteMany({}); } // Save online PDF as a file const rawData = await fetch("https://webassets.mongodb.com/MongoDB_Best_Practices_Guide.pdf"); const pdfBuffer = await rawData.arrayBuffer(); const pdfData = Buffer.from(pdfBuffer); fs.writeFileSync("atlas_best_practices.pdf", pdfData); // Load and split the sample data const loader = new PDFLoader(`atlas_best_practices.pdf`); const data = await loader.load(); const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 200, chunkOverlap: 20, }); const docs = await textSplitter.splitDocuments(data); // Instantiate MongoDB as a vector store const embeddingModel = new VoyageEmbeddings({ model: "voyage-3-large" }); const vectorStore = await MongoDBAtlasVectorSearch.fromDocuments(docs, embeddingModel, dbConfig); } finally { // Ensure that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
ファイルを保存し、次のコマンドを実行してデータをMongoDBにロードします。
node get-started.js
Tip
get-started.jsAtlas を使用している場合は、langchain_db.test の実行中後、Atlas UIで 名前空間に移動することでベクトル埋め込みを検証できます。
MongoDB ベクトル検索インデックスの作成
ベクトルストアでベクトル検索クエリを有効にするには、langchain_db.testコレクションにMongoDB ベクトル検索インデックスを作成します。
get-started.js ファイルで定義された非同期関数に次のコードを追加してください。このコードは、次のフィールドをインデックスする vectorSearch タイプのインデックスを作成します。
embeddingベクトル型としてのフィールド。embeddingフィールドには、Voyage AI のvoyage-3-large埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、1024ベクトル次元を指定し、cosineを使用して類似性を測定します。loc.pageNumberPDF 内のページ番号でデータを事前にフィルタリングするためのフィルタータイプとしての フィールド。
このコードではまた、 await 関数を使用して、検索インデックスが使用される前にデータが に同期されていることを確認します。
1 // Ensure index does not already exist, then create your MongoDB Vector Search index 2 const indexes = await collection.listSearchIndexes("vector_index").toArray(); 3 if(indexes.length === 0){ 4 5 // Define your MongoDB Vector Search Index 6 const index = { 7 name: "vector_index", 8 type: "vectorSearch", 9 definition: { 10 "fields": [ 11 { 12 "type": "vector", 13 "numDimensions": 1024, 14 "path": "embedding", 15 "similarity": "cosine" 16 }, 17 { 18 "type": "filter", 19 "path": "loc.pageNumber" 20 } 21 ] 22 } 23 } 24 25 // Run the helper method 26 const result = await collection.createSearchIndex(index); 27 console.log(result); 28 29 // Wait for index to build and become queryable 30 console.log("Waiting for initial sync..."); 31 await new Promise(resolve => setTimeout(() => { 32 resolve(); 33 }, 10000)); 34 }
ファイルを保存し、次のコマンドを実行してMongoDB ベクトル検索インデックスを作成します。
node get-started.js
ベクトル検索クエリの実行
このセクションでは、ベクトル化されたデータに対して実行できるさまざまなクエリを示します。 インデックスが作成できたら、非同期関数に次のコードを追加して、データに対してベクトル検索クエリを実行します。
注意
データをクエリするときに不正確な結果が発生した場合、インデックスの同期に予想以上に時間がかかることがあります。 最初の同期の時間を長くするには、 setTimeout関数の の数を増やします。
次のコードを非同期関数に追加し、ファイルを保存します。
次のコードでは、 similaritySearchメソッドを使用して、string MongoDB Atlas securityの基本的なセマンティック検索を実行します。 pageContentpageNumberフィールドと フィールドのみを持つドキュメントの関連性順のリストが返されます。
// Basic semantic search const basicOutput = await vectorStore.similaritySearch("MongoDB Atlas security"); const basicResults = basicOutput.map((results => ({ pageContent: results.pageContent, pageNumber: results.metadata.loc.pageNumber, }))) console.log("Semantic Search Results:") console.log(basicResults)
以下のコマンドを実行してクエリを実行します。
node get-started.js
Semantic Search Results: [ { pageContent: 'Atlas free tier, or download MongoDB for local \n' + 'development.\n' + 'Review the MongoDB manuals and tutorials in our \n' + 'documentation. \n' + 'More Resources\n' + 'For more on getting started in MongoDB:', pageNumber: 30 }, { pageContent: 'read isolation. \n' + 'With MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \n' + 'tools like Atlas Charts can be configured to read from analytics nodes only.', pageNumber: 21 }, { pageContent: '• Zoned Sharding — You can define specific rules governing data placement in a sharded cluster.\n' + 'Global Clusters in MongoDB Atlas allows you to quickly implement zoned sharding using a visual UI or', pageNumber: 27 }, { pageContent: 'are updated, associated indexes must be maintained, incurring additional CPU and disk I/O overhead. \n' + 'If you\'re running fully managed databases on MongoDB Atlas, the built-in Performance Advisor', pageNumber: 20 } ]
コレクション内の別の値とインデックス付きフィールドを比較する MQL 一致式を使用して、データを事前にフィルタリングできます。フィルタリングするメタデータフィールドはすべて、filter タイプとしてインデックスを作成する必要があります。詳細については、「ベクトル検索のフィールドにインデックスを付ける方法」を参照してください。
注意
このチュートリアルのインデックスを作成したときに、 loc.pageNumberフィールドをフィルターとして指定しました。
次のコードを非同期関数に追加し、ファイルを保存します。
次のコードでは、 similaritySearchメソッドを使用して string MongoDB Atlas securityのセマンティック検索を実行します。 次のパラメータを指定します。
3として返すドキュメントの数。$eq演算子を使用して17ページにのみ表示されるドキュメントを照合するloc.pageNumberフィールドの事前フィルタリング。
pageContentpageNumberフィールドと フィールドのみを持つドキュメントの関連性順のリストが返されます。
// Semantic search with metadata filter const filteredOutput = await vectorStore.similaritySearch("MongoDB Atlas Search", 3, { preFilter: { "loc.pageNumber": {"$eq": 22 }, } }); const filteredResults = filteredOutput.map((results => ({ pageContent: results.pageContent, pageNumber: results.metadata.loc.pageNumber, }))) console.log("Semantic Search with Filtering Results:") console.log(filteredResults)
以下のコマンドを実行してクエリを実行します。
node get-started.js
Semantic Search with Filtering Results: [ { pageContent: 'Atlas Search is built for the MongoDB document data model and provides higher performance and', pageNumber: 22 }, { pageContent: 'Figure 9: Atlas Search queries are expressed through the MongoDB Query API and backed by the leading search engine library, \n' + 'Apache Lucene.', pageNumber: 22 }, { pageContent: 'consider using Atlas Search. The service is built on fully managed Apache Lucene but exposed to users \n' + 'through the MongoDB Aggregation Framework.', pageNumber: 22 } ]
ダイバーティッドに最適化されたセマンティック関連性の測定値であるMMR(Max MongoDB Atlas)に基づいて、セマンティック検索を実行することもできます。
次のコードを非同期関数に追加し、ファイルを保存します。
次のコードでは、 maxMarginalRelevanceSearchメソッドを使用して string MongoDB Atlas securityを検索します。 また、次の任意パラメータを定義するオブジェクトも指定します。
k返されたドキュメントの数を3に制限します。fetchKドキュメントをMDRアルゴリズムに渡す前に、10ドキュメントのみを取得します。
pageContentpageNumberフィールドと フィールドのみを持つドキュメントの関連性順のリストが返されます。
// Max Marginal Relevance search const mmrOutput = await vectorStore.maxMarginalRelevanceSearch("MongoDB Atlas security", { k: 3, fetchK: 10, }); const mmrResults = mmrOutput.map((results => ({ pageContent: results.pageContent, pageNumber: results.metadata.loc.pageNumber, }))) console.log("Max Marginal Relevance Search Results:") console.log(mmrResults)
以下のコマンドを実行してクエリを実行します。
node get-started.js
Max Marginal Relevance Search Results: [ { pageContent: 'Atlas Search is built for the MongoDB document data model and provides higher performance and', pageNumber: 22 }, { pageContent: '• Zoned Sharding — You can define specific rules governing data placement in a sharded cluster.\n' + 'Global Clusters in MongoDB Atlas allows you to quickly implement zoned sharding using a visual UI or', pageNumber: 27 }, { pageContent: 'read isolation. \n' + 'With MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \n' + 'tools like Atlas Charts can be configured to read from analytics nodes only.', pageNumber: 21 } ]
Tip
詳しくは、API参照を参照してください。
データに関する質問に答えます
このセクションでは、 RAG MongoDB ベクトル検索と Lgachein を使用した 2 つの異なる RG 実装を示します。MongoDB ベクトル検索を使用してセマンティックに類似したドキュメントを検索したので、次のコード例を使用して、 MongoDB ベクトル検索によって返されたドキュメントに対して LM に質問に回答するように要求します。
次のコードを非同期関数に追加し、ファイルを保存します。
このコードでは、次の処理が行われます。
MongoDB ベクトル検索 を、セマンティクスで類似したドキュメントを検索するための検索バーとしてインスタンス化します。
これらのドキュメントをクエリのコンテキストとして使用するように LM に指示する Lgachein プロンプト テンプレート を定義します。LgChart はこれらのドキュメントを
{context}入力変数に渡し、クエリを{question}変数に渡します。OpenAI のチャットモデルを使用して、プロンプトに基づいてコンテキストを認識する応答を生成するチェーンを構築します。
Atlas のセキュリティ推奨事項に関するサンプル クエリでチェーンをプロンプトします。
LLMの応答とコンテキストとして使用されたドキュメントを返します。
// Implement RAG to answer questions on your data const retriever = vectorStore.asRetriever(); const prompt = PromptTemplate.fromTemplate(`Answer the question based on the following context: {context} Question: {question}`); const model = new ChatOpenAI({}); const chain = RunnableSequence.from([ { context: retriever.pipe(formatDocumentsAsString), question: new RunnablePassthrough(), }, prompt, model, new StringOutputParser(), ]); // Prompt the LLM const question = "How can I secure my MongoDB Atlas cluster?"; const answer = await chain.invoke(question); console.log("Question: " + question); console.log("Answer: " + answer); // Return source documents const retrievedResults = await retriever.getRelevantDocuments(question) const documents = retrievedResults.map((documents => ({ pageContent: documents.pageContent, pageNumber: documents.metadata.loc.pageNumber, }))) console.log("\nSource documents:\n" + JSON.stringify(documents, 1, 2))
次のコマンドを実行して、ファイルを実行します。
ファイルを保存した後、次のコマンドを実行します。 生成される応答は異なる場合があります。
node get-started.js
Question: How can I secure my MongoDB Atlas cluster? Answer: The given context does not explicitly provide detailed steps to secure a MongoDB Atlas cluster. However, based on general best practices, here are some common steps to secure your MongoDB Atlas cluster: 1. **Enable Network Access Controls**: Configure IP whitelists to only allow connections from trusted IP addresses. 2. **Use Strong Authentication and Authorization**: Enable SCRAM (Salted Challenge Response Authentication Mechanism) for authenticating users and define roles with specific permissions. 3. **Encrypt Data**: Ensure data is encrypted both at rest and in transit by default in MongoDB Atlas. 4. **Enable VPC Peering (if applicable)**: Use Virtual Private Cloud (VPC) peering for secure and private connections. 5. **Monitor Activity**: Use MongoDB Atlas's built-in monitoring to track cluster activity and detect unauthorized attempts or anomalies. 6. **Implement Automated Backups**: Secure backups and ensure they are protected from unauthorized access. 7. **Educate Yourself**: Continuously refer to the MongoDB documentation and follow security best practices. It is recommended to visit the MongoDB documentation and security guides for the most accurate and detailed steps tailored to your specific use case. Source documents: [ { "pageContent": "Atlas free tier, or download MongoDB for local \ndevelopment.\nReview the MongoDB manuals and tutorials in our \ndocumentation. \nMore Resources\nFor more on getting started in MongoDB:", "pageNumber": 30 }, { "pageContent": "read isolation. \nWith MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \ntools like Atlas Charts can be configured to read from analytics nodes only.", "pageNumber": 21 }, { "pageContent": "• Zoned Sharding — You can define specific rules governing data placement in a sharded cluster.\nGlobal Clusters in MongoDB Atlas allows you to quickly implement zoned sharding using a visual UI or", "pageNumber": 27 }, { "pageContent": "22\nWorkload Type: Search\nIf your application requires rich full-text search functionality and you are running MongoDB on Atlas,", "pageNumber": 22 } ]
次のコードを非同期関数に追加し、ファイルを保存します。
このコードでは、次の処理が行われます。
MongoDB ベクトル検索 を、セマンティクスで類似したドキュメントを検索するための検索バーとしてインスタンス化します。次の任意パラメーターも指定します。
searchTypeはmmrとして、 MongoDB ベクトル検索 が最大マージナル関連性(MMR)に基づいてドキュメントを検索することを指定します。filterをクリックして、log.pageNumbersフィールドに事前フィルターを追加して、 17ページのみに表示されるドキュメントを含めます。次のMDR固有のパラメーター。
fetchKドキュメントをMDRアルゴリズムに渡す前に、20ドキュメントのみを取得します。lambda、結果間の相違の度数を決定するための0と1の間の値。0は最大の相違を表し、1は最小の相違を表します。
これらのドキュメントをクエリのコンテキストとして使用するように LM に指示する Lgachein プロンプト テンプレート を定義します。LgChart はこれらのドキュメントを
{context}入力変数に渡し、クエリを{question}変数に渡します。OpenAI のチャットモデルを使用して、プロンプトに基づいてコンテキストを認識する応答を生成するチェーンを構築します。
Atlas のセキュリティ推奨事項に関するサンプル クエリでチェーンをプロンプトします。
LLMの応答とコンテキストとして使用されたドキュメントを返します。
// Implement RAG to answer questions on your data const retriever = await vectorStore.asRetriever({ searchType: "mmr", // Defaults to "similarity filter: { preFilter: { "loc.pageNumber": { "$eq": 17 } } }, searchKwargs: { fetchK: 20, lambda: 0.1, }, }); const prompt = PromptTemplate.fromTemplate(`Answer the question based on the following context: {context} Question: {question}`); const model = new ChatOpenAI({}); const chain = RunnableSequence.from([ { context: retriever.pipe(formatDocumentsAsString), question: new RunnablePassthrough(), }, prompt, model, new StringOutputParser(), ]); // Prompt the LLM const question = "How can I secure my MongoDB Atlas cluster?"; const answer = await chain.invoke(question); console.log("Question: " + question); console.log("Answer: " + answer); // Return source documents const retrievedResults = await retriever.getRelevantDocuments(question) const documents = retrievedResults.map((documents => ({ pageContent: documents.pageContent, pageNumber: documents.metadata.loc.pageNumber, }))) console.log("\nSource documents:\n" + JSON.stringify(documents, 1, 2))
次のコマンドを実行して、ファイルを実行します。
ファイルを保存した後、次のコマンドを実行します。 生成される応答は異なる場合があります。
node get-started.js
Question: How can I secure my MongoDB Atlas cluster? Answer: To secure your MongoDB Atlas cluster, you can implement the following best practices: 1. **Enable Authentication and Authorization** Ensure that authentication is enabled, which is the default for MongoDB Atlas. Use role-based access control (RBAC) to grant users only the permissions they need. 2. **Use Strong Passwords or Authentication Mechanisms** Avoid simple passwords. Use strong, complex passwords for all database users. Alternatively, use certificate-based authentication or federated authentication with your identity provider. 3. **Whitelist IP Addresses** Configure your Access List (IP Whitelist) to restrict access to trusted IP addresses. This ensures that only specified IP addresses can connect to your cluster. 4. **Enable Network Encryption (TLS/SSL)** MongoDB Atlas supports TLS/SSL by default for securing data in transit. Ensure applications are configured to connect with SSL/TLS-enabled settings. 5. **Use End-to-End Encryption (Client-Side Field-Level Encryption)** Implement client-side field-level encryption to ensure sensitive fields are encrypted end-to-end. 6. **Regularly Rotate Authentication Credentials** Periodically rotate users' passwords or access keys to mitigate the risks of credential exposure. 7. **Use Private Networking** If supported, use Virtual Private Cloud (VPC) peering or private endpoints, such as AWS PrivateLink, to connect securely to your MongoDB Atlas cluster without using the public internet. 8. **Enable Database Auditing** Enable auditing to track database activity and detect potential anomalies or unauthorized access. 9. **Enable Backup and Data Recovery** Regularly back up your data using MongoDB Atlas' automated backup systems to ensure business continuity in case of accidental deletions or data loss. 10. **Keep the MongoDB Drivers Updated** Use the latest version of MongoDB drivers in your application to benefit from security updates and enhancements. 11. **Monitor and Set Alerts** Use MongoDB Atlas' monitoring tools to track metrics and set up alerts for suspicious activities or unusual resource consumption. 12. **Implement Application-Level Security** Ensure your application properly handles user authentication, session management, and input sanitization to prevent unauthorized access or injection attacks. 13. **Watch for Security Best Practices Updates** Regularly review MongoDB Atlas documentation and security advisories to stay aware of new features and recommendations. By following these practices, you can greatly enhance the security posture of your MongoDB Atlas cluster. Source documents: [ { "pageContent": "Optimizing Data \nAccess Patterns\nNative tools in MongoDB for improving query \nperformance and reducing overhead.", "pageNumber": 17 } ]
次のステップ
MongoDB ベクトル検索 をLgGraph と統合する方法については、 MongoDB をLgGraph.js と統合する を参照してください。
MongoDBは、次の開発者リソースも提供しています。