| | """ |
| | 💾 Haven Memory System |
| | Conversation history and context management. |
| | """ |
| |
|
| | import json |
| | import os |
| | from datetime import datetime |
| |
|
| |
|
| | class MemoryJournal: |
| | def __init__(self, filepath="haven_memory.json"): |
| | self.filepath = filepath |
| | self._ensure_file() |
| |
|
| | def _ensure_file(self): |
| | if not os.path.exists(self.filepath): |
| | with open(self.filepath, 'w') as f: |
| | json.dump([], f) |
| |
|
| | def save_interaction(self, role, content, avatar=None): |
| | try: |
| | with open(self.filepath, 'r') as f: |
| | history = json.load(f) |
| | except: |
| | history = [] |
| | |
| | entry = { |
| | "timestamp": datetime.now().isoformat(), |
| | "role": role, |
| | "content": content, |
| | "avatar": avatar |
| | } |
| | history.append(entry) |
| | |
| | |
| | if len(history) > 50: |
| | history = history[-50:] |
| | |
| | with open(self.filepath, 'w') as f: |
| | json.dump(history, f, indent=2) |
| |
|
| | def load_history(self): |
| | try: |
| | with open(self.filepath, 'r') as f: |
| | return json.load(f) |
| | except: |
| | return [] |
| |
|
| | def get_context_string(self, limit=5): |
| | history = self.load_history()[-limit:] |
| | context = "" |
| | for msg in history: |
| | context += f"{msg['role'].upper()}: {msg['content']}\n" |
| | return context |
| |
|