base.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. """记忆系统基础类和配置
  2. 按照第8章架构设计的基础组件:
  3. - MemoryItem: 记忆项数据结构
  4. - MemoryConfig: 记忆系统配置
  5. - BaseMemory: 记忆基类
  6. """
  7. from abc import ABC, abstractmethod
  8. from typing import List, Dict, Any
  9. from datetime import datetime
  10. from pydantic import BaseModel
  11. class MemoryItem(BaseModel):
  12. """记忆项数据结构"""
  13. id: str
  14. content: str
  15. memory_type: str
  16. user_id: str
  17. timestamp: datetime
  18. importance: float = 0.5
  19. metadata: Dict[str, Any] = {}
  20. class Config:
  21. arbitrary_types_allowed = True
  22. class MemoryConfig(BaseModel):
  23. """记忆系统配置"""
  24. # 存储路径
  25. storage_path: str = "./memory_data"
  26. # 向量/嵌入相关(可选关闭,适用于只用 SQLite 的轻量 episodic)
  27. disable_vector_store: bool = False
  28. disable_embeddings: bool = False
  29. # 统计显示用的基础配置(仅用于展示)
  30. max_capacity: int = 100
  31. importance_threshold: float = 0.1
  32. decay_factor: float = 0.95
  33. # 工作记忆特定配置
  34. working_memory_capacity: int = 10
  35. working_memory_tokens: int = 2000
  36. working_memory_ttl_minutes: int = 120
  37. # 感知记忆特定配置
  38. perceptual_memory_modalities: List[str] = ["text", "image", "audio", "video"]
  39. class BaseMemory(ABC):
  40. """记忆基类
  41. 定义所有记忆类型的通用接口和行为
  42. """
  43. def __init__(self, config: MemoryConfig, storage_backend=None):
  44. self.config = config
  45. self.storage = storage_backend
  46. self.memory_type = self.__class__.__name__.lower().replace("memory", "")
  47. @abstractmethod
  48. def add(self, memory_item: MemoryItem) -> str:
  49. """添加记忆项
  50. Args:
  51. memory_item: 记忆项对象
  52. Returns:
  53. 记忆ID
  54. """
  55. pass
  56. @abstractmethod
  57. def retrieve(self, query: str, limit: int = 5, **kwargs) -> List[MemoryItem]:
  58. """检索相关记忆
  59. Args:
  60. query: 查询内容
  61. limit: 返回数量限制
  62. **kwargs: 其他检索参数
  63. Returns:
  64. 相关记忆列表
  65. """
  66. pass
  67. @abstractmethod
  68. def update(self, memory_id: str, content: str = None,
  69. importance: float = None, metadata: Dict[str, Any] = None) -> bool:
  70. """更新记忆
  71. Args:
  72. memory_id: 记忆ID
  73. content: 新内容
  74. importance: 新重要性
  75. metadata: 新元数据
  76. Returns:
  77. 是否更新成功
  78. """
  79. pass
  80. @abstractmethod
  81. def remove(self, memory_id: str) -> bool:
  82. """删除记忆
  83. Args:
  84. memory_id: 记忆ID
  85. Returns:
  86. 是否删除成功
  87. """
  88. pass
  89. @abstractmethod
  90. def has_memory(self, memory_id: str) -> bool:
  91. """检查记忆是否存在
  92. Args:
  93. memory_id: 记忆ID
  94. Returns:
  95. 是否存在
  96. """
  97. pass
  98. @abstractmethod
  99. def clear(self):
  100. """清空所有记忆"""
  101. pass
  102. @abstractmethod
  103. def get_stats(self) -> Dict[str, Any]:
  104. """获取记忆统计信息
  105. Returns:
  106. 统计信息字典
  107. """
  108. pass
  109. def _generate_id(self) -> str:
  110. """生成记忆ID"""
  111. import uuid
  112. return str(uuid.uuid4())
  113. def _calculate_importance(self, content: str, base_importance: float = 0.5) -> float:
  114. """计算记忆重要性
  115. Args:
  116. content: 记忆内容
  117. base_importance: 基础重要性
  118. Returns:
  119. 计算后的重要性分数
  120. """
  121. importance = base_importance
  122. # 基于内容长度
  123. if len(content) > 100:
  124. importance += 0.1
  125. # 基于关键词
  126. important_keywords = ["重要", "关键", "必须", "注意", "警告", "错误"]
  127. if any(keyword in content for keyword in important_keywords):
  128. importance += 0.2
  129. return max(0.0, min(1.0, importance))
  130. def __str__(self) -> str:
  131. stats = self.get_stats()
  132. return f"{self.__class__.__name__}(count={stats.get('count', 0)})"
  133. def __repr__(self) -> str:
  134. return self.__str__()