第五层:记忆系统

📌 核心文件nanobot/memory/store.py
文件位置~/.nanobot/memory/

概述

记忆系统(Memory System)让 Agent 能够长期记住重要信息,超越单个对话会话的限制。

记忆文件结构

~/.nanobot/memory/
├── MEMORY.md         # 长期记忆
└── 2026-02-03.md     # 每日笔记

MEMORY.md - 长期记忆

存储持久化的重要信息:

# 用户信息
- 姓名:张三
- 职业:软件工程师
- 偏好:喜欢 Python,使用 macOS

# 项目信息
- 主项目:nanobot 开发
- 代码路径:~/code/nanobot
- 数据库:PostgreSQL 14

# 其他重要信息
- 每天 9 点开始工作
- 不喜欢过于冗长的解释

每日笔记

按日期自动创建:

# 2026-02-03

## 对话记录
- 讨论了 nanobot 的架构设计
- 创建了学习文档

## 重要决定
- 决定使用 Pydantic 进行配置验证

MemoryStore 实现

class MemoryStore:
    """记忆存储管理器"""
    
    def __init__(self, workspace: Path):
        self.workspace = workspace
        self.memory_dir = workspace / "memory"
        self.memory_dir.mkdir(exist_ok=True)
        
        self.memory_file = self.memory_dir / "MEMORY.md"
        self.daily_notes_dir = self.memory_dir
    
    def get_memory_context(self) -> str:
        """获取记忆内容用于系统提示"""
        parts = []
        
        # 长期记忆
        if self.memory_file.exists():
            content = self.memory_file.read_text(encoding="utf-8")
            if content.strip():
                parts.append(f"## Long-term Memory\n\n{content}")
        
        # 今日笔记
        today = datetime.now().strftime("%Y-%m-%d")
        today_file = self.daily_notes_dir / f"{today}.md"
        if today_file.exists():
            content = today_file.read_text(encoding="utf-8")
            if content.strip():
                parts.append(f"## Today's Notes\n\n{content}")
        
        return "\n\n".join(parts) if parts else ""
    
    def add_to_memory(self, content: str):
        """添加内容到长期记忆"""
        if self.memory_file.exists():
            current = self.memory_file.read_text(encoding="utf-8")
            updated = f"{current}\n\n{content}"
        else:
            updated = content
        
        self.memory_file.write_text(updated, encoding="utf-8")
    
    def add_to_daily(self, content: str, date: str | None = None):
        """添加内容到每日笔记"""
        if date is None:
            date = datetime.now().strftime("%Y-%m-%d")
        
        daily_file = self.daily_notes_dir / f"{date}.md"
        
        if daily_file.exists():
            current = daily_file.read_text(encoding="utf-8")
            updated = f"{current}\n\n{content}"
        else:
            updated = f"# {date}\n\n{content}"
        
        daily_file.write_text(updated, encoding="utf-8")

Agent如何使用记忆

1. 自动加载到上下文

# 在 ContextBuilder.build_system_prompt 中
memory = self.memory.get_memory_context()
if memory:
    system_prompt += f"\n\n# Memory\n\n{memory}"

LLM 看到的系统提示会包含记忆内容。

2. 通过工具读写

Agent 可以主动操作记忆:

读取记忆

{
  "name": "read_file",
  "arguments": {"path": "~/.nanobot/memory/MEMORY.md"}
}

写入记忆

{
  "name": "write_file",
  "arguments": {
    "path": "~/.nanobot/memory/MEMORY.md",
    "content": "用户喜欢简洁的回答..."
  }
}

追加记忆

{
  "name": "exec",
  "arguments": {
    "command": "echo '新的记忆内容' >> ~/.nanobot/memory/MEMORY.md"
  }
}

使用示例

场景 1:记住用户偏好

对话 1

用户:“我喜欢 Python,不喜欢 Java”

Agent:“好的,我会记住你的偏好。”

(Agent 调用工具):

write_file(
    path="~/.nanobot/memory/MEMORY.md",
    content="# 用户偏好\n- 喜欢:Python\n- 不喜欢:Java"
)

对话 2(数天后)

用户:“帮我选一个后端框架”

Agent:“基于你喜欢 Python,我推荐 FastAPI 或 Django…“

(Agent 从系统提示中看到了之前的记忆)

场景 2:项目追踪

今天

用户:“创建了新项目 my-app,使用 React + FastAPI”

Agent 记录到今日笔记:

# 2026-02-03

## 项目
- 创建 my-app
  - 前端:React
  - 后端:FastAPI

明天

用户:“my-app 项目的后端框架是什么?”

Agent:“FastAPI(昨天创建的)”

最佳实践

1. 结构化记忆

# ✅ 好的记忆格式

# 用户信息
- 姓名:...
- 职业:...

# 项目
## project-1
- 路径:~/code/project-1
- 技术栈:Python, FastAPI

## project-2
- 路径:~/code/project-2
- 技术栈:React, Node.js

2. 及时更新

# Agent 在重要时刻自动记录
if user_shared_important_info:
    add_to_memory(info)

if task_completed:
    add_to_daily(f"完成任务:{task_description}")

3. 避免冗余

# ❌ 太详细
用户在 10:23:45 说他喜欢 Python,当时天气晴朗...

# ✅ 简洁
用户偏好:Python

小结

  • ✅ 简单的文件系统存储
  • ✅ 自动集成到上下文
  • ✅ Agent 可主动读写
  • ✅ 支持长期和每日记忆

下一步13-渠道管理.md