您可以将MongoDB与 Mem0 集成,为AI代理配置在对话中持续存在的长期内存。本教程将 Mem0 配置为使用MongoDB作为其向量存储,然后构建内存增强助手。在本教程中,您将执行以下任务:
设置您的环境。
使用MongoDB作为 Mem0 向量存储。
存储和检索内存文档。
构建一个助手,根据检索的记忆个性化其响应。
背景
Mem0 是一个用于AI代理和助手的开源内存层。 Mem 不是在每次请求都将整个对话历史记录传递给0 LLM,而是从对话中提取离散的事实,将每个事实存储为文档,并在查询时仅检索最相关的事实。
当您将 Mem0 配置为使用MongoDB作为其向量存储时,Mem0 会将这些内存文档保存在MongoDB集合中。它使用MongoDB Vector Search 进行语义检索,并使用MongoDB Search 进行全文关键字检索。 Mem0 会在首次连接到您的集合时为您创建两个索引。
先决条件
要完成本教程,您必须拥有以下资源:
以下MongoDB 集群类型之一:
使用Python和Docker创建的本地Atlas部署。安装
atlas-local-lib-pypip install atlas-local-lib-py(),以编程方式创建和管理本地部署。要学习;了解更多信息,请参阅 atlas-local-lib-py存储库。安装了 Search 和 Vector Search 的MongoDB Community集群。
一个 OpenAI API 密钥。您必须拥有一个 OpenAI 帐户,该帐户具有可用于 API 请求的信用额度。要了解有关注册 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 Vector Search索引完成构建。
提示
要检查存储的内存文档,请浏览Atlasmem0_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检索了爱丽丝的位置和语言偏好。
运行文件
要运行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
要学习;了解有关 Mem0 在您的集合上创建的索引的更多信息,请参阅创建MongoDB Vector Search 索引和管理MongoDB搜索索引。