persistant history
This commit is contained in:
+43
-4
@@ -1,13 +1,52 @@
|
|||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
# agent/history.py
|
# agent/history.py
|
||||||
class ConversationHistory:
|
class ConversationHistory:
|
||||||
def __init__(self):
|
"""Manages converstation history with JSON file persistance"""
|
||||||
self.messages: list[dict] = []
|
|
||||||
|
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):
|
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]:
|
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):
|
def clear(self):
|
||||||
|
"""Clear history and delete file."""
|
||||||
self.messages = []
|
self.messages = []
|
||||||
|
if self.file.exists():
|
||||||
|
self.file.unlink()
|
||||||
|
|||||||
@@ -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()
|
||||||
Reference in New Issue
Block a user