"""
此示例演示如何将 Memory 类与 MongoDB 存储一起使用。
"""
import asyncio
import os
from agno.agent.agent import Agent
from agno.memory.v2.db.mongodb import MongoMemoryDb
from agno.memory.v2.memory import Memory
from agno.models.openai.chat import OpenAIChat
# 从环境变量获取 MongoDB 连接字符串
# 格式: mongodb://username:password@localhost:27017/
mongo_url = "mongodb://localhost:27017/"
database_name = "agno_memory"
# 创建 MongoDB 内存数据库
memory_db = MongoMemoryDb(
connection_string=mongo_url,
database_name=database_name,
collection_name="memories" # 在数据库中使用的集合名称
)
# 创建带有 MongoDB 后端的内存实例
memory = Memory(db=memory_db)
# 如果集合不存在,它将在此创建
memory.clear()
# 创建带有内存的代理
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
memory=memory,
enable_user_memories=True,
)
async def run_example():
# 使用带有 MongoDB 支持的内存的代理
await agent.aprint_response(
"My name is Jane Smith and I enjoy painting and photography.",
user_id="jane@example.com",
)
await agent.aprint_response(
"What are my creative interests?",
user_id="jane@example.com",
)
# 显示存储在 MongoDB 中的记忆
memories = memory.get_user_memories(user_id="jane@example.com")
print("Memories stored in MongoDB:")
for i, m in enumerate(memories):
print(f"{i}: {m.memory}")
if __name__ == "__main__":
asyncio.run(run_example())
创建虚拟环境
打开 Terminal
并创建一个 python 虚拟环境。
python3 -m venv .venv
source .venv/bin/activate
设置环境变量
export OPENAI_API_KEY=xxx
安装库
pip install -U agno openai pymongo
运行示例
python၃ cookbook/agent_concepts/memory/mongodb_memory.py