From 4695b709d92a3821e65f67bfef33aac7f5be22c1 Mon Sep 17 00:00:00 2001 From: Eric Phillips Date: Fri, 20 Feb 2026 23:32:50 -0700 Subject: [PATCH] persistant history --- agent/history.py | 47 ++++++++++++++++++++++++++++--- tests/test_history_persistance.py | 23 +++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 tests/test_history_persistance.py diff --git a/agent/history.py b/agent/history.py index c9ef133..5b75bc7 100644 --- a/agent/history.py +++ b/agent/history.py @@ -1,13 +1,52 @@ +import json +from datetime import datetime +from pathlib import Path +from typing import Optional + + # agent/history.py class ConversationHistory: - def __init__(self): - self.messages: list[dict] = [] + """Manages converstation history with JSON file persistance""" + + def __init__(self, session_id: Optional[str] = None): + self.history_dir = Path("./history") + self.history_dir.mkdir(exist_ok=True) + + # Generate session ID if not provided + if session_id is None: + session_id = datetime.now().strftime("%Y%m%d-%H%M%S") + + self.session_id = session_id + self.file = self.history_dir / f"{session_id}.json" + self.messages = self._load() + + def _load(self) -> list[dict]: + """Load history from file if it exists.""" + if self.file.exists(): + try: + return json.loads(self.file.read_text()) + except json.JSONDecodeError: + print(f"Warning: Could not load {self.file}, starting fresh") + return [] + return [] + + def _save(self): + """Save history to file.""" + self.file.write_text(json.dumps(self.messages, indent=2)) def add_message(self, role: str, content: str): - self.messages.append({"role": role, "content": content}) + """Add a message to history and save.""" + self.messages.append( + {"role": role, "content": content, "timestamp": datetime.now().isoformat()} + ) + self._save() def get_all(self) -> list[dict]: - return self.messages + """Get all messages (without timestamps for LLM API).""" + return [{"role": m["role"], "content": m["content"]} for m in self.messages] def clear(self): + """Clear history and delete file.""" self.messages = [] + if self.file.exists(): + self.file.unlink() diff --git a/tests/test_history_persistance.py b/tests/test_history_persistance.py new file mode 100644 index 0000000..2151e6e --- /dev/null +++ b/tests/test_history_persistance.py @@ -0,0 +1,23 @@ +# test_history_persistence.py +from agent.history import ConversationHistory + +# Create history +history = ConversationHistory(session_id="test-session") +history.add_message("user", "Hello") +history.add_message("assistant", "Hi there!") + +print(f"Session ID: {history.session_id}") +print(f"Messages: {len(history.messages)}") + +# Verify file exists +print(f"File exists: {history.file.exists()}") +print(f"File contents:") +print(history.file.read_text()) + +# Create new instance with same session_id +history2 = ConversationHistory(session_id="test-session") +print(f"\nLoaded messages: {len(history2.messages)}") +print(f"First message: {history2.messages[0]}") + +# Clean up +history.clear()