Spaces:
Sleeping
Sleeping
Upload memory.py
Browse files- api/memory.py +92 -92
api/memory.py
CHANGED
|
@@ -1,92 +1,92 @@
|
|
| 1 |
-
"""
|
| 2 |
-
NeuroCheck Agentic AI β Session Memory
|
| 3 |
-
File-based session store: no Redis required for local deployment.
|
| 4 |
-
Each session is a JSON file in /tmp/neurocheck_sessions/.
|
| 5 |
-
"""
|
| 6 |
-
from __future__ import annotations
|
| 7 |
-
import json, uuid, os
|
| 8 |
-
from datetime import datetime
|
| 9 |
-
from pathlib import Path
|
| 10 |
-
from typing import List, Dict, Any
|
| 11 |
-
|
| 12 |
-
SESSION_DIR = Path("/tmp/neurocheck_sessions")
|
| 13 |
-
SESSION_DIR.mkdir(parents=True, exist_ok=True)
|
| 14 |
-
|
| 15 |
-
MAX_HISTORY = 40 # max messages kept per session
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def new_session() -> str:
|
| 19 |
-
"""Create a new session and return its ID."""
|
| 20 |
-
sid = str(uuid.uuid4())
|
| 21 |
-
_write(sid, {
|
| 22 |
-
"session_id": sid,
|
| 23 |
-
"created_at": _now(),
|
| 24 |
-
"messages": [],
|
| 25 |
-
"classification": None,
|
| 26 |
-
"symptoms_collected": [],
|
| 27 |
-
})
|
| 28 |
-
return sid
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def get_session(sid: str) -> Dict[str, Any] | None:
|
| 32 |
-
p = _path(sid)
|
| 33 |
-
if not p.exists():
|
| 34 |
-
return None
|
| 35 |
-
return json.loads(p.read_text())
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def append_message(sid: str, role: str, content: str) -> None:
|
| 39 |
-
"""Append a human/assistant message to session history."""
|
| 40 |
-
s = get_session(sid)
|
| 41 |
-
if s is None:
|
| 42 |
-
return
|
| 43 |
-
s["messages"].append({"role": role, "content": content, "ts": _now()})
|
| 44 |
-
# Keep last MAX_HISTORY messages
|
| 45 |
-
if len(s["messages"]) > MAX_HISTORY:
|
| 46 |
-
s["messages"] = s["messages"][-MAX_HISTORY:]
|
| 47 |
-
_write(sid, s)
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def set_classification(sid: str, classification: Dict[str, Any]) -> None:
|
| 51 |
-
s = get_session(sid)
|
| 52 |
-
if s is None:
|
| 53 |
-
return
|
| 54 |
-
s["classification"] = classification
|
| 55 |
-
_write(sid, s)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def get_history(sid: str) -> List[Dict[str, str]]:
|
| 59 |
-
s = get_session(sid)
|
| 60 |
-
if s is None:
|
| 61 |
-
return []
|
| 62 |
-
return s.get("messages", [])
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def get_lc_messages(sid: str):
|
| 66 |
-
"""Return LangChain-compatible message list for context injection."""
|
| 67 |
-
from langchain_core.messages import HumanMessage, AIMessage
|
| 68 |
-
msgs = get_history(sid)
|
| 69 |
-
lc = []
|
| 70 |
-
for m in msgs:
|
| 71 |
-
if m["role"] == "human":
|
| 72 |
-
lc.append(HumanMessage(content=m["content"]))
|
| 73 |
-
else:
|
| 74 |
-
lc.append(AIMessage(content=m["content"]))
|
| 75 |
-
return lc
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def list_sessions() -> List[str]:
|
| 79 |
-
return [p.stem for p in SESSION_DIR.glob("*.json")]
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
# ββ Internal helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
-
def _path(sid: str) -> Path:
|
| 84 |
-
return SESSION_DIR / f"{sid}.json"
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
def _write(sid: str, data: Dict) -> None:
|
| 88 |
-
_path(sid).write_text(json.dumps(data, indent=2))
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def _now() -> str:
|
| 92 |
-
return datetime.utcnow().isoformat() + "Z"
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck Agentic AI β Session Memory
|
| 3 |
+
File-based session store: no Redis required for local deployment.
|
| 4 |
+
Each session is a JSON file in /tmp/neurocheck_sessions/.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
import json, uuid, os
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import List, Dict, Any
|
| 11 |
+
|
| 12 |
+
SESSION_DIR = Path(os.environ.get("SESSION_DIR", "/tmp/neurocheck_sessions"))
|
| 13 |
+
SESSION_DIR.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
MAX_HISTORY = 40 # max messages kept per session
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def new_session() -> str:
|
| 19 |
+
"""Create a new session and return its ID."""
|
| 20 |
+
sid = str(uuid.uuid4())
|
| 21 |
+
_write(sid, {
|
| 22 |
+
"session_id": sid,
|
| 23 |
+
"created_at": _now(),
|
| 24 |
+
"messages": [],
|
| 25 |
+
"classification": None,
|
| 26 |
+
"symptoms_collected": [],
|
| 27 |
+
})
|
| 28 |
+
return sid
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_session(sid: str) -> Dict[str, Any] | None:
|
| 32 |
+
p = _path(sid)
|
| 33 |
+
if not p.exists():
|
| 34 |
+
return None
|
| 35 |
+
return json.loads(p.read_text())
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def append_message(sid: str, role: str, content: str) -> None:
|
| 39 |
+
"""Append a human/assistant message to session history."""
|
| 40 |
+
s = get_session(sid)
|
| 41 |
+
if s is None:
|
| 42 |
+
return
|
| 43 |
+
s["messages"].append({"role": role, "content": content, "ts": _now()})
|
| 44 |
+
# Keep last MAX_HISTORY messages
|
| 45 |
+
if len(s["messages"]) > MAX_HISTORY:
|
| 46 |
+
s["messages"] = s["messages"][-MAX_HISTORY:]
|
| 47 |
+
_write(sid, s)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def set_classification(sid: str, classification: Dict[str, Any]) -> None:
|
| 51 |
+
s = get_session(sid)
|
| 52 |
+
if s is None:
|
| 53 |
+
return
|
| 54 |
+
s["classification"] = classification
|
| 55 |
+
_write(sid, s)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_history(sid: str) -> List[Dict[str, str]]:
|
| 59 |
+
s = get_session(sid)
|
| 60 |
+
if s is None:
|
| 61 |
+
return []
|
| 62 |
+
return s.get("messages", [])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_lc_messages(sid: str):
|
| 66 |
+
"""Return LangChain-compatible message list for context injection."""
|
| 67 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 68 |
+
msgs = get_history(sid)
|
| 69 |
+
lc = []
|
| 70 |
+
for m in msgs:
|
| 71 |
+
if m["role"] == "human":
|
| 72 |
+
lc.append(HumanMessage(content=m["content"]))
|
| 73 |
+
else:
|
| 74 |
+
lc.append(AIMessage(content=m["content"]))
|
| 75 |
+
return lc
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def list_sessions() -> List[str]:
|
| 79 |
+
return [p.stem for p in SESSION_DIR.glob("*.json")]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ββ Internal helpers ββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
+
def _path(sid: str) -> Path:
|
| 84 |
+
return SESSION_DIR / f"{sid}.json"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _write(sid: str, data: Dict) -> None:
|
| 88 |
+
_path(sid).write_text(json.dumps(data, indent=2))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _now() -> str:
|
| 92 |
+
return datetime.utcnow().isoformat() + "Z"
|