本示例展示了如何为智能体使用持久化记忆。

在每次运行时,智能体都可以创建/更新/删除用户记忆。

要启用此功能,请在智能体配置中设置 enable_agentic_memory=True

代码

cookbook/agent_concepts/memory/07_agentic_memory.py
from agno.agent.agent import Agent
from agno.memory.v2.db.sqlite import SqliteMemoryDb
from agno.memory.v2.memory import Memory
from agno.models.openai import OpenAIChat
from rich.pretty import pprint

memory_db = SqliteMemoryDb(table_name="memory", db_file="tmp/memory.db")

# 无需设置模型,它会被智能体设置为智能体的模型
memory = Memory(db=memory_db)

# 重置此示例的记忆
memory.clear()

john_doe_id = "john_doe@example.com"

agent = Agent(
    model=OpenAIChat(id="gpt-4o-mini"),
    memory=memory,
    enable_agentic_memory=True,
)

agent.print_response(
    "My name is John Doe and I like to hike in the mountains on weekends.",
    stream=True,
    user_id=john_doe_id,
)

agent.print_response("What are my hobbies?", stream=True, user_id=john_doe_id)

memories = memory.get_user_memories(user_id=john_doe_id)
print("Memories about John Doe:")
pprint(memories)


agent.print_response(
    "Remove all existing memories of me.",
    stream=True,
    user_id=john_doe_id,
)

memories = memory.get_user_memories(user_id=john_doe_id)
print("Memories about John Doe:")
pprint(memories)

agent.print_response(
    "My name is John Doe and I like to paint.", stream=True, user_id=john_doe_id
)

memories = memory.get_user_memories(user_id=john_doe_id)
print("Memories about John Doe:")
pprint(memories)


agent.print_response(
    "I don't pain anymore, i draw instead.", stream=True, user_id=john_doe_id
)

memories = memory.get_user_memories(user_id=john_doe_id)

print("Memories about John Doe:")
pprint(memories)

使用方法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

设置您的 API 密钥

export GOOGLE_API_KEY=xxx
3

安装库

pip install -U agno google-generativeai
4

运行示例

python cookbook/agent_concepts/memory/07_agentic_memory.py