Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- memory/__init__.py +0 -0
- memory/faiss_store.py +108 -0
memory/__init__.py
ADDED
|
File without changes
|
memory/faiss_store.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PsycheOS — FAISS Memory Store
|
| 3 |
+
Cross-session RAG for patient history retrieval.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
import hashlib
|
| 9 |
+
from typing import List, Optional
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import numpy as np
|
| 14 |
+
import faiss
|
| 15 |
+
from sentence_transformers import SentenceTransformer
|
| 16 |
+
FAISS_AVAILABLE = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
FAISS_AVAILABLE = False
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class MemoryStore:
|
| 22 |
+
"""
|
| 23 |
+
Stores and retrieves conversation history using FAISS vector search.
|
| 24 |
+
Falls back to keyword-based retrieval if FAISS/sentence-transformers unavailable.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, dim: int = 384, index_path: str = "/tmp/psycheos_faiss"):
|
| 28 |
+
self.dim = dim
|
| 29 |
+
self.index_path = index_path
|
| 30 |
+
self.memories = [] # list of {text, distress, timestamp, embedding_idx}
|
| 31 |
+
self.faiss_available = FAISS_AVAILABLE
|
| 32 |
+
self._encoder = None
|
| 33 |
+
self._index = None
|
| 34 |
+
|
| 35 |
+
if self.faiss_available:
|
| 36 |
+
try:
|
| 37 |
+
self._encoder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 38 |
+
self._index = faiss.IndexFlatL2(dim)
|
| 39 |
+
except Exception:
|
| 40 |
+
self.faiss_available = False
|
| 41 |
+
|
| 42 |
+
def store(self, message: str, distress_level: int, session: int = 1):
|
| 43 |
+
"""Store a message with its distress level and metadata."""
|
| 44 |
+
entry = {
|
| 45 |
+
"text": message,
|
| 46 |
+
"distress": distress_level,
|
| 47 |
+
"session": session,
|
| 48 |
+
"timestamp": datetime.now().isoformat(),
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
if self.faiss_available and self._encoder and self._index:
|
| 52 |
+
try:
|
| 53 |
+
emb = self._encoder.encode([message])
|
| 54 |
+
self._index.add(emb)
|
| 55 |
+
entry["embedding_idx"] = self._index.ntotal - 1
|
| 56 |
+
except Exception:
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
self.memories.append(entry)
|
| 60 |
+
|
| 61 |
+
def retrieve(self, query: str, k: int = 3) -> str:
|
| 62 |
+
"""Retrieve top-k relevant past memories."""
|
| 63 |
+
if not self.memories:
|
| 64 |
+
return ""
|
| 65 |
+
|
| 66 |
+
if self.faiss_available and self._encoder and self._index and self._index.ntotal > 0:
|
| 67 |
+
try:
|
| 68 |
+
import numpy as np
|
| 69 |
+
q_emb = self._encoder.encode([query])
|
| 70 |
+
k_actual = min(k, self._index.ntotal)
|
| 71 |
+
distances, indices = self._index.search(q_emb, k_actual)
|
| 72 |
+
retrieved = []
|
| 73 |
+
for idx in indices[0]:
|
| 74 |
+
if 0 <= idx < len(self.memories):
|
| 75 |
+
m = self.memories[idx]
|
| 76 |
+
retrieved.append(f"[Distress {m['distress']}] {m['text'][:80]}")
|
| 77 |
+
return " | ".join(retrieved)
|
| 78 |
+
except Exception:
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
# Keyword fallback
|
| 82 |
+
query_words = set(query.lower().split())
|
| 83 |
+
scored = []
|
| 84 |
+
for m in self.memories[-20:]:
|
| 85 |
+
mem_words = set(m["text"].lower().split())
|
| 86 |
+
overlap = len(query_words & mem_words)
|
| 87 |
+
scored.append((overlap, m))
|
| 88 |
+
|
| 89 |
+
scored.sort(reverse=True)
|
| 90 |
+
top = scored[:k]
|
| 91 |
+
if not top:
|
| 92 |
+
return ""
|
| 93 |
+
|
| 94 |
+
return " | ".join(
|
| 95 |
+
f"[Distress {m['distress']}] {m['text'][:60]}"
|
| 96 |
+
for _, m in top if m["text"]
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
def get_session_summary(self) -> dict:
|
| 100 |
+
"""Return a summary of stored memories."""
|
| 101 |
+
if not self.memories:
|
| 102 |
+
return {"total": 0, "avg_distress": 0, "max_distress": 0}
|
| 103 |
+
distress_levels = [m["distress"] for m in self.memories]
|
| 104 |
+
return {
|
| 105 |
+
"total": len(self.memories),
|
| 106 |
+
"avg_distress": round(sum(distress_levels) / len(distress_levels), 2),
|
| 107 |
+
"max_distress": max(distress_levels),
|
| 108 |
+
}
|