对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

开始使用MongoDB Mem0 集成

您可以将MongoDB与 Mem0 集成,为AI代理配置在对话中持续存在的长期内存。本教程将 Mem0 配置为使用MongoDB作为其向量存储,然后构建内存增强助手。在本教程中,您将执行以下任务:

  1. 设置您的环境。

  2. 使用MongoDB作为 Mem0 向量存储。

  3. 存储和检索内存文档。

  4. 构建一个助手,根据检索的记忆个性化其响应。

Mem0 是一个用于AI代理和助手的开源内存层。 Mem 不是在每次请求都将整个对话历史记录传递给0 LLM,而是从对话中提取离散的事实,将每个事实存储为文档,并在查询时仅检索最相关的事实。

当您将 Mem0 配置为使用MongoDB作为其向量存储时,Mem0 会将这些内存文档保存在MongoDB集合中。它使用MongoDB Vector Search 进行语义检索,并使用MongoDB Search 进行全文关键字检索。 Mem0 会在首次连接到您的集合时为您创建两个索引。

要完成本教程,您必须拥有以下资源:

  • 以下MongoDB 集群类型之一:

    • 运行MongoDB6.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 和 Vector Search 的MongoDB Community集群。

  • 一个 OpenAI API 密钥。您必须拥有一个 OpenAI 帐户,该帐户具有可用于 API 请求的信用额度。要了解有关注册 OpenAI 账号的更多信息,请参阅 OpenAI API 网站

  • Python v3.10 或更高版本。

1

在终端中运行以下命令,创建名为 mem0-mongodb-project 的新目录并安装所需的依赖项:

mkdir mem0-mongodb-project
cd mem0-mongodb-project
pip install mem0ai pymongo openai python-dotenv

Mem0 需要PyMongo v4.13.2 或更高版本。前面的命令会安装最新版本的PyMongo。

2

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

要学习;了解更多信息,请参阅通过客户端库连接到集群。

连接字符串应使用以下格式:

mongodb://localhost:<port-number>/?directConnection=true

要学习;了解更多信息,请参阅连接字符串。

3

mem0-mongodb-project目录中,创建名为 main.py 的文件。将以下代码添加到此文件以加载环境变量:

from mem0 import Memory
from openai import OpenAI
from dotenv import load_dotenv
import os
load_dotenv()

在后续步骤中,您将向此文件添加代码以配置 Mem0 并构建助手。

在本部分中,您将配置 Mem0 以使用MongoDB作为其向量存储。然后,存储Mem0 从对话中提取的记忆,并使用语义搜索来检索这些记忆。

1

要将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配置为向量存储

构建索引大约需要一分钟时间。在构建时,索引处于初始同步状态。构建完成后,您可以开始查询集合中的数据。

2

添加以下代码以从有关用户搬迁的对话中提取并存储记忆:

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 从会话中提取事实,并将每个事实作为单独的内存文档写入集合。

3

添加以下代码以存储第二个对话的内存,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)
4

要搜索可回答有关用户重定位查询的内存数据,请将以下代码添加到 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索引完成构建。

5

要在不运行语义搜索的情况下返回用户的完整内存历史记录,请将以下代码添加到 main.py文件中:

all_memories = m.get_all(filters={"user_id": "alice"})
for mem in all_memories["results"]:
print(mem["id"], mem["memory"])

提示

要检查存储的内存文档,请浏览Atlasmem0_db.agent_memory 用户界面中的 集合。要学习;了解更多信息,请参阅查看集合。

本节介绍如何将内存存储和检索结合到助手中,以个性化其响应。在助手做出响应之前,它会检索与当前消息最相关的记忆,并将它们添加到系统提示中。响应后,它会存储新的对话回合,以便记忆随着每次交流而增长。

1

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
2

添加以下代码以定义一个函数,该函数生成个性化响应并将新的对话轮次存储为记忆:

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搜索索引。