refactor: 优化兴趣值管理器和统一调度器,增强任务执行的并发控制
This commit is contained in:
@@ -437,6 +437,11 @@ class MemoryManager:
|
||||
logger.info(
|
||||
f"搜索完成: 找到 {len(filtered_memories)} 条记忆 (策略={strategy})"
|
||||
)
|
||||
|
||||
# 强制激活被检索到的记忆(核心功能)
|
||||
if filtered_memories:
|
||||
await self._auto_activate_searched_memories(filtered_memories)
|
||||
|
||||
return filtered_memories[:top_k]
|
||||
|
||||
except Exception as e:
|
||||
@@ -536,6 +541,8 @@ class MemoryManager:
|
||||
"access_count": activation_info.get("access_count", 0) + 1,
|
||||
})
|
||||
|
||||
# 同步更新 memory.activation 字段,确保数据一致性
|
||||
memory.activation = new_activation
|
||||
memory.metadata["activation"] = activation_info
|
||||
memory.last_accessed = now
|
||||
|
||||
@@ -562,6 +569,49 @@ class MemoryManager:
|
||||
logger.error(f"激活记忆失败: {e}", exc_info=True)
|
||||
return False
|
||||
|
||||
async def _auto_activate_searched_memories(self, memories: list[Memory]) -> None:
|
||||
"""
|
||||
自动激活被搜索到的记忆
|
||||
|
||||
Args:
|
||||
memories: 被检索到的记忆列表
|
||||
"""
|
||||
try:
|
||||
# 获取配置参数
|
||||
base_strength = getattr(self.config, "auto_activate_base_strength", 0.1)
|
||||
max_activate_count = getattr(self.config, "auto_activate_max_count", 5)
|
||||
|
||||
# 激活强度根据记忆重要性调整
|
||||
activate_tasks = []
|
||||
for i, memory in enumerate(memories[:max_activate_count]):
|
||||
# 重要性越高,激活强度越大
|
||||
strength = base_strength * (0.5 + memory.importance)
|
||||
|
||||
# 创建异步激活任务
|
||||
task = self.activate_memory(memory.id, strength=strength)
|
||||
activate_tasks.append(task)
|
||||
|
||||
if i >= max_activate_count - 1:
|
||||
break
|
||||
|
||||
# 并发执行激活任务(但不等待所有完成,避免阻塞搜索)
|
||||
if activate_tasks:
|
||||
import asyncio
|
||||
# 使用 asyncio.gather 但设置较短的 timeout
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.gather(*activate_tasks, return_exceptions=True),
|
||||
timeout=2.0 # 2秒超时,避免阻塞主流程
|
||||
)
|
||||
logger.debug(f"自动激活 {len(activate_tasks)} 条记忆完成")
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(f"自动激活记忆超时,已激活部分记忆")
|
||||
except Exception as e:
|
||||
logger.warning(f"自动激活记忆失败: {e}")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"自动激活搜索记忆失败: {e}")
|
||||
|
||||
def _get_related_memories(self, memory_id: str, max_depth: int = 1) -> list[str]:
|
||||
"""
|
||||
获取相关记忆 ID 列表(旧版本,保留用于激活传播)
|
||||
|
||||
@@ -199,6 +199,17 @@ class Memory:
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> Memory:
|
||||
"""从字典创建记忆"""
|
||||
metadata = data.get("metadata", {})
|
||||
|
||||
# 优先从 metadata 中获取激活度信息
|
||||
activation_level = 0.0
|
||||
activation_info = metadata.get("activation", {})
|
||||
if activation_info and "level" in activation_info:
|
||||
activation_level = activation_info["level"]
|
||||
else:
|
||||
# 备选:使用直接的 activation 字段
|
||||
activation_level = data.get("activation", 0.0)
|
||||
|
||||
return cls(
|
||||
id=data["id"],
|
||||
subject_id=data["subject_id"],
|
||||
@@ -206,13 +217,13 @@ class Memory:
|
||||
nodes=[MemoryNode.from_dict(n) for n in data["nodes"]],
|
||||
edges=[MemoryEdge.from_dict(e) for e in data["edges"]],
|
||||
importance=data.get("importance", 0.5),
|
||||
activation=data.get("activation", 0.0),
|
||||
activation=activation_level, # 使用统一的激活度值
|
||||
status=MemoryStatus(data.get("status", "staged")),
|
||||
created_at=datetime.fromisoformat(data["created_at"]),
|
||||
last_accessed=datetime.fromisoformat(data.get("last_accessed", data["created_at"])),
|
||||
access_count=data.get("access_count", 0),
|
||||
decay_factor=data.get("decay_factor", 1.0),
|
||||
metadata=data.get("metadata", {}),
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
def update_access(self) -> None:
|
||||
|
||||
@@ -552,7 +552,7 @@ class MemoryTools:
|
||||
for memory_id in sorted_memory_ids:
|
||||
memory = self.graph_store.get_memory_by_id(memory_id)
|
||||
if memory:
|
||||
# 综合评分:相似度(60%) + 重要性(30%) + 时效性(10%)
|
||||
# 综合评分:相似度(40%) + 重要性(20%) + 时效性(10%) + 激活度(30%)
|
||||
similarity_score = final_scores[memory_id]
|
||||
importance_score = memory.importance
|
||||
|
||||
@@ -567,11 +567,20 @@ class MemoryTools:
|
||||
age_days = (now - memory_time).total_seconds() / 86400
|
||||
recency_score = 1.0 / (1.0 + age_days / 30) # 30天半衰期
|
||||
|
||||
# 综合分数
|
||||
# 获取激活度分数(从metadata中读取,兼容memory.activation字段)
|
||||
activation_info = memory.metadata.get("activation", {})
|
||||
activation_score = activation_info.get("level", memory.activation)
|
||||
|
||||
# 如果metadata中没有激活度信息,使用memory.activation作为备选
|
||||
if activation_score == 0.0 and memory.activation > 0.0:
|
||||
activation_score = memory.activation
|
||||
|
||||
# 综合分数 - 加入激活度影响
|
||||
final_score = (
|
||||
similarity_score * 0.6 +
|
||||
importance_score * 0.3 +
|
||||
recency_score * 0.1
|
||||
similarity_score * 0.4 + # 向量相似度 40%
|
||||
importance_score * 0.2 + # 重要性 20%
|
||||
recency_score * 0.1 + # 时效性 10%
|
||||
activation_score * 0.3 # 激活度 30% ← 新增
|
||||
)
|
||||
|
||||
memories_with_scores.append((memory, final_score))
|
||||
|
||||
Reference in New Issue
Block a user