The memory refine tool
| 77 | |
| 78 | |
| 79 | class DefaultMemory(Memory): |
| 80 | """The memory refine tool""" |
| 81 | |
| 82 | def __init__(self, config: DictConfig): |
| 83 | super().__init__(config) |
| 84 | memory_config = config.memory.default_memory |
| 85 | self.user_id: Optional[str] = getattr(memory_config, 'user_id', |
| 86 | DEFAULT_USER) |
| 87 | self.agent_id: Optional[str] = getattr(memory_config, 'agent_id', None) |
| 88 | self.run_id: Optional[str] = getattr(memory_config, 'run_id', None) |
| 89 | self.compress: Optional[bool] = getattr(config, 'compress', True) |
| 90 | self.is_retrieve: Optional[bool] = getattr(config, 'is_retrieve', True) |
| 91 | self.path: Optional[str] = getattr( |
| 92 | memory_config, 'path', |
| 93 | os.path.join(DEFAULT_OUTPUT_DIR, '.default_memory')) |
| 94 | self.history_mode = getattr(memory_config, 'history_mode', 'add') |
| 95 | self.ignore_roles: List[str] = getattr(memory_config, 'ignore_roles', |
| 96 | ['tool', 'system']) |
| 97 | self.ignore_fields: List[str] = getattr(memory_config, 'ignore_fields', |
| 98 | ['reasoning_content']) |
| 99 | self.search_limit: int = getattr(memory_config, 'search_limit', |
| 100 | DEFAULT_SEARCH_LIMIT) |
| 101 | # Add lock for thread safety in shared usage |
| 102 | self._lock = asyncio.Lock() |
| 103 | self.memory = self._init_memory_obj() |
| 104 | self.load_cache() |
| 105 | |
| 106 | async def init_cache_messages(self): |
| 107 | if len(self.cache_messages) and not len(self.memory_snapshot): |
| 108 | for id, messages in self.cache_messages.items(): |
| 109 | await self.add_single(messages, msg_id=id) |
| 110 | |
| 111 | def save_cache(self): |
| 112 | """ |
| 113 | Save self.max_msg_id, self.cache_messages, and self.memory_snapshot to self.path/cache_messages.json |
| 114 | """ |
| 115 | cache_file = os.path.join(self.path, 'cache_messages.json') |
| 116 | |
| 117 | # Ensure the directory exists |
| 118 | os.makedirs(self.path, exist_ok=True) |
| 119 | |
| 120 | data = { |
| 121 | 'max_msg_id': self.max_msg_id, |
| 122 | 'cache_messages': { |
| 123 | str(k): ([msg.to_dict() for msg in msg_list], _hash) |
| 124 | for k, (msg_list, _hash) in self.cache_messages.items() |
| 125 | }, |
| 126 | 'memory_snapshot': [mm.to_dict() for mm in self.memory_snapshot] |
| 127 | } |
| 128 | |
| 129 | with open(cache_file, 'w', encoding='utf-8') as f: |
| 130 | json5.dump(data, f, indent=2, ensure_ascii=False) |
| 131 | |
| 132 | def load_cache(self): |
| 133 | """ |
| 134 | Load data from self.path/cache_messages.json into self.max_msg_id, self.cache_messages, and self.memory_snapshot |
| 135 | """ |
| 136 | cache_file = os.path.join(self.path, 'cache_messages.json') |
nothing calls this directly
no outgoing calls
no test coverage detected