03_WorkingMemory_Implementation.py 11 KB

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