Docs Menu
Docs Home
/ /

LangChain JavaScript/Typescript 統合を始めましょう

注意

このチュートリアルでは、Lgachein の JavaScriptライブラリ を使用します。Pythonライブラリを使用するチュートリアルについては、 LangChain Python を参照してください。

MongoDB ベクトル検索 をLgChuin と統合して、LM アプリケーションを構築し、検索拡張生成 (RAG)(RAG)を実装できます。このチュートリアルでは、Lgachein とMongoDB ベクトル検索の使用を開始し、データのセマンティック検索を実行し、 RAG実装を構築する方法を説明します。具体的には、次のアクションを実行します。

  1. 環境を設定します。

  2. カスタム データをMongoDBに保存します。

  3. データにMongoDB ベクトル検索インデックスを作成します。

  4. 次のベクトル検索クエリを実行します。

    • セマンティック検索。

    • メタデータの事前フィルタリングによるセマンティック検索。

    • 最大マージナル関連性(MMR)検索。

  5. MongoDB ベクトル検索を使用してデータの質問に答え、RAG を実装します。

LgChuin は、「チェーン」の使用を通じて LVM アプリケーションの作成を簡素化するオープンソースのフレームワークです。 チェーンは 、RAG を含むさまざまなAIユースケースで組み合わせることができる Lgachein 固有のコンポーネントです。

MongoDB ベクトル検索 をLgachein と統合することで、 MongoDB をベクトルデータベースとして使用し、 MongoDB ベクトル検索 を使用してセマンティックで類似したドキュメントを検索して RAG を実装することができます。To learn more about RAG, see Retrieval-Augmented Generation (RAG) with MongoDB.

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

  • 次のいずれかのMongoDBクラスター タイプ

    • MongoDB バージョン 6.0.11、7.0.2、またはそれ以降を実行している Atlas クラスター。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認する。

    • Atlas CLI を使用して作成されたローカル Atlas 配置。詳細については、「Atlas 配置のローカル配置の作成」を参照してください。

    • Search とベクトル検索がインストールされたMongoDB Community または Enterprise クラスター。

  • Voyage AI APIキー。APIキーを作成するには、「 モデルAPIキー 」を参照してください。

    注意

    Atlas ( Atlas UIで作成されたAPIキー)または Vyage AI (Vorage AIから直接作成されたAPIキー)に支払い方法が構成されていない場合、 APIリクエストは失敗する可能性があります。

  • OpenAI APIキー。APIリクエストに使用できるクレジットを持つ OpenAI アカウントが必要です。OpenAI アカウントの登録の詳細については、OpenAI APIウェブサイト を参照してください。

  • Node.js プロジェクトを実行するためのターミナルとコード エディター。

  • npmとNode.jsがインストールされました。

このチュートリアルの環境を設定します。 環境を設定するには、次の手順を実行します。

1

ターミナルで次のコマンドを実行して、 langchain-mongodbという名前の新しいディレクトリを作成し、プロジェクトを初期化します。

mkdir langchain-mongodb
cd langchain-mongodb
npm init -y
2

次のコマンドを実行します:

npm install langchain@latest @langchain/community@latest @langchain/core@latest @langchain/mongodb@latest @langchain/openai@latest @langchain/textsplitters@latest pdf-parse@1 --legacy-peer-deps
3

ES モジュール を使用するようにプロジェクトを構成するには、"type": "module"package.jsonファイルに追加して保存します。

{
"type": "module",
// other fields...
}
4

プロジェクトで、 get-started.jsという名前のファイルを作成し、次のコードをコピーしてファイルに貼り付けます。 チュートリアル全体でこのファイルにコードを追加します。

この最初のコード スニペットは、このチュートリアルに必要なパッケージをインポートし、環境変数を定義して、 MongoDBクラスターへの接続を確立します。

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/textsplitters";
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);
const formatDocumentsAsString = (docs) => docs.map(d => d.pageContent).join("\n\n");
5

環境の設定を完了するには、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クラスターをベクトルデータベースとしてインスタンス化するための非同期関数を定義します。これはベクトルストアとも呼ばれます。次のコードを 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({ modelName: "voyage-4" });
embeddingModel.apiUrl = 'https://ai.mongodb.com/v1/embeddings';
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

ベクトルストアでベクトル検索クエリを有効にするには、langchain_db.testコレクションにMongoDB ベクトル検索インデックスを作成します。

1
  1. get-started.jsファイルで定義した非同期関数の try ステートメントの末尾に次のコードを追加します。このコードでは、次のフィールドにインデックスためのvectorSearch タイプのインデックスを作成します。

    • embedding ベクトル型としてのフィールド。embeddingフィールドには、Voyage AI の voyage-4 埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、1024ベクトル次元を指定し、cosine を使用して類似性を測定します。

    • loc.pageNumber PDF 内のページ番号でデータを事前にフィルタリングするためのフィルター タイプとしてのフィールド。

    このコードではまた、 await 関数を使用して、検索インデックスが使用される前にデータが に同期されていることを確認します。

    1// Ensure index does not already exist, then create your MongoDB Vector Search index
    2const indexes = await collection.listSearchIndexes("vector_index").toArray();
    3if(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
    30// Wait for index to build and become queryable
    31console.log("Waiting for initial sync...");
    32await new Promise(resolve => setTimeout(() => {
    33 resolve();
    34}, 3000));
  2. ファイルを保存します。

2
node get-started.js

このセクションでは、ベクトル化されたデータに対して実行できるさまざまなクエリを示します。 インデックスが作成できたら、非同期関数に次のコードを追加して、データに対してベクトル検索クエリを実行します。

注意

データをクエリするときに不正確な結果が発生した場合、インデックスの同期に予想以上に時間がかかることがあります。 最初の同期の時間を長くするには、 setTimeout関数の の数を増やします。

1

次のコードでは、 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)
if (basicResults.length === 0) {
console.log("No results found after waiting for index sync. Check Atlas Search index status and embedding configuration.");
}
2
node get-started.js
Semantic Search Results:
[
{
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: 'well-tuned queries.\n' +
'Built-in slow query profiling is also available if you’re deploying MongoDB with Atlas.',
pageNumber: 16
},
{
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: 'If you are running MongoDB on your own infrastructure, you can configure replica set tags to achieve \n' +
'read isolation.',
pageNumber: 21
}
]

MQLマッチ式を使用して、インデックス付きフィールドをコレクション内の別の値と比較することで、データを事前にフィルタリングできます。フィルターするメタデータフィールドはすべて filter タイプとしてインデックスする必要があります。詳細については、 ベクトル検索のフィールドにインデックスを作成する方法 を参照してください。

注意

このチュートリアルのインデックスを作成したときに、 loc.pageNumberフィールドをフィルターとして指定しました。

1

次のコードでは、 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)
2
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)に基づいて、セマンティック検索を実行することもできます。

1

次のコードでは、 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)
2
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 に質問に回答するように要求します。

1

このコードでは、次の処理が行われます。

  • MongoDB ベクトル検索 を、セマンティクスで類似したドキュメントを検索するための検索バーとしてインスタンス化します。

// 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({ modelName: "gpt-5-mini" }) // Pick your preferred model. Ensure to enable it in your OpenAI settings dashboard.
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.invoke(question)
const documents = retrievedResults.map((documents => ({
pageContent: documents.pageContent,
pageNumber: documents.metadata.loc.pageNumber,
})))
console.log("\nSource documents:\n" + JSON.stringify(documents, null, 2))
2

ファイルを保存した後、次のコマンドを実行します。 生成される応答は異なる場合があります。

node get-started.js
Question: How can I secure my MongoDB Atlas cluster?
Answer: You can secure your MongoDB Atlas cluster by achieving workload isolation with dedicated analytics nodes, configuring visualization tools like Atlas Charts to read from analytics nodes only, and using built-in slow query profiling if deploying with Atlas. Additionally, you can distribute replica set members across multiple data centers for added security during election and failover.
Source documents:
[
{
"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": "If you are running MongoDB on your own infrastructure, you can configure replica set tags to achieve \nread isolation.",
"pageNumber": 21
},
{
"pageContent": "well-tuned queries.\nBuilt-in slow query profiling is also available if you’re deploying MongoDB with Atlas.",
"pageNumber": 16
},
{
"pageContent": "achieved during election and failover. \nIf possible, distribute replica set members across multiple data centers. If you’re using MongoDB Atlas,",
"pageNumber": 24
}
]
1

このコードでは、次の処理が行われます。

  • MongoDB ベクトル検索 を、セマンティクスで類似したドキュメントを検索するための検索バーとしてインスタンス化します。次の任意パラメーターも指定します。

    • searchTypemmr として、 MongoDB ベクトル検索 が最大マージナル関連性(MMR)に基づいてドキュメントを検索することを指定します。

    • filter をクリックして、 loc.pageNumberフィールドに事前フィルターを追加して、 17ページのみに表示されるドキュメントを含めます。

    • 次のMDR固有のパラメーター。

      • fetchK ドキュメントをMDRアルゴリズムに渡す前に、 20ドキュメントのみを取得します。

      • lambda、結果間の相違の度数を決定するための01の間の値。 0は最大の相違を表し、 1は最小の相違を表します。

// 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.invoke(question)
const documents = retrievedResults.map((documents => ({
pageContent: documents.pageContent,
pageNumber: documents.metadata.loc.pageNumber,
})))
console.log("\nSource documents:\n" + JSON.stringify(documents, null, 2))
2

ファイルを保存した後、次のコマンドを実行します。 生成される応答は異なる場合があります。

node get-started.js
Question: How can I secure my MongoDB Atlas cluster?
Answer: One way to secure your MongoDB Atlas cluster is by implementing proper access controls and ensuring that only authorized users have access to your data. You can also enable encryption at rest and in transit, use network security features such as VPC peering, and regularly update and patch your MongoDB database to protect against security vulnerabilities. Additionally, implementing auditing and monitoring tools can help you detect and respond to any security incidents in a timely manner.
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は、次の開発者リソースも提供しています。

戻る

RAG アプリケーションを評価する

項目一覧