Spaces:
Running
on
Zero
Running
on
Zero
File size: 2,012 Bytes
fba7f09 |
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import os
import uuid
import datetime as dt
import sys
from typing import Optional
from supabase import create_client, Client
def _utc_now_iso() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat()
class AnalyticsLogger:
"""
Simple Supabase logger for:
- Sessions (id: uuid, created_at: timestamptz)
- Chats (id: uuid, session_id: uuid, timestamp: timestamptz, user: text, answer: text)
"""
def __init__(self):
url = os.getenv("SUPABASE_URL")
key = os.getenv("SUPABASE_KEY")
if not url or not key:
raise RuntimeError("Missing SUPABASE_URL or SUPABASE_KEY env var.")
self.client: Client = create_client(url, key)
self.session_id: Optional[str] = None
def start_session(self, model_id: str) -> str:
"""
Creates a session row and returns the session UUID (string).
"""
sid = str(uuid.uuid4())
payload = {"id": sid, "created_at": _utc_now_iso(), "model_id": model_id}
try:
self.client.table("Sessions").insert(payload).execute()
self.session_id = sid
return sid
except Exception as e:
print(f"[AnalyticsLogger] Failed to start session: {e}", file=sys.stderr)
raise e
def log_interaction(self, user: str, answer: str, ts_iso: Optional[str] = None) -> None:
"""
Inserts a single chat interaction.
"""
if not self.session_id:
raise ValueError("Session not started. Call start_session() first.")
session_id = self.session_id
chat_payload = {
"id": str(uuid.uuid4()),
"session_id": session_id,
"timestamp": ts_iso or _utc_now_iso(),
"user": user,
"answer": answer,
}
try:
self.client.table("Chats").insert(chat_payload).execute()
except Exception as e:
print(f"[AnalyticsLogger] Failed to log interaction: {e}", file=sys.stderr)
|