Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- api/database.py +97 -15
- api/main.py +16 -0
api/database.py
CHANGED
|
@@ -61,13 +61,19 @@ def init_db() -> None:
|
|
| 61 |
-- (safe to run multiple times β ALTER TABLE fails silently via Python)
|
| 62 |
|
| 63 |
CREATE TABLE IF NOT EXISTS chat_sessions (
|
| 64 |
-
id
|
| 65 |
-
session_uuid
|
| 66 |
-
user_id
|
| 67 |
-
title
|
| 68 |
-
created_at
|
| 69 |
-
updated_at
|
| 70 |
-
deleted_at
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
);
|
| 72 |
|
| 73 |
CREATE TABLE IF NOT EXISTS messages (
|
|
@@ -239,12 +245,22 @@ def get_message_count(session_uuid: str) -> int:
|
|
| 239 |
# ββ Admin helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 240 |
|
| 241 |
def migrate_add_admin_column() -> None:
|
| 242 |
-
"""Safe migration β adds is_admin
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
|
| 249 |
|
| 250 |
def set_admin(username: str, is_admin: bool = True) -> bool:
|
|
@@ -264,7 +280,16 @@ def get_all_users_admin() -> list:
|
|
| 264 |
SELECT
|
| 265 |
u.id, u.username, u.email, u.created_at, u.is_admin,
|
| 266 |
COUNT(DISTINCT cs.id) AS session_count,
|
| 267 |
-
COUNT(DISTINCT m.id) AS message_count
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
FROM users u
|
| 269 |
LEFT JOIN chat_sessions cs ON cs.user_id = u.id AND cs.deleted_at IS NULL
|
| 270 |
LEFT JOIN messages m ON m.session_uuid = cs.session_uuid
|
|
@@ -283,7 +308,8 @@ def get_all_sessions_admin() -> tuple:
|
|
| 283 |
|
| 284 |
|
| 285 |
def get_user_sessions_with_messages(user_id: int) -> list:
|
| 286 |
-
"""Return all sessions for a user including full message content."""
|
|
|
|
| 287 |
with get_conn() as conn:
|
| 288 |
sessions = conn.execute(
|
| 289 |
"SELECT * FROM chat_sessions WHERE user_id=? AND deleted_at IS NULL ORDER BY created_at DESC",
|
|
@@ -297,5 +323,61 @@ def get_user_sessions_with_messages(user_id: int) -> list:
|
|
| 297 |
(s["session_uuid"],)
|
| 298 |
).fetchall()
|
| 299 |
s["messages"] = [dict(m) for m in msgs]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
result.append(s)
|
| 301 |
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
-- (safe to run multiple times β ALTER TABLE fails silently via Python)
|
| 62 |
|
| 63 |
CREATE TABLE IF NOT EXISTS chat_sessions (
|
| 64 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 65 |
+
session_uuid TEXT NOT NULL UNIQUE,
|
| 66 |
+
user_id INTEGER NOT NULL REFERENCES users(id),
|
| 67 |
+
title TEXT NOT NULL DEFAULT 'New Chat',
|
| 68 |
+
created_at TEXT NOT NULL,
|
| 69 |
+
updated_at TEXT NOT NULL,
|
| 70 |
+
deleted_at TEXT DEFAULT NULL,
|
| 71 |
+
ms_tier TEXT DEFAULT NULL,
|
| 72 |
+
ms_tier_label TEXT DEFAULT NULL,
|
| 73 |
+
ms_symptoms TEXT DEFAULT NULL,
|
| 74 |
+
ms_workup TEXT DEFAULT NULL,
|
| 75 |
+
ms_action TEXT DEFAULT NULL,
|
| 76 |
+
concluded_at TEXT DEFAULT NULL
|
| 77 |
);
|
| 78 |
|
| 79 |
CREATE TABLE IF NOT EXISTS messages (
|
|
|
|
| 245 |
# ββ Admin helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 246 |
|
| 247 |
def migrate_add_admin_column() -> None:
|
| 248 |
+
"""Safe migration β adds is_admin and conclusion columns to existing databases."""
|
| 249 |
+
cols = [
|
| 250 |
+
"ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0",
|
| 251 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_tier TEXT DEFAULT NULL",
|
| 252 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_tier_label TEXT DEFAULT NULL",
|
| 253 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_symptoms TEXT DEFAULT NULL",
|
| 254 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_workup TEXT DEFAULT NULL",
|
| 255 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_action TEXT DEFAULT NULL",
|
| 256 |
+
"ALTER TABLE chat_sessions ADD COLUMN concluded_at TEXT DEFAULT NULL",
|
| 257 |
+
]
|
| 258 |
+
for sql in cols:
|
| 259 |
+
try:
|
| 260 |
+
with get_conn() as conn:
|
| 261 |
+
conn.execute(sql)
|
| 262 |
+
except Exception:
|
| 263 |
+
pass # Column already exists β safe to ignore
|
| 264 |
|
| 265 |
|
| 266 |
def set_admin(username: str, is_admin: bool = True) -> bool:
|
|
|
|
| 280 |
SELECT
|
| 281 |
u.id, u.username, u.email, u.created_at, u.is_admin,
|
| 282 |
COUNT(DISTINCT cs.id) AS session_count,
|
| 283 |
+
COUNT(DISTINCT m.id) AS message_count,
|
| 284 |
+
MAX(CASE WHEN cs.ms_tier='CRITICAL_EMERGENCY' THEN 5
|
| 285 |
+
WHEN cs.ms_tier='HIGH' THEN 4
|
| 286 |
+
WHEN cs.ms_tier='MODERATE' THEN 3
|
| 287 |
+
WHEN cs.ms_tier='WATCH' THEN 2
|
| 288 |
+
WHEN cs.ms_tier='LOW' THEN 1
|
| 289 |
+
ELSE 0 END) AS highest_risk_score,
|
| 290 |
+
(SELECT cs2.ms_tier FROM chat_sessions cs2
|
| 291 |
+
WHERE cs2.user_id=u.id AND cs2.ms_tier IS NOT NULL
|
| 292 |
+
ORDER BY cs2.concluded_at DESC LIMIT 1) AS latest_tier
|
| 293 |
FROM users u
|
| 294 |
LEFT JOIN chat_sessions cs ON cs.user_id = u.id AND cs.deleted_at IS NULL
|
| 295 |
LEFT JOIN messages m ON m.session_uuid = cs.session_uuid
|
|
|
|
| 308 |
|
| 309 |
|
| 310 |
def get_user_sessions_with_messages(user_id: int) -> list:
|
| 311 |
+
"""Return all sessions for a user including full message content and conclusion."""
|
| 312 |
+
import json as _json
|
| 313 |
with get_conn() as conn:
|
| 314 |
sessions = conn.execute(
|
| 315 |
"SELECT * FROM chat_sessions WHERE user_id=? AND deleted_at IS NULL ORDER BY created_at DESC",
|
|
|
|
| 323 |
(s["session_uuid"],)
|
| 324 |
).fetchall()
|
| 325 |
s["messages"] = [dict(m) for m in msgs]
|
| 326 |
+
# Attach parsed conclusion
|
| 327 |
+
if s.get("ms_tier"):
|
| 328 |
+
s["conclusion"] = {
|
| 329 |
+
"tier": s["ms_tier"],
|
| 330 |
+
"tier_label": s["ms_tier_label"],
|
| 331 |
+
"symptoms": _json.loads(s.get("ms_symptoms") or "[]"),
|
| 332 |
+
"workup": _json.loads(s.get("ms_workup") or "[]"),
|
| 333 |
+
"action": s.get("ms_action", ""),
|
| 334 |
+
"concluded_at": s.get("concluded_at"),
|
| 335 |
+
}
|
| 336 |
+
else:
|
| 337 |
+
s["conclusion"] = None
|
| 338 |
result.append(s)
|
| 339 |
return result
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def save_conclusion(session_uuid: str, tier: str, tier_label: str,
|
| 343 |
+
symptoms: list, workup: list, action: str) -> None:
|
| 344 |
+
"""Save the MS classification conclusion to the session record."""
|
| 345 |
+
import json as _json
|
| 346 |
+
now = _now()
|
| 347 |
+
with get_conn() as conn:
|
| 348 |
+
conn.execute("""
|
| 349 |
+
UPDATE chat_sessions
|
| 350 |
+
SET ms_tier=?, ms_tier_label=?, ms_symptoms=?, ms_workup=?,
|
| 351 |
+
ms_action=?, concluded_at=?, updated_at=?
|
| 352 |
+
WHERE session_uuid=?
|
| 353 |
+
""", (
|
| 354 |
+
tier,
|
| 355 |
+
tier_label,
|
| 356 |
+
_json.dumps(symptoms),
|
| 357 |
+
_json.dumps(workup),
|
| 358 |
+
action,
|
| 359 |
+
now,
|
| 360 |
+
now,
|
| 361 |
+
session_uuid,
|
| 362 |
+
))
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def get_conclusion(session_uuid: str) -> dict | None:
|
| 366 |
+
"""Return the saved conclusion for a session, or None."""
|
| 367 |
+
import json as _json
|
| 368 |
+
with get_conn() as conn:
|
| 369 |
+
row = conn.execute(
|
| 370 |
+
"SELECT ms_tier, ms_tier_label, ms_symptoms, ms_workup, ms_action, concluded_at "
|
| 371 |
+
"FROM chat_sessions WHERE session_uuid=?",
|
| 372 |
+
(session_uuid,)
|
| 373 |
+
).fetchone()
|
| 374 |
+
if not row or not row["ms_tier"]:
|
| 375 |
+
return None
|
| 376 |
+
return {
|
| 377 |
+
"tier": row["ms_tier"],
|
| 378 |
+
"tier_label": row["ms_tier_label"],
|
| 379 |
+
"symptoms": _json.loads(row["ms_symptoms"] or "[]"),
|
| 380 |
+
"workup": _json.loads(row["ms_workup"] or "[]"),
|
| 381 |
+
"action": row["ms_action"],
|
| 382 |
+
"concluded_at": row["concluded_at"],
|
| 383 |
+
}
|
api/main.py
CHANGED
|
@@ -1175,6 +1175,22 @@ async def chat_endpoint(
|
|
| 1175 |
title = req.message[:60].strip()
|
| 1176 |
update_session_title(sid, title)
|
| 1177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1178 |
# Also keep in-memory store for agent context (existing logic)
|
| 1179 |
append_message(sid, "human", req.message)
|
| 1180 |
history = get_history(sid)
|
|
|
|
| 1175 |
title = req.message[:60].strip()
|
| 1176 |
update_session_title(sid, title)
|
| 1177 |
|
| 1178 |
+
# Run classifier to extract structured conclusion and save to session
|
| 1179 |
+
try:
|
| 1180 |
+
from api.database import save_conclusion
|
| 1181 |
+
_cls = classify(req.message)
|
| 1182 |
+
if _cls.tier not in ("LOW",): # only save meaningful conclusions
|
| 1183 |
+
save_conclusion(
|
| 1184 |
+
session_uuid=sid,
|
| 1185 |
+
tier=_cls.tier,
|
| 1186 |
+
tier_label=_cls.tier_label,
|
| 1187 |
+
symptoms=[f.label for f in _cls.features],
|
| 1188 |
+
workup=_cls.workup[:6],
|
| 1189 |
+
action=_cls.action,
|
| 1190 |
+
)
|
| 1191 |
+
except Exception as _ce:
|
| 1192 |
+
logger.warning("[chat] Conclusion save failed: {}", _ce)
|
| 1193 |
+
|
| 1194 |
# Also keep in-memory store for agent context (existing logic)
|
| 1195 |
append_message(sid, "human", req.message)
|
| 1196 |
history = get_history(sid)
|