File size: 1,280 Bytes
a66103f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import json
import uuid
from datetime import datetime
from pathlib import Path

class SessionManager:
    def __init__(self):
        self.sessions_dir = Path("data/sessions")
        self.sessions_dir.mkdir(parents=True, exist_ok=True)
    
    def create_session(self) -> str:
        """Create new empty session and return ID"""
        session_id = str(uuid.uuid4())
        self.save_session(session_id, {
            "created_at": datetime.now().isoformat(),
            "history": []
        })
        return session_id
    
    def save_session(self, session_id: str, data: dict):
        """Save session data to file"""
        with open(self.sessions_dir / f"{session_id}.json", "w") as f:
            json.dump(data, f, indent=2)
    
    def load_session(self, session_id: str) -> dict:
        """Load session data or create new if not found"""
        try:
            with open(self.sessions_dir / f"{session_id}.json") as f:
                return json.load(f)
        except FileNotFoundError:
            return self.create_session()
    
    def clear_session(self, session_id: str):
        """Reset session while keeping ID"""
        self.save_session(session_id, {
            "created_at": datetime.now().isoformat(),
            "history": []
        })