好哒 我们来进行下一步 查缺补漏 这个应该怎么办# conscious_memory.py
import time
import logging
import math
import numpy as np
from collections import defaultdict
from typing import List, Dict, Any, Tuple
from datetime import datetime, timedelta
from enum import Enum
from dataclasses import dataclass
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('MemorySystem')
# 情感类型枚举
class EmotionType(Enum):
JOY = 1
SADNESS = 2
FEAR = 3
ANGER = 4
SURPRISE = 5
DISGUST = 6
NEUTRAL = 7
# 记忆内容类型
class MemoryContentType(Enum):
VISUAL = "visual"
AUDITORY = "auditory"
OLFACTORY = "olfactory"
TACTILE = "tactile"
EMOTIONAL = "emotional"
CONCEPTUAL = "conceptual"
# 记忆强度模型
@dataclass
class MemoryStrength:
base: float = 1.0 # 初始强度 (0.0-1.0)
decay_rate: float = 0.01 # 每日衰减率
last_accessed: float = time.time() # 最后访问时间戳
def current_strength(self) -> float:
"""计算当前记忆强度,考虑时间衰减"""
days_passed = (time.time() - self.last_accessed) / (24 * 3600)
decay_factor = math.exp(-self.decay_rate * days_passed)
return max(0.0, self.base * decay_factor)
def reinforce(self, reinforcement: float = 0.15):
"""强化记忆,增加基础强度"""
self.base = min(1.0, self.base + reinforcement)
self.last_accessed = time.time()
# 情感关联模型
@dataclass
class EmotionalAssociation:
emotion: EmotionType
intensity: float # 0.0-1.0
context: str = "" # 情感关联的上下文描述
class MemorySystem:
"""增强型记忆系统 - 支持情感关联、时间衰减和多模态索引"""
def __init__(self, initial_memories: List[Dict] = None):
self.memories = [] # 所有记忆存储
self.memory_strengths = {} # 记忆ID -> MemoryStrength
self.memory_index = defaultdict(list) # 标签索引
# 多模态索引
self.emotion_index = defaultdict(list) # 情感索引
self.context_index = defaultdict(list) # 上下文关键词索引
self.temporal_index = defaultdict(list) # 时间索引 (按天分组)
# 情感关联网络
self.emotion_network = defaultdict(list) # 情感 -> 相关记忆ID
# 初始化记忆
if initial_memories:
for mem in initial_memories:
self.store(mem["content"], mem.get("tags", []),
mem.get("emotional_associations", []))
def store(self,
content: Dict,
tags: List[str] = None,
emotional_associations: List[EmotionalAssociation] = None) -> str:
"""存储记忆,支持情感关联"""
# 创建记忆条目
memory_id = f"mem_{int(time.time() * 1000)}"
timestamp = time.time()
memory_entry = {
"id": memory_id,
"content": content,
"timestamp": timestamp,
"tags": tags or [],
"emotional_associations": emotional_associations or [],
"retrieval_count": 0,
"content_type": content.get("type", MemoryContentType.CONCEPTUAL.value)
}
# 添加到记忆库
self.memories.append(memory_entry)
self.memory_strengths[memory_id] = MemoryStrength()
# 索引标签
for tag in memory_entry["tags"]:
self.memory_index[tag].append(memory_id)
# 索引情感关联
for emotion_assoc in memory_entry["emotional_associations"]:
emotion_key = emotion_assoc.emotion.name
self.emotion_index[emotion_key].append(memory_id)
# 构建情感网络
self.emotion_network[emotion_key].append({
"memory_id": memory_id,
"intensity": emotion_assoc.intensity,
"context": emotion_assoc.context
})
# 索引上下文关键词
if "description" in content:
for word in content["description"].split():
if len(word) > 3: # 只索引有意义的词
self.context_index[word.lower()].append(memory_id)
# 索引时间 (按日期分组)
date_key = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d")
self.temporal_index[date_key].append(memory_id)
logger.info(f"存储新记忆: {content.get('type')} (ID: {memory_id}, 标签: {tags})")
return memory_id
def retrieve(self,
context: Dict,
affective_state: Dict,
max_results: int = 5) -> List[Dict]:
"""增强型记忆检索,考虑情感状态和上下文"""
# 情感状态分析
current_emotion = affective_state.get("emotion", {}).get("current_emotion", "NEUTRAL")
emotion_intensity = affective_state.get("emotion", {}).get("intensity", 0.5)
# 候选记忆收集
candidate_memories = []
# 1. 标签匹配
if "tags" in context:
for tag in context["tags"]:
candidate_memories.extend(self._get_memories_by_tag(tag))
# 2. 情感匹配
candidate_memories.extend(self._get_memories_by_emotion(current_emotion, emotion_intensity))
# 3. 上下文关键词匹配
if "keywords" in context:
for keyword in context["keywords"]:
candidate_memories.extend(self._get_memories_by_keyword(keyword))
# 4. 时间相关性 (最近事件优先)
if "time_recency" in context and context["time_recency"]:
candidate_memories.extend(self._get_recent_memories())
# 去重并计算相关性分数
scored_memories = self._score_memories(candidate_memories, context, affective_state)
# 按分数排序并返回前N个结果
scored_memories.sort(key=lambda x: x[1], reverse=True)
return [mem[0] for mem in scored_memories[:max_results]]
def reinforce_memory(self, memory_id: str, reinforcement: float = 0.15):
"""强化特定记忆"""
if memory_id in self.memory_strengths:
self.memory_strengths[memory_id].reinforce(reinforcement)
logger.info(f"强化记忆 {memory_id},新强度: {self.memory_strengths[memory_id].base:.2f}")
def decay_memories(self, decay_factor: float = 0.05):
"""定期衰减记忆强度"""
for memory_id, strength in self.memory_strengths.items():
# 衰减率与当前强度成正比
decay_rate = decay_factor * (1 - strength.current_strength())
strength.decay_rate += decay_rate
logger.info(f"记忆衰减完成,总衰减因子: {decay_factor}")
def forget_weak_memories(self, threshold: float = 0.1):
"""遗忘强度低于阈值的记忆"""
forgotten = []
for memory in self.memories[:]:
strength = self.memory_strengths[memory["id"]].current_strength()
if strength < threshold:
self._remove_memory(memory["id"])
forgotten.append(memory["id"])
if forgotten:
logger.warning(f"遗忘{len(forgotten)}个弱记忆: {', '.join(forgotten)}")
return forgotten
def get_emotion_network(self, emotion: str) -> List[Dict]:
"""获取特定情感相关的记忆网络"""
return self.emotion_network.get(emotion.upper(), [])
def get_stats(self) -> Dict:
"""获取记忆系统统计信息"""
total_memories = len(self.memories)
strengths = [s.current_strength() for s in self.memory_strengths.values()]
return {
"total_memories": total_memories,
"tag_distribution": {tag: len(ids) for tag, ids in self.memory_index.items()},
"emotion_distribution": {emo: len(ids) for emo, ids in self.emotion_index.items()},
"avg_strength": sum(strengths) / total_memories if total_memories else 0,
"weak_memories": sum(1 for s in strengths if s < 0.3)
}
# ===== 内部辅助方法 =====
def _get_memories_by_tag(self, tag: str) -> List[Dict]:
"""通过标签获取记忆"""
return [self._get_memory_by_id(mid) for mid in self.memory_index.get(tag, [])]
def _get_memories_by_emotion(self, emotion: str, intensity: float) -> List[Dict]:
"""通过情感获取记忆,考虑情感强度"""
emotion = emotion.upper()
memories = []
for mem_id in self.emotion_index.get(emotion, []):
mem = self._get_memory_by_id(mem_id)
# 检查情感强度是否匹配
for assoc in mem["emotional_associations"]:
if assoc.emotion.name == emotion and assoc.intensity >= intensity * 0.7:
memories.append(mem)
break
return memories
def _get_memories_by_keyword(self, keyword: str) -> List[Dict]:
"""通过关键词获取记忆"""
keyword = keyword.lower()
return [self._get_memory_by_id(mid) for mid in self.context_index.get(keyword, [])]
def _get_recent_memories(self, days: int = 30) -> List[Dict]:
"""获取近期记忆"""
recent_memories = []
cutoff = time.time() - days * 24 * 3600
for mem in self.memories:
if mem["timestamp"] > cutoff:
recent_memories.append(mem)
return recent_memories
def _score_memories(self,
memories: List[Dict],
context: Dict,
affective_state: Dict) -> List[Tuple[Dict, float]]:
"""为记忆计算综合相关性分数"""
scored = []
current_emotion = affective_state.get("emotion", {}).get("current_emotion", "NEUTRAL")
for mem in memories:
if not mem:
continue
mem_id = mem["id"]
strength = self.memory_strengths[mem_id].current_strength()
# 1. 基础分数 (记忆强度 + 检索次数)
score = strength * 0.6 + min(1.0, mem["retrieval_count"] * 0.1)
# 2. 情感匹配分数
emotion_score = 0
for assoc in mem["emotional_associations"]:
if assoc.emotion.name == current_emotion:
emotion_score = assoc.intensity * 0.3
break
score += emotion_score
# 3. 时间衰减补偿 (最近记忆加分)
recency = 1 - (time.time() - mem["timestamp"]) / (365 * 24 * 3600)
score += recency * 0.1
# 4. 上下文匹配分数
if "keywords" in context:
context_words = set(word.lower() for word in context["keywords"])
content_words = set(mem["content"].get("description", "").lower().split())
match_count = len(context_words & content_words)
score += match_count * 0.05
# 更新检索计数
mem["retrieval_count"] += 1
self.memory_strengths[mem_id].last_accessed = time.time()
scored.append((mem, score))
return scored
def _get_memory_by_id(self, memory_id: str) -> Dict:
"""通过ID获取记忆"""
for mem in self.memories:
if mem["id"] == memory_id:
return mem
return None
def _remove_memory(self, memory_id: str):
"""从系统中完全移除记忆"""
# 从主列表移除
self.memories = [mem for mem in self.memories if mem["id"] != memory_id]
# 从索引中移除
for index in [self.memory_index, self.emotion_index, self.context_index]:
for key, ids in index.items():
if memory_id in ids:
ids.remove(memory_id)
# 从情感网络中移除
for emotion, associations in self.emotion_network.items():
self.emotion_network[emotion] = [a for a in associations if a["memory_id"] != memory_id]
# 移除强度记录
if memory_id in self.memory_strengths:
del self.memory_strengths[memory_id]
logger.info(f"完全移除记忆: {memory_id}")
# ===== 测试用例 =====
if __name__ == "__main__":
print("=== 增强型记忆系统测试 ===")
# 初始化记忆系统
memory_system = MemorySystem()
# 创建情感关联
birthday_joy = EmotionalAssociation(EmotionType.JOY, 0.9, "生日派对")
accident_fear = EmotionalAssociation(EmotionType.FEAR, 0.85, "车祸现场")
# 添加记忆
memory_system.store(
content={"type": "event", "description": "我的10岁生日派对", "location": "家里后院"},
tags=["childhood", "celebration"],
emotional_associations=[birthday_joy]
)
memory_system.store(
content={"type": "event", "description": "高中毕业典礼", "location": "学校礼堂"},
tags=["education", "achievement"],
emotional_associations=[EmotionalAssociation(EmotionType.JOY, 0.8)]
)
memory_system.store(
content={"type": "trauma", "description": "目睹严重车祸", "location": "市中心"},
tags=["accident", "trauma"],
emotional_associations=[accident_fear]
)
# 添加近期记忆
recent_memory_id = memory_system.store(
content={"type": "daily", "description": "早晨喝咖啡阅读新闻", "location": "厨房"},
tags=["routine", "morning"]
)
# 模拟检索上下文
context = {
"tags": ["celebration"],
"keywords": ["生日"],
"time_recency": True
}
# 模拟情感状态
affective_state = {
"emotion": {
"current_emotion": "JOY",
"intensity": 0.7
}
}
# 检索记忆
print("\n检索与'庆祝'相关的记忆:")
results = memory_system.retrieve(context, affective_state)
for mem in results:
print(
f" - {mem['content']['description']} (强度: {memory_system.memory_strengths[mem['id']].current_strength():.2f})")
# 强化特定记忆
print("\n强化近期记忆:")
memory_system.reinforce_memory(recent_memory_id)
# 模拟时间流逝
print("\n模拟时间流逝(30天)...")
for _ in range(30):
memory_system.decay_memories(decay_factor=0.01)
# 再次检索
print("\n再次检索相同上下文:")
results = memory_system.retrieve(context, affective_state)
for mem in results:
strength = memory_system.memory_strengths[mem['id']].current_strength()
print(f" - {mem['content']['description']} (衰减后强度: {strength:.2f})")
# 遗忘弱记忆
print("\n遗忘弱记忆:")
forgotten = memory_system.forget_weak_memories(threshold=0.3)
if forgotten:
print(f"已遗忘记忆: {', '.join(forgotten)}")
else:
print("没有需要遗忘的记忆")
# 获取系统统计
stats = memory_system.get_stats()
print("\n系统统计:")
print(f"总记忆数: {stats['total_memories']}")
print(f"平均强度: {stats['avg_strength']:.2f}")
print(f"弱记忆数: {stats['weak_memories']}")