03_WorkingMemory_Implementation.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 代码示例 03: WorkingMemory实现详解
  5. 展示工作记忆的混合检索策略和TTL机制
  6. """
  7. import time
  8. from datetime import datetime, timedelta
  9. from typing import List, Dict, Any
  10. from hello_agents.tools import MemoryTool
  11. from hello_agents.memory import MemoryItem
  12. class WorkingMemoryDemo:
  13. """工作记忆演示类"""
  14. def __init__(self):
  15. self.memory_tool = MemoryTool(
  16. user_id="working_memory_demo",
  17. memory_types=["working"] # 只启用工作记忆
  18. )
  19. def demonstrate_capacity_management(self):
  20. """演示容量管理和TTL机制"""
  21. print("🧠 工作记忆容量管理演示")
  22. print("=" * 50)
  23. print("工作记忆特点:")
  24. print("• 容量有限(默认50条)")
  25. print("• TTL机制(默认60分钟)")
  26. print("• 自动清理过期记忆")
  27. print("• 优先级管理(重要性排序)")
  28. # 添加多条记忆来演示容量管理
  29. print(f"\n📝 添加测试记忆...")
  30. for i in range(10):
  31. importance = 0.3 + (i * 0.07) # 递增重要性
  32. self.memory_tool.execute("add",
  33. content=f"工作记忆测试项目 {i+1} - 重要性 {importance:.2f}",
  34. memory_type="working",
  35. importance=importance,
  36. test_id=i+1,
  37. category="capacity_test"
  38. )
  39. # 查看当前状态
  40. stats = self.memory_tool.execute("stats")
  41. print(f"当前状态: {stats}")
  42. # 演示重要性排序
  43. print(f"\n🔍 按重要性搜索:")
  44. result = self.memory_tool.execute("search",
  45. query="测试项目",
  46. memory_type="working",
  47. limit=5
  48. )
  49. print(result)
  50. def demonstrate_mixed_retrieval_strategy(self):
  51. """演示混合检索策略"""
  52. print("\n🔍 混合检索策略演示")
  53. print("-" * 40)
  54. print("混合检索策略包括:")
  55. print("• TF-IDF向量化语义检索")
  56. print("• 关键词匹配检索")
  57. print("• 时间衰减因子")
  58. print("• 重要性权重调整")
  59. # 添加不同类型的记忆用于检索测试
  60. test_memories = [
  61. {
  62. "content": "Python是一种高级编程语言,语法简洁清晰",
  63. "importance": 0.8,
  64. "topic": "programming",
  65. "language": "python"
  66. },
  67. {
  68. "content": "机器学习是人工智能的重要分支,包括监督学习和无监督学习",
  69. "importance": 0.9,
  70. "topic": "ai",
  71. "domain": "machine_learning"
  72. },
  73. {
  74. "content": "数据结构包括数组、链表、栈、队列等基本结构",
  75. "importance": 0.7,
  76. "topic": "computer_science",
  77. "category": "data_structures"
  78. },
  79. {
  80. "content": "算法复杂度分析使用大O记号来描述时间和空间复杂度",
  81. "importance": 0.8,
  82. "topic": "algorithms",
  83. "analysis": "complexity"
  84. }
  85. ]
  86. print(f"\n📝 添加测试记忆...")
  87. for i, memory in enumerate(test_memories):
  88. content = memory.pop("content")
  89. importance = memory.pop("importance")
  90. self.memory_tool.execute("add",
  91. content=content,
  92. memory_type="working",
  93. importance=importance,
  94. **memory
  95. )
  96. # 测试不同类型的检索
  97. search_tests = [
  98. ("Python编程", "测试语义匹配"),
  99. ("学习", "测试关键词匹配"),
  100. ("复杂度", "测试部分匹配"),
  101. ("人工智能机器学习", "测试多词匹配")
  102. ]
  103. print(f"\n🔍 混合检索测试:")
  104. for query, description in search_tests:
  105. print(f"\n查询: '{query}' ({description})")
  106. result = self.memory_tool.execute("search",
  107. query=query,
  108. memory_type="working",
  109. limit=2
  110. )
  111. print(f"结果: {result}")
  112. def demonstrate_time_decay_mechanism(self):
  113. """演示时间衰减机制"""
  114. print("\n⏰ 时间衰减机制演示")
  115. print("-" * 40)
  116. print("时间衰减机制:")
  117. print("• 新记忆权重更高")
  118. print("• 旧记忆权重衰减")
  119. print("• 模拟人类记忆特点")
  120. print("• 平衡新旧信息重要性")
  121. # 添加不同时间的记忆(模拟)
  122. time_test_memories = [
  123. ("最新的重要信息 - 刚刚学习的概念", 0.7, "newest"),
  124. ("较新的信息 - 昨天学习的内容", 0.7, "recent"),
  125. ("较旧的信息 - 上周学习的内容", 0.7, "older"),
  126. ("最旧的信息 - 很久以前的内容", 0.7, "oldest")
  127. ]
  128. print(f"\n📝 添加不同时期的记忆...")
  129. for content, importance, age_category in time_test_memories:
  130. self.memory_tool.execute("add",
  131. content=content,
  132. memory_type="working",
  133. importance=importance,
  134. age_category=age_category,
  135. timestamp_category=age_category
  136. )
  137. # 搜索测试时间衰减效果
  138. print(f"\n🔍 时间衰减效果测试:")
  139. result = self.memory_tool.execute("search",
  140. query="学习的内容",
  141. memory_type="working",
  142. limit=4
  143. )
  144. print("搜索结果(注意时间因素对排序的影响):")
  145. print(result)
  146. def demonstrate_automatic_cleanup(self):
  147. """演示自动清理机制"""
  148. print("\n🧹 自动清理机制演示")
  149. print("-" * 40)
  150. print("自动清理机制:")
  151. print("• 过期记忆自动清理")
  152. print("• 容量超限时清理低优先级记忆")
  153. print("• 保持系统性能和响应速度")
  154. print("• 模拟工作记忆的有限容量")
  155. # 获取清理前的状态
  156. stats_before = self.memory_tool.execute("stats")
  157. print(f"\n清理前状态: {stats_before}")
  158. # 添加一些低重要性的记忆
  159. print(f"\n📝 添加低重要性记忆...")
  160. for i in range(5):
  161. self.memory_tool.execute("add",
  162. content=f"低重要性临时记忆 {i+1}",
  163. memory_type="working",
  164. importance=0.1 + i * 0.05,
  165. temporary=True,
  166. cleanup_test=True
  167. )
  168. # 触发基于重要性的清理
  169. print(f"\n🧹 执行基于重要性的清理...")
  170. cleanup_result = self.memory_tool.execute("forget",
  171. strategy="importance_based",
  172. threshold=0.3
  173. )
  174. print(f"清理结果: {cleanup_result}")
  175. # 获取清理后的状态
  176. stats_after = self.memory_tool.execute("stats")
  177. print(f"\n清理后状态: {stats_after}")
  178. def demonstrate_performance_characteristics(self):
  179. """演示性能特征"""
  180. print("\n⚡ 性能特征演示")
  181. print("-" * 40)
  182. print("工作记忆性能特点:")
  183. print("• 纯内存存储,访问速度极快")
  184. print("• 无需磁盘I/O,响应时间短")
  185. print("• 适合频繁访问的临时数据")
  186. print("• 系统重启后数据丢失(符合设计)")
  187. # 性能测试
  188. print(f"\n⏱️ 性能测试:")
  189. # 批量添加测试
  190. start_time = time.time()
  191. for i in range(20):
  192. self.memory_tool.execute("add",
  193. content=f"性能测试记忆 {i+1}",
  194. memory_type="working",
  195. importance=0.5,
  196. performance_test=True
  197. )
  198. add_time = time.time() - start_time
  199. print(f"批量添加20条记忆耗时: {add_time:.3f}秒")
  200. # 批量搜索测试
  201. start_time = time.time()
  202. for i in range(10):
  203. self.memory_tool.execute("search",
  204. query=f"性能测试",
  205. memory_type="working",
  206. limit=3
  207. )
  208. search_time = time.time() - start_time
  209. print(f"批量搜索10次耗时: {search_time:.3f}秒")
  210. # 获取最终统计
  211. final_stats = self.memory_tool.execute("stats")
  212. print(f"\n📊 最终统计: {final_stats}")
  213. def main():
  214. """主函数"""
  215. print("🧠 WorkingMemory实现详解")
  216. print("展示工作记忆的核心特性和实现机制")
  217. print("=" * 60)
  218. try:
  219. demo = WorkingMemoryDemo()
  220. # 1. 容量管理演示
  221. demo.demonstrate_capacity_management()
  222. # 2. 混合检索策略演示
  223. demo.demonstrate_mixed_retrieval_strategy()
  224. # 3. 时间衰减机制演示
  225. demo.demonstrate_time_decay_mechanism()
  226. # 4. 自动清理机制演示
  227. demo.demonstrate_automatic_cleanup()
  228. # 5. 性能特征演示
  229. demo.demonstrate_performance_characteristics()
  230. print("\n" + "=" * 60)
  231. print("🎉 WorkingMemory实现演示完成!")
  232. print("=" * 60)
  233. print("\n✨ 工作记忆核心特性:")
  234. print("1. 🧠 有限容量 - 模拟人类工作记忆限制")
  235. print("2. ⚡ 高速访问 - 纯内存存储,响应迅速")
  236. print("3. 🔍 混合检索 - 语义+关键词+时间+重要性")
  237. print("4. ⏰ 时间衰减 - 新信息优先,旧信息衰减")
  238. print("5. 🧹 自动清理 - TTL机制+优先级管理")
  239. print("\n🎯 设计理念:")
  240. print("• 临时性 - 存储当前会话的临时信息")
  241. print("• 高效性 - 快速访问和处理能力")
  242. print("• 智能性 - 自动管理和优化策略")
  243. print("• 仿生性 - 模拟人类工作记忆特点")
  244. except Exception as e:
  245. print(f"\n❌ 演示过程中发生错误: {e}")
  246. import traceback
  247. traceback.print_exc()
  248. if __name__ == "__main__":
  249. main()