53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
import json
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
|
|
# agent/history.py
|
|
class ConversationHistory:
|
|
"""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):
|
|
"""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]:
|
|
"""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()
|