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
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user