flare / session.py
ciyidogan's picture
Update session.py
525e493 verified
raw
history blame
2.34 kB
"""Flare – Session & SessionStore
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Basit, thread-safe, in-memory oturum yöneticisi.
"""
import uuid
import threading
from typing import Dict, List
from utils import log
class Session:
"""Tek kullanıcılık sohbet durumu."""
def __init__(self, project_name: str):
self.session_id: str = str(uuid.uuid4())
self.project_name: str = project_name
self.last_intent: str | None = None
self.variables: Dict[str, str] = {}
self.awaiting_parameters: List[str] = []
self.state: str = "intent_detection"
self.chat_history: List[Dict[str, str]] = []
self.auth_tokens: Dict[str, str] = {}
# --------- helpers ----------
def add_turn(self, role: str, content: str) -> None:
self.chat_history.append({"role": role, "content": content})
if len(self.chat_history) > 20: # hafıza koruması
self.chat_history.pop(0)
def to_dict(self) -> Dict:
return {
"session_id": self.session_id,
"project_name": self.project_name,
"last_intent": self.last_intent,
"variables": self.variables,
"awaiting_parameters": self.awaiting_parameters,
"state": self.state,
"chat_history": self.chat_history,
}
class SessionStore:
"""Thread-safe oturum havuzu."""
def __init__(self) -> None:
self._sessions: Dict[str, Session] = {}
self._lock = threading.Lock()
def create_session(self, project_name: str) -> Session:
with self._lock:
session = Session(project_name)
self._sessions[session.session_id] = session
log(f"🆕 Created session: {session.session_id} (project: {project_name})")
return session
def get_session(self, session_id: str) -> Session | None:
with self._lock:
return self._sessions.get(session_id)
def remove_session(self, session_id: str) -> None:
with self._lock:
if session_id in self._sessions:
del self._sessions[session_id]
log(f"❌ Removed session: {session_id}")
def __contains__(self, session_id: str) -> bool:
return self.get_session(session_id) is not None
# Global singleton
session_store = SessionStore()