本项目的记忆系统是 Alias 智能代理平台的核心组件,负责管理用户画像(User Profiling)和工具使用经验(Tool Memory)。该系统基于 mem0 和 ReMe 两个开源框架构建,提供了一套完整的记忆存储、检索和演进机制。
┌─────────────────────────────────────────────────────────────────┐
│ API Layer (FastAPI) │
│ /alias_memory_service/* REST API Endpoints │
├─────────────────────────────────────────────────────────────────┤
│ Service Layer │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ AsyncUserProfilingMemory │ ToolMemory (ReMe) │ │
│ └─────────────────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────────┤
│ Memory Pool Layer │
│ ┌──────────────────┬──────────────────┬──────────────────┐ │
│ │ Candidate Pool │ UserProfiling │ UserInfo Pool │ │
│ │ (候选池) │ Pool │ (用户信息池) │ │
│ │ │ (用户画像池) │ │ │
│ └──────────────────┴──────────────────┴──────────────────┘ │
├─────────────────────────────────────────────────────────────────┤
│ Base Memory Layer │
│ BaseAsyncVectorMemory (mem0) │
├─────────────────────────────────────────────────────────────────┤
│ Storage Layer │
│ ┌──────────────────┬──────────────────┬──────────────────┐ │
│ │ Qdrant │ SQLite │ Redis │ │
│ │ (向量存储) │ (历史记录) │ (缓存/可选) │ │
│ └──────────────────┴──────────────────┴──────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
BaseMemory (ABC)
│
┌───────────────┴───────────────┐
▼ ▼
AsyncUserProfilingMemory ToolMemory
│ │
┌─────────┼─────────┐ │
▼ ▼ ▼ ▼
Candidate UserProfiling UserInfo ReMeApp
Pool Pool Pool (工具记忆)
│ │ │
└─────────┼───────────┘
▼
BaseAsyncVectorMemory (mem0)
│
┌─────────┼─────────┐
▼ ▼ ▼
Qdrant SQLite Embedding
(向量库) (历史) (LLM)
用户画像记忆系统基于 mem0 框架构建,通过收集和处理用户行为数据来构建全面的用户画像。
| 池名称 | 用途 | 设计特点 |
|---|---|---|
| **Candidate Pool (候选池)** | 临时存储待验证的用户偏好记忆 | 基于访问频率和时间衰减计算评分 |
| **User Profiling Pool (画像池)** | 存储已确认的稳定用户偏好 | 只有高质量记忆才能进入 |
| **User Info Pool (信息池)** | 存储从对话中提取的基本用户事实 | 个人信息、背景等 |
候选池中的每条记忆都会被动态评分,评分公式如下:
# 时间评分 (越近越高)
time_score = exp(-temperature * time_diff_hours)
normalized_time = time_score / max_time_diff
# 访问次数评分 (访问越多越高)
normalized_visit = 1 / (1 + exp(-visited_count / 10))
# 综合评分
score = 0.7 * normalized_time + 0.3 * normalized_visit
设计思想:
用户交互 → 候选池 → 评分计算 → 阈值判断 → 画像池
│
▼
threshold = 0.95 * (1 - 1/n)
(n = 候选池中记忆数量)
动态阈值设计:
async def get_highest_score_memory_by_threshold(self, candidates):
threshold = 0.95 * (1.0 - (1 / len(candidates)))
# 只有得分超过阈值的记忆才能晋升
工具记忆基于 ReMe 框架构建,管理工具执行历史并提供使用指南。
工具调用 → 记录结果 → 阈值检查 → 自动摘要 → 指南生成
| 功能 | 描述 |
|---|---|
| **结果存储** | 记录工具名称、输入参数、输出结果、执行状态、耗时 |
| **自动摘要** | 基于阈值触发历史记录的智能摘要 |
| **经验检索** | 根据工具名称检索历史使用模式和最佳实践 |
class ToolMemory(BaseMemory):
def __init__(
self,
summary_time_threshold: int = 300, # 时间阈值: 5分钟
summary_count_threshold: int = 5, # 数量阈值: 5次调用
):
触发条件(满足任一即触发):
action_handlers = {
"LIKE": # 点赞
"DISLIKE": # 踩
"CANCEL_LIKE": # 取消点赞
"CANCEL_DISLIKE": # 取消踩
"EDIT_ROADMAP": # 编辑执行路线图
"EDIT_FILE": # 编辑文件
"START_CHAT": # 开始对话
"FOLLOWUP_CHAT": # 追问
"BREAK_CHAT": # 中断对话
"COLLECT_SESSION": # 收藏会话
"UNCOLLECT_SESSION": # 取消收藏会话
"COLLECT_TOOL": # 收藏工具调用
"UNCOLLECT_TOOL": # 取消收藏工具调用
}
用户行为 → record_action() → 行为分发器 → 具体处理器 → 记忆更新
│
├── LIKE/DISLIKE → 偏好提取
├── EDIT_* → 编辑偏好提取
├── *_CHAT → 对话偏好提取
└── COLLECT_* → 工作流提取
系统使用专门设计的 Prompt 从用户行为中提取信息:
| 行为类型 | 提取内容 |
|---|---|
| SESSION_SUMMARY | 任务描述、问题分类 |
| AGENT_ROADMAP | 多Agent协作路线图 |
| AGENT_KEY_WORKFLOW | 高层工作流摘要 |
| SUBTASK_ROADMAP | 子任务执行路径 |
| EXTRACT_USER_INFO | 用户基本信息 |
| EXTRACT_USER_EVENT | 用户事件偏好 |
class BaseAsyncVectorMemory(MemoryBase):
def __init__(self, config: MemoryConfig):
# 嵌入模型 - 用于语义向量化
self.embedding_model = EmbedderFactory.create(...)
# 向量存储 - Qdrant
self.vector_store = VectorStoreFactory.create(...)
# LLM - 用于记忆推理
self.llm = LlmFactory.create(...)
# 历史数据库 - SQLite
self.db = SQLiteManager(config.history_db_path)
add()
│
┌────────────┼────────────┐
▼ ▼ ▼
直接添加 推理添加 图谱更新
(infer=False) (infer=True) (可选)
│ │
│ ┌───────┴───────┐
│ ▼ ▼
│ 提取事实 搜索已有记忆
│ │ │
│ └───────┬───────┘
│ ▼
│ LLM推理决策
│ (ADD/UPDATE/DELETE)
│ │
└────────────┼────────────┐
▼ ▼
向量存储 历史记录
(Qdrant) (SQLite)
async def search(self, query, user_id, limit=10, threshold=0.3):
# 1. 生成查询向量
query_embedding = await asyncio.to_thread(
self.embedding_model.embed, query
)
# 2. 向量相似度搜索
results = await self._search_vector_store(
query, filters, limit, threshold
)
# 3. 更新访问元数据(用于评分)
await self._update_metadata(memory_ids)
return results
class AliasLongTermMemory(LongTermMemoryBase):
"""Agent 使用的长期记忆接口"""
def __init__(self, session_service: SessionService):
self.session_service = session_service
self.memory_client = MemoryClient()
# 记录对话到记忆
async def record(self, msgs: list[Msg]) -> None
# 检索用户画像
async def retrieve(self, query) -> Optional[str]
# 检索工具使用经验
async def tool_memory_retrieve(self, query: str) -> ToolResponse
# 主动记录重要信息
async def record_to_memory(self, thinking, content) -> ToolResponse
# 基于关键词检索记忆
async def retrieve_from_memory(self, keywords) -> ToolResponse
class MemoryClient(BaseClient):
"""通过 HTTP API 访问记忆服务"""
# 健康检查
async def is_available() -> bool
# 记录用户行为
async def record_action(action: Action) -> dict
# 检索用户画像
async def retrieve_user_profiling(uid, query, limit, threshold)
# 检索工具记忆
async def retrieve_tool_memory(uid, query)
# 添加长期记忆
async def add_to_longterm_memory(uid, content, session_id)
| 原则 | 实现 |
|---|---|
| **渐进式记忆** | 通过候选池→画像池的演进机制,避免噪声进入核心记忆 |
| **时效性优先** | 评分公式中时间权重(70%)高于频率权重(30%) |
| **动态阈值** | 阈值随候选数量动态调整,平衡选择性与包容性 |
| **异步优先** | 全异步架构,支持高并发场景 |
| **解耦设计** | 用户画像与工具记忆独立模块,互不干扰 |
| **插件化存储** | 支持 Qdrant、Redis 等多种后端 |
┌─────────────────────┐
│ 高质量用户画像 │
│ (User Profiling) │
└─────────────────────┘
▲
│ 演进晋升
┌─────────────────────┐
│ 候选池筛选 │
│ (Candidate Pool) │
└─────────────────────┘
▲
│ 多源输入
┌─────────────┬───────────┼───────────┬─────────────┐
│ │ │ │ │
LIKE/DISLIKE EDIT CHAT COLLECT TOOL_USE
│ │ │ │ │
└─────────────┴───────────┴───────────┴─────────────┘
用户行为流
alias/src/alias/
├── memory_service/ # 记忆服务核心
│ ├── basememory.py # 抽象基类定义
│ ├── user_profiling_memory.py # 用户画像记忆实现
│ ├── tool_memory.py # 工具记忆实现
│ ├── memory_base/ # 记忆基础设施
│ │ ├── base_vec_memory.py # 向量记忆基类 (mem0)
│ │ ├── candidate_pool.py # 候选池实现
│ │ ├── userprofiling_pool.py# 画像池实现
│ │ ├── userinfo_pool.py # 信息池实现
│ │ ├── storage.py # SQLite 存储管理
│ │ └── prompt.py # LLM Prompt 模板
│ └── service/ # FastAPI 服务
│ └── api/routers/ # API 路由
│ ├── user_profiling.py
│ └── tool_memory.py
└── agent/memory/ # Agent 记忆接口
├── longterm_memory.py # 长期记忆封装
└── longterm_memory_utils.py # 工具函数
| 框架 | 用途 | 项目地址 |
|---|---|---|
| **mem0** | 用户画像记忆的核心引擎 | https://github.com/mem0ai/mem0 |
| **ReMe** | 工具记忆管理系统 | https://github.com/agentscope-ai/ReMe |
| **Qdrant** | 向量数据库存储 | https://qdrant.tech/ |
| **FastAPI** | API 服务框架 | https://fastapi.tiangolo.com/ |
本项目的记忆系统采用了创新的双层记忆架构(用户画像 + 工具经验),通过候选池→画像池的演进机制确保记忆质量,利用动态阈值和时间衰减评分实现智能筛选。系统充分利用了 LLM 的语义理解能力进行事实提取和记忆管理,同时保持了良好的架构解耦和异步性能。这种设计使得智能代理能够持续学习和适应用户偏好,提供更加个性化的服务体验。
还没有人回复