注意
このチュートリアルでは、LangChain の JavaScript ライブラリ を使用します。Python ライブラリを使用したチュートリアルについては、LangChain Python をご覧ください。
Atlas ベクトル検索 をLgChuin と統合して、LM アプリケーションを構築し、検索拡張生成 (RAG)(RAG)を実装できます。このチュートリアルでは、LlangCharin と Atlas ベクトル検索 の使用を開始し、データに対してセマンティック検索を実行し、 RAG実装を構築する方法を説明します。具体的には、次のアクションを実行します。
環境を設定します。
カスタム データを Atlas に保存します。
データに Atlas Vector Search インデックスを作成します。
次のベクトル検索クエリを実行します。
セマンティック検索。
メタデータの事前フィルタリングによるセマンティック検索。
最大マージナル関連性(MMR)検索。
Atlas Vector Search を使用してデータの質問に答え、 RAGを実装します。
バックグラウンド
LgChuin は、「チェーン」の使用を通じて LVM アプリケーションの作成を簡素化するオープンソースのフレームワークです。 チェーンは 、RAG を含むさまざまなAIユースケースで組み合わせることができる Lgachein 固有のコンポーネントです。
を RAGと統合することで、Atlas Vector Search Atlasをベクトルデータベースとして使用し、 を使用してセマンティックで類似したドキュメントを検索して RG を実装することができます。Atlas Vector SearchRAGRGRAG Atlas Vector Searchの詳細については、「 による検索拡張生成( ) 」を してください。
前提条件
Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。
Atlas アカウントで、MongoDB バージョン 6.0.11 または7.0.2 以降(RCs を含む)のクラスターを実行している。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認してください。詳細については、クラスターの作成を参照してください。
投票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という名前のファイルを作成し、次のコードをコピーしてファイルに貼り付けます。 チュートリアル全体でこのファイルにコードを追加します。
この最初のコードスニペットにより、このチュートリアルに必要な Atlas パッケージのインポート、環境変数の定義、Atlas クラスターへの接続の確立が行われます。
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.ATLAS_CONNECTION_STRING = "<connection-string>"; const client = new MongoClient(process.env.ATLAS_CONNECTION_STRING);
Atlas をベクトル ストアとして使用
このセクションでは、カスタム データを Atlas にロードし、Atlas をベクトルデータベースとしてインスタンス化するための非同期関数を定義します。これは ベクトル ストア と呼ばれます 。次のコードをget-started.jsファイルに追加します。
注意
このチュートリアルでは、ベクトルストアのデータソースとして、MongoDB Atlasベストプラクティスというタイトルの一般にアクセス可能な PDFドキュメントを使用します。このドキュメントでは、Atlas 配置を管理するためのさまざまな推奨事項と主要概念について説明します。
このコードは、次のアクションを実行します。
次のパラメータを指定して、Atlas コレクションを構成します。
langchain_db.testドキュメントを保存する Atlas コレクションとして。vector_indexベクトル ストアをクエリするために使用するインデックスとして 。text未加工のテキスト コンテンツを含むフィールドの名前:embeddingベクトル埋め込みを含むフィールドの名前として。
カスタム データを準備するには、次の手順を実行します。
指定された URL から未加工データを検索し、 PDF として保存します。
テキストスプリット を使用する データを小さなドキュメントに分割します。
各ドキュメントの文字数と連続する 2 つのドキュメント間で重複する文字数を決定する チャンク パラメータを指定します。
MongoDBAtlasVectorSearch.fromDocumentsメソッドを呼び出して、サンプル ドキュメントからベクトル ストアを作成します。 このメソッドでは、次のパラメーターを指定します。ベクトルデータベースに保存する サンプル ドキュメント 。
embeddingフィールドのベクトル埋め込みにテキストを変換するために使用されるモデルとして、AI の埋め込みモデルを使用します。Atlas の構成。
async function run() { try { // Configure your Atlas collection const database = client.db("langchain_db"); const collection = database.collection("test"); const dbConfig = { collection: collection, indexName: "vector_index", // The name of the Atlas 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 Atlas 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);
ファイルを保存し、次のコマンドを実行してデータを Atlas にロードします。
node get-started.js
Tip
get-started.jsを実行した後、クラスター内のlangchain_db.testコレクションに移動すると、Atlas UI でベクトル埋め込みを表示できます。
Atlas Vector Search インデックスの作成
注意
Atlas Vector Search インデックスを作成するには、Atlas プロジェクトに対するProject Data Access Admin以上のアクセス権が必要です。
ベクトル ストアでベクトル検索クエリを有効にするには、 langchain_db.testコレクションに Atlas Vector Search インデックスを作成します。
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 Atlas Vector Search index 2 const indexes = await collection.listSearchIndexes("vector_index").toArray(); 3 if(indexes.length === 0){ 4 5 // Define your Atlas 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 Atlas to sync index 30 console.log("Waiting for initial sync..."); 31 await new Promise(resolve => setTimeout(() => { 32 resolve(); 33 }, 10000)); 34 }
ファイルを保存し、次のコマンドを実行して Atlas Vector Search インデックスを作成します。
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 リファレンス を参照してください。
データに関する質問に答えます
このセクションでは、Atlas ベクトル検索と Lgachein を使用した 2 つの異なる RG 実装を示します。Atlas ベクトル検索を使用してセマンティックに類似したドキュメントを検索したので、次のコード例を使用して、Atlas ベクトル検索によって返されたドキュメントに対する質問に答えるように LM に指示します。
次のコードを非同期関数に追加し、ファイルを保存します。
このコードでは、次の処理が行われます。
Atlas Vector Search をレプリカとして インスタンス 化 セマンティックに類似したドキュメントをクエリします。
これらのドキュメントをクエリのコンテキストとして使用するように 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 } ]
次のコードを非同期関数に追加し、ファイルを保存します。
このコードでは、次の処理が行われます。
Atlas Vector Search をレプリカとして インスタンス 化 セマンティックに類似したドキュメントをクエリします。次の任意パラメーターも指定します。
searchTypeとしてmmrとして、Atlas Vector Search が Max MongoDB Atlas(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 } ]
次のステップ
Atlas Vector Search を LangGraph と統合する方法については、「MongoDB と LangGraph.js の統合」を参照してください。
MongoDBは、次の開発者リソースも提供しています。