您可以将 MongoDB 与 Mem0 集成,以配置为 AI 代理提供可在对话之间持久存储的长期记忆。本教程配置 Mem0 使用 MongoDB 作为其向量存储,然后构建一个增强记忆的助手。在本教程中,您将执行以下任务:
设置您的环境。
使用 MongoDB 作为 Mem0 向量存储。
存储和检索内存文档。
构建一个助手,根据其检索到的记忆个性化其响应。
背景
Mem0 是一个面向AI代理和助手的开源内存层。 Mem0 不是在每次请求都将整个对话历史记录传递给 LLM,而是从对话中提取离散的事实,将每个事实存储为文档,并在查询时仅检索最相关的事实。
当您将 Mem0 配置为使用 MongoDB 作为其向量存储时,Mem0 会将这些内存文档持久存储到 MongoDB 集合中。它使用 MongoDB 向量搜索进行语义检索,并使用 MongoDB Search 进行全文关键字检索。Mem0 会在首次连接到您的集合时,为您创建这两个索引。
先决条件
要完成本教程,您必须具备以下资源:
以下MongoDB 集群类型之一:
使用Python和Docker创建的本地Atlas部署。安装
atlas-local-lib-py(pip install atlas-local-lib-py) 以以编程方式创建和管理本地部署。要学习;了解更多信息,请参阅 atlas-local-lib-py存储库。安装了 Search 和 Vector 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 集群或本地部署的连接字符串。
连接字符串应使用以下格式:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
重要: 确保连接字符串包含数据库用户的凭证。要学习有关查找连接字符串的更多信息,请参阅通过客户端库连接到集群。
存储和检索内存数据
在本节中,您将配置 Mem0 以使用 MongoDB 作为其向量存储。然后,您存储 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 作为向量存储
存储对话中的记忆。
添加以下代码,用于从关于用户搬迁的对话中提取和存储记忆:
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 使用 LLM 从对话中提取事实,并将每个事实作为单独的内存文档写入您的集合。
搜索存储的记忆。
要搜索回答关于用户迁移的查询的内存数据,请将以下代码添加到您的 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"])
在运行查询之前,代码会等待 60 秒,以便 MongoDB 向量搜索索引完成建立。
提示
要检查存储的内存文档,请浏览 Atlas 用户界面中的 mem0_db.agent_memory 集合。要了解更多,请参阅 查看集合。
构建一个记忆增强助手
本节介绍如何将内存存储和检索组合到助手中,该助手可以实现回复的个性化。在助手回复之前,它会检索与当前消息最相关的记忆,并将其添加到系统提示中。在回复之后,它会存储新的对话轮次,以便记忆随着每次交流而增长。
检索记忆并构建系统提示。
在您的 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?"))
助手推荐了一个在柏林举行的 Python 聚会,因为它在构建提示之前,从 MongoDB 中检索了 Alice 的位置和语言偏好。
运行文件
要运行 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 与 Mem0 集成。
要学习;了解有关 Mem0 在您的集合上创建的索引的更多信息,请参阅创建MongoDB Vector Search 索引和管理MongoDB搜索索引。