qwen_agent/.features/memory/MEMORY.md
2026-06-01 11:51:21 +08:00

56 lines
3.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
feature: "memory"
scope: "Agent 长期记忆能力(基于 Mem0 + pgvector跨会话回忆与事实提取存储"
updated_at: "2026-06-01"
status: active
---
# Memory记忆功能
## 当前状态
Agent 的长期记忆能力,底层使用 **Mem0** 库 + **pgvector**PostgreSQL 向量存储)。
在 agent 执行前 `recall` 相关记忆并注入 system prompt在执行后于后台线程异步提取并存储新事实。
`(user_id, agent_id)` 多租户隔离,每个 `agent_id` 一张 `mem0_{agent_id}` 集合表。
> 注意API/配置字段历史上叫 `memori`,为兼容性保留命名,内部实际用的是 **Mem0**。
## 配置开关
| 层级 | 字段 | 默认 | 位置 |
|------|------|------|------|
| 全局总开关 | `MEM0_ENABLED` (env) | `true` | `utils/settings.py:80` |
| Agent 配置 | `enable_memori: bool` | `False` | `agent/agent_config.py:47` |
| API 请求 | `enable_memory: bool` | `False` | `utils/api_models.py:56` |
| 召回数量 | `memori_semantic_search_top_k: int` | `20` | `agent/agent_config.py:48` |
| 召回数量(env) | `MEM0_SEMANTIC_SEARCH_TOP_K` | `20` | `utils/settings.py:84` |
| 连接池大小 | `MEM0_POOL_SIZE` (env) | `50` | `utils/settings.py:61` |
开启路径V1 走请求体 `enable_memory`V2 走 bot 配置 `enable_memory`;两者都受全局 `MEM0_ENABLED` 限制。
中间件注册在 `agent/deep_assistant.py:270``if config.enable_memori:`)。
## 核心文件
- `agent/mem0_manager.py` — Mem0 客户端管理器:实例创建/LRU 缓存(最多 50、连接池管理、`recall_memories` / `add_memory` / `delete_all`、多租户隔离、`CustomMem0Embedding`、`json_repair` 补丁
- `agent/mem0_middleware.py` — 中间件:`before_agent` 召回并写入 `config._mem0_context`(行 114/155`after_agent` 后台异步提取存储
- `agent/mem0_config.py` — Mem0 配置类user/agent/session id、记忆提示模板、自定义提取 prompt 加载(`PreMemoryPrompt` hook
- `routes/memory.py` — 内存管理 APIGET/POST/DELETE供前端管理用户记忆
- `drop_mem0_tables.py` — 清理脚本,删除所有 `mem0_*` 表(重置/清脏数据)
## 数据流
**写入**User+Assistant 消息 → `after_agent`(后台线程)→ `add_memory``Mem0.add()`LLM 提取事实)→ pgvector 向量化存入 `mem0_{agent_id}`
**读取**User query → `before_agent``recall_memories``Mem0.search()`(向量相似 top_k→ 格式化后写入 `config._mem0_context` → 注入 system prompt也供思考功能 [[../thinking/MEMORY|thinking]] 使用)。
## 关键设计决策
- 复用项目已加载的 embedding 模型(`CustomMem0Embedding`),避免 Mem0 重复加载 SentenceTransformer → `decisions/2026-06-custom-embedding.md`
- 连接池主动释放 + LRU 缓存实例,防连接池耗尽 → `decisions/2026-06-connection-pool.md`
## Gotchas开发必读
- **命名陷阱**:配置叫 `enable_memori`(无 yAPI 叫 `enable_memory`,内部实现是 Mem0三个名字别混。
- **连接池耗尽**Mem0 PGVector `__init__` 取连接、`__del__` 释放;必须在每次操作后主动 `_release_connection()`,否则高并发会打满 `MEM0_POOL_SIZE`
- **JSON 脆弱**LLM 提取事实返回的 JSON 常有尾逗号/单引号,已 monkey patch 成 `json_repair.loads`,不要改回原生解析。
- **表膨胀**:每个 `agent_id` 一张表,多 bot 长期运行会产生大量表,定期用 `drop_mem0_tables.py` 清理。
- **Embedding 维度**`paraphrase-multilingual-MiniLM-L12-v2`384 维;换模型需同步 pgvector 列维度,否则写入报错。
## 索引
- 设计决策:`decisions/`
- 变更历史:`changelog/`
- 相关文档:`docs/`