MongoDB をLgGraph.js と統合すると、 MongoDB LingGraph チェックポイントから取得する短期間のメモリに加えて、長期のメモリをエージェントに追加できます。
このページでは、次のチュートリアルの概念を構築します。
このページでは、次の方法を学習します。
LgGraph では、長期的なメモリとは対照的な短期間のメモリが理解されます。
LgGraph.js 用のMongoDBベースの長期メモリ ストアを構成します。
スレッドやセッション全体でユーザー固有のデータを永続的に検索します。
セマンティック 呼び出し用にMongoDB ベクトル検索と Vyage AI埋め込みを使用して長期メモリを組み合わせます。
注意
このページの例では、 TypeScript スタイルの構文を使用しています。型の注釈を削除することで、単純なJavaScript用に調整できます。
LgGraph のMongoDBメモリ メカニズムの概要
LongGraph は 2 つの補完メモリ メカニズムを提供します。
短期間メモリ(チェックポイント)
チェックポイント を使用して、リクエスト全体で単一のスレッド(変換)の状態を永続化します。 MongoDB統合では、これはMongoDB LingGraph チェックポイント(MongoDBSaver )によって処理されます。これにより、特定の対話に対して、時間移動、人間によるレビュー、フォールトトレランスなどの機能が可能になります。
長期メモリ(ストア)
ストア抽象化を使用して、単一の対話内だけでなくスレッド間でデータを保持します。セッション間とエージェント間の両方に耐えられるデータを保存するのに最適です。
MongoDB Store for LgGraph.js を使用すると、次のことが可能になります。
MongoDBをバックエンドとして使用して、 JavaScript /TypeScript に
BaseStoreインターフェースを実装します。LgGraph の標準ストアAPI (
get、put、delete、search)を使用します。JSONドキュメントを階層的な名前空間で保存します(例: 、
[userId, "memories"])。オート埋め込み機能付きのMongoDB ベクトル検索とValidation AI埋め込みを基盤とした、保存済みデータのセマンティック検索とメタデータフィルタリングを実行します。
前提条件
始める前に、以下のものを必ず用意してください。
次のいずれかのMongoDBクラスター タイプ
MongoDB バージョン 6.0.11、7.0.2、またはそれ以降を実行している Atlas クラスター。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認する。
Atlas CLI を使用して作成されたローカル Atlas 配置。詳細については、「Atlas 配置のローカル配置の作成」を参照してください。
Search とベクトル検索がインストールされたMongoDB Community または Enterprise クラスター。
npmとNode.jsがインストールされました。
Voyage AI APIキー。APIキーを作成するには、「 モデルAPIキー 」を参照してください。
OpenAI APIキー。APIリクエストに使用できるクレジットを持つ OpenAI アカウントが必要です。OpenAI アカウントの登録の詳細については、OpenAI APIウェブサイト を参照してください。
セマンティック検索を使用する場合は、 MongoDB ベクトル検索用に構成されたMongoDBデータベースとコレクション。詳細については、 「Atlas ベクトル検索インデックスの作成」 を参照してください。
について理解があり、理想的には以下を完了している必要があります。
MongoDB をLgGraph.js と統合します(概要、チェックポイント、検索ツール)。
LgGraph.js とMongoDB AtlasでAIエージェントを構築できます( エンドツーエンドエージェント、ベクトル検索、短期間メモリ)。
依存関係のインストール
「 AIエージェントの構築 」チュートリアルで使用されるコア依存関係と、LgGraph.js のMongoDB Store モジュールをインストールします。
npm init -y # Core LangChain / LangGraph / MongoDB dependencies npm i --legacy-peer-deps \ langchain \ @langchain/langgraph \ @langchain/mongodb \ @langchain/community \ @langchain/langgraph-checkpoint-mongodb \ dotenv \ express \ mongodb \ zod
@langchain/langgraph-checkpoint-mongodbパッケージには、チェックポイントと長期メモリ用のMongoDBストアの両方が含まれています。
MongoDBストアの構成
LgGraphBaseStore getputdeletesearchストアは、階層的な名前空間の下のJSONドキュメントに対して、 、 、 、 などの操作を含む インターフェースを実装します。
MongoDBクライアントの初期化
既存の LgGraph.jsエージェントサーバーからMongoDBクライアント構成を再利用します。
// mongodb-client.ts import { MongoClient } from "mongodb"; import "dotenv/config"; export const client = new MongoClient(process.env.MONGODB_URI as string); export async function connectClient() { await client.connect(); await client.db("admin").command({ ping: 1 }); console.log("Pinged your deployment. You successfully connected to MongoDB!"); }
MongoDBStore インスタンスの作成
長期メモリ用に構成された MongoDBStore をエクスポートするモジュールを作成します。
// long-term-store.ts import type { MongoClient } from "mongodb"; import { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; const DB_NAME = "hr_database"; const COLLECTION_NAME = "long_term_memory"; export function createMongoDBStore(client: MongoClient) { const store = new MongoDBStore({ client, dbName: DB_NAME, collectionName: COLLECTION_NAME, }); return store; }
このストアでは、[userId, "memories"] や [userId, "preferences"] などの階層的な名前空間によってキーされるスレッドとセッション全体のデータが永続化されます。
長期メモリ スキーマの設計
長期メモリは、ユーザーまたはドメインに関する安定したデータをモデル化する場合に最適です。
一般的なパターンには、次のようなものがあります。
ユーザー プロファイル - ロール、年数、チーム、場所。永続的な設定(例: 、単調、言語、製品階層など)。
制約と - アラート、コンプライアンス制限、予算上限。
インタラクション履歴のサマリー - 過去のセッションの高レベルのサマリー。転送する必要がある決定(例、)。「ユーザーは自己管理型よりもMongoDB Atlas を優先します 」)。
これらは、単純なJSONドキュメントとして、またはセマンティック検索用の埋め込みを持つドキュメントとして保存できます。
永続的なユーザーメモリ
MongoDB Store API は次の操作をサポートしています。
put- 値を保存または更新します。get-名前空間とキーで値を検索します。delete- 値を削除します。search-ベクトル類似度やメタデータフィルターによって値を検索します。
正確な TypeScript の型は異なる場合がありますが、次のコードは LgGraph.js の一般的な使用パターンを示しています。
// memory-api.ts import type { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; type MemoryValue = { type: "profile" | "preference" | "fact"; data: Record<string, unknown>; updatedAt: string; }; export async function putUserMemory( store: MongoDBStore, userId: string, key: string, value: MemoryValue ) { await store.put( [userId, "memories"], key, value ); } export async function getUserMemories( store: MongoDBStore, userId: string, key: string ) { const result = await store.get( [userId, "memories"], key ); return result; }
エージェント ワークフローに長期メモリを追加する
このセクションでは、「 LgGraph.js とMongoDB Atlasを使用してAIエージェントを構築する 」で説明されているものと同様の、次のようなエージェントワークフローがすでに存在していることを前提としています。
messagesフィールドを持つGraphState注釈 。Vyage AIからの埋め込みを使用してMongoDB ベクトル検索を呼び出すツールノード。
ツールを呼び出すか、直接応答するかを決定するチャット モデルノード。
短期間メモリ用の
MongoDBSaverチェックポイント。
エージェント関数へのストアの挿入
MongoDBクライアントとともに store を受け入れるように、callAgent 関数をアップデートします。
// agent-with-long-term-memory.ts import { ChatOpenAI } from "@langchain/openai"; import { AIMessage, BaseMessage, HumanMessage, } from "@langchain/core/messages"; import { ChatPromptTemplate, MessagesPlaceholder, } from "@langchain/core/prompts"; import { StateGraph, Annotation } from "@langchain/langgraph"; import { tool } from "@langchain/core/tools"; import { ToolNode } from "@langchain/langgraph/prebuilt"; import { MongoDBSaver } from "@langchain/langgraph-checkpoint-mongodb"; import type { MongoClient } from "mongodb"; import type { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; import { putUserMemory, getUserMemories } from "./memory-api"; export async function callAgent( client: MongoClient, store: MongoDBStore, query: string, threadId: string, userId: string, ) { const dbName = "hr_database"; const db = client.db(dbName); const collection = db.collection("employees"); // 1. Retrieve long-term memories for the user const existingMemories = await getUserMemories(store, userId, "last_response"); // 2. Define graph state const GraphState = Annotation.Root({ messages: Annotation<BaseMessage[]>({ reducer: (x, y) => x.concat(y), }), userId: Annotation<string>(), memories: Annotation<unknown | null>(), }); // 3. Define tools (for example, MongoDB Vector Search retriever) const employeeLookupTool = tool(/* ...reuse from Build an AI Agent tutorial... */); const tools = [employeeLookupTool]; const toolNode = new ToolNode<typeof GraphState.State>(tools); // 4. Configure the chat model const model = new ChatOpenAI({ model: "gpt-5.4-mini", }).bindTools(tools); // 5. Define the model node async function callModel(state: typeof GraphState.State) { const prompt = ChatPromptTemplate.fromMessages([ "system", `You are a helpful HR chatbot agent. Use the provided tools and long-term memories to answer questions. Long-term memories (if any) are in the "memories" field.`, new MessagesPlaceholder("messages"), ]); const formatted = await prompt.formatMessages({ messages: state.messages, }); const result = await model.invoke(formatted); return { messages: [result] }; } // 6. Define routing logic function shouldContinue(state: typeof GraphState.State) { const messages = state.messages; const lastMessage = messages[messages.length - 1] as AIMessage; if (lastMessage.tool_calls?.length) { return "tools"; } return "__end__"; } // 7. Build the workflow const workflow = new StateGraph(GraphState) .addNode("agent", callModel) .addNode("tools", toolNode) .addEdge("__start__", "agent") .addConditionalEdges("agent", shouldContinue) .addEdge("tools", "agent"); // 8. Configure short-term memory (checkpointer) const checkpointer = new MongoDBSaver({ client, dbName }); const app = workflow.compile({ checkpointer, store, }); // 9. Invoke the graph with both short-term and long-term memory const finalState = await app.invoke( { messages: [new HumanMessage(query)], userId, memories: existingMemories, }, { recursionLimit: 15, configurable: { thread_id: threadId }, }, ); const last = finalState.messages[finalState.messages.length - 1]; const content = last.content; // 10. Optionally, update long-term memory with new facts await putUserMemory(store, userId, "last_response", { type: "fact", data: { content }, updatedAt: new Date().toISOString(), }); return content; }
このパターンにより次のことが可能になります。
各インタラクションの開始時に長期メモリを読み取ります。
それらのメモリを 状態に挿入します(例、
memoriesとして、またはシステム プロンプトに)。エージェントが学習した内容に基づいて、各インタラクションの後に長期メモリを更新します。
長期メモリへのセマンティック検索と自動埋め込みの使用
長期メモリを意味で検索可能にするには、次の操作を実行します。
各メモリを、次の内容を含むドキュメントとして保存します。
テキストの概要または説明。
構造化メタデータ(例: 、
userId、type、tags)。セマンティック検索用の埋め込みベクトル。
メモリコレクションの
embeddingフィールドにMongoDB ベクトル検索インデックスを構成します。投票AI埋め込み または 投票自動埋め込み(Atlas 埋め込みと再ランクAPIを通じて)を使用して、挿入する前に各メモリドキュメントの埋め込みを生成します。
組み込みの
searchメソッドをMongoDBStoreで使用します。これは、メモリコレクションの$vectorSearchを呼び出し、オプションでuserIdやtypeなどのメタデータフィルタと組み合わせて使用します。
次のコードは、MongoDBStore に組み込みの search メソッドを使用して、セマンティック類似性とメタデータフィルターでメモリを検索する方法を示しています。
// semantic-memory.ts import type { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; export async function searchUserMemories( store: MongoDBStore, userId: string, queryText: string, limit = 5, ) { const results = await store.search( [userId, "memories"], { query: queryText, filter: { type: "fact" }, limit, }, ); return results; }
search メソッドは、名前空間プレフィックスと、次のフィールドを持つオプションオブジェクトを受け入れます。
query- セマンティック検索用のテキスト string。ストアはMongoDB ベクトル検索を使用して、クエリにセマンティックに類似するメモリを検索します。filter- 結果を絞り込むメタデータフィルターオブジェクト(例: 、{ type: "fact" })。limit- 返される結果の最大数(デフォルト:10)。offset- ページネーションのためにスキップする結果の数(デフォルト:0)。
注意
Vyage Auto埋め込みを使用すると、埋め込み生成を Atlas 埋め込みと再ランク付けAPIにオフロードし、 MongoDB ベクトル検索 をストレージバックエンドとして使用できます。 LgGraph.js の長期メモリ ストアはこのエクスペリエンスで動作するように設計されており、自動埋め込み生成と LingGraph ストアおよびベクトル検索を組み合わせて 1 つの長期メモリレイヤーを構築できます。
短期間メモリと長期メモリを使用する場合
次のガイドラインを使用して、アプリケーションの各部分に適切なメモリ メカニズムを選択します。
メカニズム | 使用ケース | 詳細 |
|---|---|---|
短縮メモリ(チェックポイント) | 対話内でのみ重要なスレッドごとのコンテキストには を使用します。 | 段階的な理由付け、ツール呼び出し結果、中間状態に最適です。 PythonとJavaScript の両方の統合で |
長期メモリ(ストア) | 一定時間保持する必要があるクロススレッド情報には を使用します。 | ユーザー プロファイル、ポリシーと制約、長期的な結果、セマンティック 呼び出しに最適です。 LgGraph.js の |
実際のアプリケーションの多くでは、次のことを行います。
現在のやり取りの一貫性を保つには、短期間メモリを使用します。
長期メモリを使用して、過去のやり取りからユーザーと重要な情報を覚えておいてください。
応答の生成時にメモリをセマンティックで検索するには、 Auto埋め込み 機能を持つMongoDB ベクトル検索と Vyage AI埋め込みを使用します。
次のステップ
「 LgGraph.js とMongoDB Atlasを使用してAIエージェントを構築する 」のエンドツーエンドのチュートリアルに従ってください。
このページを参照として使用して、既存のエージェントの上部に長期メモリとセマンティック検索をレイヤー。
埋め込みと自動埋め込みワークフローの詳細については、 Vyage AI のドキュメント と Atlas 埋め込みと再ランク付けAPI をご覧ください。
MongoDBは、次の開発者リソースも提供しています。