MongoDB をMem0 と統合すると、対話全体に保持されるAIエージェントの長期メモリを構成できます。このチュートリアルでは、Mem0 がMongoDB をベクトルストアとして使用するように構成し、メモリ拡張支援を構築します。このチュートリアルでは、次のタスクを実行します。
環境を設定します。
MongoDB をMem0ベクトルストアとして使用します。
メモリ ドキュメントの保存と取得。
検索したメモリに基づいて、応答をパーソナライズする支援を構築します。
バックグラウンド
Mem0 は、 AIエージェントと 支援のオープンソース メモリレイヤーです。すべてのリクエストでやり取り履歴全体を LM に渡す代わりに、Mem0 はやり取りから個別の情報を抽出し、各ファセットをドキュメントとして保存し、クエリ時に最も関連性の高いファセットのみを検索します。
MongoDB をベクトルストアとして使用するように Mem0 を構成すると、Mem0 はこれらのメモリ ドキュメントをMongoDBコレクションに永続化します。セマンティック検索にはMongoDB ベクトル検索 を使用し、全文キーワード検索にはMongoDB Search を使用します。 Mem0 は、コレクションに初めて接続するときに両方のインデックスを作成します 。
前提条件
Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。
次のいずれかのMongoDBクラスター タイプ
MongoDBバージョン6.0.11 、7.0.2 、またはそれ以降を実行中Atlas クラスター。 IPアドレスが Atlas プロジェクトのアクセス リストに含まれていることを確認します。
PythonとDockerを使用して作成されたローカル Atlas 配置。プログラムでローカル配置を作成および管理するには、
atlas-local-lib-py(pip install atlas-local-lib-py)をインストールします。詳細については、 atlas-local-lib-pyリポジトリを参照してください。Search とベクトル検索がインストールされたMongoDB Community クラスター。
OpenAI APIキー。API リクエストに使用できるクレジットがある OpenAI アカウントが必要です。OpenAI のアカウント登録の詳細については、OpenAI API のウェブサイトをご覧ください。
Python v3.10 以降。
環境を設定する
環境変数を設定します。
mem0-mongodb-projectディレクトリに .envファイルを作成し、次のコードを追加します。
OPENAI_API_KEY="<openai-api-key>" MONGODB_URI="<connection-string>"
<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。
接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
詳細については、クライアント ライブラリを使用したクラスターへの接続 を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true
「接続文字列」を参照してください。
メモリ データの保存と取得
このセクションでは、 MongoDB をベクトルストアとして使用するように Mem0 を構成します。次に、Mem0 が対話から抽出したメモリを保存し、セマンティック検索を使用して取得します。
MongoDB をベクトルストアとして構成します。
MongoDB をMem0ベクトルストアとして使用するには、次のコードを main.pyファイルに追加します。
config = { "llm": { "provider": "openai", "config": { "model": "gpt-4o-mini", "temperature": 0.1, "max_tokens": 2000, }, }, "embedder": { "provider": "openai", "config": { "model": "text-embedding-3-small", "embedding_dims": 1536, }, }, "vector_store": { "provider": "mongodb", "config": { "mongo_uri": os.environ["MONGODB_URI"], "db_name": "mem0_db", "collection_name": "agent_memory", "embedding_model_dims": 1536, }, }, } m = Memory.from_config(config)
このコードは、config 辞書に次のキーを設定します。
llm: 対話から要因を抽出するモデルとしてgpt-4o-miniを指定しますembedder: 埋め込みを生成するモデルとしてtext-embedding-3-smallを指定しますvector_store: MongoDB をベクトルストアとして構成します
インデックスの構築には約 1 分かかります。構築中、インデックスは最初の同期状態になります。構築が完了したら、コレクション内のデータのクエリを開始できます。
チャットのメモリを保存します。
ユーザーのロケーションに関するやり取りからメモリを抽出して保存するには、次のコードを追加します。
messages = [ {"role": "user", "content": "I'm moving to Berlin next month."}, {"role": "assistant", "content": "I'll remember that you're relocating to Berlin."}, ] result = m.add(messages, user_id="alice") print(result)
やり取りデータを add() メソッドに渡すと、Mem0 は LM を使用してやり取りから情報を抽出し、各ファセットを個別の メモリドキュメントとしてコレクションに書込みます。
2 回目の対話のメモリを保存します。
2 回目の交信のメモリを保存するには、次のコードを追加します。これは Mem0 が同じユーザーのメモリプロファイルに追加します。
messages = [ {"role": "user", "content": "I prefer concise answers and I use Python daily."}, {"role": "assistant", "content": "Noted. I'll keep my responses brief and Python-focused."}, ] result = m.add(messages, user_id="alice") print(result)
保存されたメモリを検索します。
ユーザーのリロケーションに関するクエリに答えるメモリ データを検索するには、次のコードを main.pyファイルに追加します。
print("\nWaiting for the MongoDB Vector Search index to finish building...") time.sleep(60) results = m.search( query="When is Alice moving?", filters={"user_id": "alice"}, top_k=5, ) for mem in results["results"]: print(mem["memory"], "- score:", mem["score"])
クエリを実行中前に、 MongoDB ベクトル検索インデックスの構築を完了できるようにコードは 60 秒待機します。
Tip
保存されたメモリ ドキュメントを確認するには、mem0_db.agent_memory Atlas UIで コレクションを参照してください。詳細については、「 コレクションの表示 」を参照してください。
メモリ拡張支援の構築
このセクションでは、メモリのストレージと検索を組み合わせて、応答をパーソナライズする支援を行う方法を示します。支援が応答する前に、現在のメッセージに最も関連するメモリを検索し、システムプロンプトに追加します。応答後に新しい交換を保存し、交換のたびにメモリが拡張されます。
メモリを取得し、システム プロンプトを構築します。
main.pyファイルに次のコードを追加して、メッセージに最も関連するメモリを検索し、それらのメモリをシステム プロンプトに追加する関数を定義します。
openai_client = OpenAI() USER_ID = "alice" def build_system_prompt(user_message): # Retrieve the memories that are most relevant to the message relevant = m.search( query=user_message, filters={"user_id": USER_ID}, top_k=5, ) memory_text = "\n".join(f"- {mem['memory']}" for mem in relevant["results"]) # Add the retrieved memories to the system prompt system_prompt = "You are a helpful personal assistant." if memory_text: system_prompt += ( " Use the following facts to personalize your response:\n" f"{memory_text}" ) return system_prompt
応答を生成し、交信の結果を保存します。
次のコードを追加して、パーソナライズされた応答を生成し、新しいやり取りをメモリとして保存する関数を定義します。
def chat(user_message): # Generate a response response = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": build_system_prompt(user_message)}, {"role": "user", "content": user_message}, ], ) assistant_message = response.choices[0].message.content # Store the new conversation turn as memories m.add( [ {"role": "user", "content": user_message}, {"role": "assistant", "content": assistant_message}, ], user_id=USER_ID, ) return assistant_message print(chat("Can you recommend a programming meetup in my city?"))
支援者は、プロンプトを構築する前にMongoDBから AES の場所と言語設定を取得したため、ベルリンでのPythonインターフェースを使用することを推奨します。
ファイルを実行
main.pyファイルを実行するには、mem0-mongodb-projectディレクトリから次のコマンドを実行します。
python main.py
コマンドが正常に実行されると、出力は次のようになります。
# Output from the first add() method that stores relocation data {'results': [{'id': '...', 'memory': 'User is moving to Berlin around September 2026.', 'event': 'ADD'}]} # Output from the second add() method that stores user preferences {'results': [{'id': '...', 'memory': 'Prefers concise answers', 'event': 'ADD'}, {'id': '...', 'memory': 'Uses Python daily', 'event': 'ADD'}]} Waiting for the MongoDB Vector Search index to finish building... # Output from the search() method that retrieves the relocation memory User is moving to Berlin in September 2026. - score: 0.38553877995545677User is moving to Berlin around September 2026. - score: 0.7043201923370361 # Output from the get_all() method that returns the full memory history <id> User is moving to Berlin around September 2026. <id> Prefers concise answers <id> Uses Python daily # Output from the chat() method that asks the assistant about programming meetups Since you're moving to Berlin around September 25, 2026, I recommend checking platforms like Meetup.com or Eventbrite closer to your move for local Python programming meetups. You can also follow local tech communities on social media for updates on events.
次のステップ
Mem0 構成キーと メソッドの完全なセットの詳細については、 「Memory MongoDBと Mem との統合 」を参照してください。0
Mem がコレクションに作成するインデックスの詳細については、0 「 MongoDB ベクトル検索インデックスの作成 」と「 MongoDB Search インデックスの管理 」を参照してください。