源文件:chapter3/user-memory/README.md 用户记忆系统 - 进阶对话式记忆管理 一套精巧的用户记忆系统,采用对话与记忆处理分离的架构,支持多种 LLM 提供商和多种记忆存储模式。基于 React 模式与工具化方法构建,遵循面向生产级 AI Agent 的最佳实践。 核心特性 分离式架构:对话 Agent 与后台记忆处理器解耦 多种记忆模式:从简单的笔记到带完整上下文的高级 JSON 卡片 多提供商支持:Kimi/Moonshot、SiliconFlow、豆包、OpenRouter(含 Gemini 2.
源文件:chapter3/user-memory/README.md
一套精巧的用户记忆系统,采用对话与记忆处理分离的架构,支持多种 LLM 提供商和多种记忆存储模式。基于 React 模式与工具化方法构建,遵循面向生产级 AI Agent 的最佳实践。
git clone <repository-url> cd chapter3/user-memory
pip install -r requirements.txt
cp env.example .env # 编辑 .env,填入你的 API 密钥
# Kimi/Moonshot(默认) export MOONSHOT_API_KEY="your-api-key-here" # SiliconFlow export SILICONFLOW_API_KEY="your-api-key-here" # 豆包 export DOUBAO_API_KEY="your-api-key-here" # OpenRouter export OPENROUTER_API_KEY="your-api-key-here"
python quickstart.py
它会演示:
python main.py --mode interactive --user your_name
交互模式下的可用命令:
memory - 显示当前记忆状态process - 手动触发记忆处理save - 立即保存记忆reset - 开始新的对话会话quit/exit - 不保存退出python main.py --mode demo --memory-mode enhanced_notes
python main.py --mode evaluation --memory-mode advanced_json_cards
系统采用分离式架构设计:
┌─────────────────────────────────────────────────────────┐ │ User Interface │ └────────────────────┬───────────────────────┬─────────────┘ │ │ ┌────────────▼─────────┐ ┌─────────▼──────────┐ │ Conversational Agent │ │ Background Memory │ │ │ │ Processor │ │ • Handles dialogue │ │ • Analyzes context │ │ • Reads memory │ │ • Updates memory │ │ • Streams responses │ │ • Tool-based ops │ └────────────┬─────────┘ └─────────┬──────────┘ │ │ ┌────────────▼───────────────────────▼──────────┐ │ Memory Manager │ │ (Notes/JSON Cards Storage) │ └───────────────────────────────────────────────┘
ConversationalAgent(conversational_agent.py)
BackgroundMemoryProcessor(background_memory_processor.py)
UserMemoryAgent(agent.py)
MemoryManager(memory_manager.py)
notes)基础的事实与偏好存储:
- User email: john@example.com - Favorite color: blue - Works at: TechCorp
enhanced_notes)带上下文的完整段落:
User works at TechCorp as a senior software engineer, specializing in machine learning for the past 3 years. They lead a team of 5 developers and are passionate about open source contributions.
json_cards)层次化结构化存储:
{ "personal": { "contact": { "email": { "value": "john@example.com", "updated_at": "2024-01-15T10:30:00" } } } }
advanced_json_cards)带元数据的完整记忆卡对象:
{ "medical": { "doctor_primary": { "backstory": "User shared their primary care physician details during health discussion", "date_created": "2024-01-15 10:30:00", "person": "John Smith (primary)", "relationship": "primary account holder", "doctor_name": "Dr. Sarah Johnson", "specialty": "Internal Medicine", "clinic": "City Medical Center" } } }
带自动记忆处理的实时对话:
python main.py --mode interactive \ --user john_doe \ --memory-mode enhanced_notes \ --conversation-interval 2 # 每 2 轮对话处理一次
对记忆系统能力的结构化演示:
python main.py --mode demo \ --provider siliconflow \ --memory-mode json_cards
基于测试用例、带打分的评测:
python main.py --mode evaluation \ --memory-mode advanced_json_cards \ --provider kimi
| 提供商 | 模型 | 最适用于 |
|---|---|---|
| Kimi/Moonshot | kimi-k3 | 中文、通用任务 |
| SiliconFlow | Qwen3-235B-A22B-Thinking | 高性能、推理 |
| 豆包 | doubao-seed-1-6-thinking | 字节生态、推理 |
| OpenRouter | Gemini 2.5 Pro、GPT-5、Claude Sonnet 4 | 多种顶级模型 |
# 使用 SiliconFlow python main.py --provider siliconflow --model "Qwen/Qwen3-235B-A22B-Thinking-2507" # 通过 OpenRouter 使用 Gemini python main.py --provider openrouter --model "google/gemini-3.5-flash" # 使用豆包 python main.py --provider doubao --model "doubao-seed-1-6-thinking-250715"
from conversational_agent import ConversationalAgent, ConversationConfig from config import MemoryMode # 初始化 Agent agent = ConversationalAgent( user_id="user123", provider="kimi", config=ConversationConfig( enable_memory_context=True, temperature=0.7 ), memory_mode=MemoryMode.ENHANCED_NOTES ) # 对话 response = agent.chat("Hi, I'm Alice and I work at TechCorp") print(response)
from background_memory_processor import BackgroundMemoryProcessor, MemoryProcessorConfig # 初始化处理器 processor = BackgroundMemoryProcessor( user_id="user123", provider="kimi", config=MemoryProcessorConfig( conversation_interval=2, # 每 2 轮处理一次 enable_auto_processing=True ), memory_mode=MemoryMode.JSON_CARDS ) # 启动后台处理 processor.start_background_processing() # 手动处理 results = processor.process_recent_conversations()
from agent import UserMemoryAgent, UserMemoryConfig # 用工具初始化 Agent agent = UserMemoryAgent( user_id="user123", provider="siliconflow", config=UserMemoryConfig( enable_memory_updates=True, memory_mode=MemoryMode.ADVANCED_JSON_CARDS ) ) # 执行带工具调用的任务 result = agent.execute_task( "Remember that I prefer Python and my email is john@example.com" ) # 访问工具调用历史 for call in result['tool_calls']: print(f"Tool: {call.tool_name}") print(f"Args: {call.arguments}") print(f"Result: {call.result}")
系统与 user-memory-evaluation 集成以进行系统化测试:
# 用测试用例运行评测 python main.py --mode evaluation --memory-mode advanced_json_cards # 评测模式下: # 1. 选择测试用例 ID # 2. 系统处理对话历史 # 3. 生成对用户问题的回答 # 4. 获得评测分数与反馈
# 提供商选择 PROVIDER=kimi # 或 siliconflow、doubao、openrouter # 模型配置 MODEL_TEMPERATURE=0.3 MODEL_MAX_TOKENS=4096 # 记忆设置 MEMORY_MODE=enhanced_notes MAX_MEMORY_ITEMS=100 MEMORY_UPDATE_TEMPERATURE=0.2 # 处理配置 SESSION_TIMEOUT=3600 MAX_CONTEXT_LENGTH=8000 # 存储路径 MEMORY_STORAGE_DIR=data/memories CONVERSATION_HISTORY_DIR=data/conversations
python main.py \ --mode interactive \ --user custom_user \ --memory-mode advanced_json_cards \ --provider openrouter \ --model "google/gemini-3.5-flash" \ --conversation-interval 3 \ --background-processing True \ --no-verbose
user-memory/ ├── main.py # 主入口,含全部模式 ├── quickstart.py # 快速演示脚本 ├── agent.py # 带 React 模式的 UserMemoryAgent ├── conversational_agent.py # 纯对话处理器 ├── background_memory_processor.py # 后台记忆处理 ├── memory_manager.py # 记忆存储后端 ├── config.py # 配置与设置 ├── conversation_history.py # 对话跟踪 ├── memory_operation_formatter.py # 操作展示工具 ├── run_evaluation.py # 评测运行器 ├── locomo_benchmark.py # LOCOMO 基准集成 ├── PROVIDERS.md # 提供商文档 ├── requirements.txt # Python 依赖 ├── env.example # 环境模板 ├── data/ # 数据存储 │ ├── memories/ # 用户记忆文件 │ └── conversations/ # 对话历史 └── logs/ # 应用日志
# 快速端到端演示(分离的对话 + 记忆处理) python quickstart.py # 离线记忆整合/去重(无需 API 调用) python -c "from memory_manager import NotesMemoryManager; m=NotesMemoryManager('smoke'); print(m.consolidate_memories())"
config.py 中更新 API 密钥配置agent.py 和 conversational_agent.py 中添加 provider 分支main.py 中更新命令行选项PROVIDERS.md 文档中补充说明memory_manager.py 中扩展 BaseMemoryManagerconfig.py 的 MemoryMode 枚举中添加[在此填写你的许可证]
[贡献指南]
[支持信息]
This experiment now supports a universal OpenRouter fallback for its chat LLM.
MOONSHOT_API_KEY / KIMI_API_KEY / OPENAI_API_KEY / DOUBAO_API_KEY …) is present, behavior is unchanged.OPENROUTER_API_KEY is set, the chat LLM is automatically routed through OpenRouter (https://openrouter.ai/api/v1). Model names are mapped automatically: gpt-*/o1-* → openai/…, claude-* → anthropic/claude-opus-4.8, kimi-* → moonshotai/kimi-k2.6, ids already containing / are kept as-is, and other provider-native ids (e.g. doubao-*) fall back to openai/gpt-5.6-luna. Set OPENROUTER_MODEL to force a specific OpenRouter model id.Add OPENROUTER_API_KEY=... to your .env (see env.example) to enable it.