Spaces:
Sleeping
Sleeping
feat: swap ChromaDB for Qdrant Cloud — persistent cross-session memory
Browse files- memory.py +90 -73
- requirements.txt +1 -1
memory.py
CHANGED
|
@@ -1,21 +1,34 @@
|
|
|
|
|
|
|
|
| 1 |
import uuid
|
| 2 |
from datetime import datetime, timezone
|
| 3 |
|
| 4 |
-
import
|
|
|
|
|
|
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
|
|
|
|
|
|
|
| 7 |
_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
-
def
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
)
|
| 18 |
-
return _collections[user_id]
|
| 19 |
|
| 20 |
|
| 21 |
def get_embedding(text: str) -> list[float]:
|
|
@@ -23,103 +36,107 @@ def get_embedding(text: str) -> list[float]:
|
|
| 23 |
|
| 24 |
|
| 25 |
def add_memory(fact: str, metadata: dict, user_id: str = "guest") -> str:
|
|
|
|
|
|
|
| 26 |
memory_id = str(uuid.uuid4())
|
| 27 |
-
|
| 28 |
-
|
| 29 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 30 |
"usage_count": 0,
|
| 31 |
"type": metadata.get("type", "general"),
|
| 32 |
-
**metadata,
|
| 33 |
}
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
documents=[fact],
|
| 38 |
-
metadatas=[meta],
|
| 39 |
)
|
| 40 |
return memory_id
|
| 41 |
|
| 42 |
|
| 43 |
def retrieve_relevant(query: str, user_id: str = "guest", top_k: int = 5) -> list[dict]:
|
| 44 |
-
col =
|
| 45 |
-
|
|
|
|
| 46 |
if count == 0:
|
| 47 |
return []
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
memories = []
|
| 52 |
-
for
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
| 58 |
return memories
|
| 59 |
|
| 60 |
|
| 61 |
def get_all_memories(user_id: str = "guest") -> list[dict]:
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
memories = [
|
| 64 |
-
{"id":
|
| 65 |
-
for
|
| 66 |
-
results["ids"], results["documents"], results["metadatas"]
|
| 67 |
-
)
|
| 68 |
]
|
| 69 |
-
return sorted(
|
| 70 |
-
memories, key=lambda m: m["metadata"].get("timestamp", ""), reverse=True
|
| 71 |
-
)
|
| 72 |
|
| 73 |
|
| 74 |
def is_duplicate(new_fact: str, user_id: str = "guest", threshold: float = 0.92) -> bool:
|
| 75 |
-
col =
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
embedding = get_embedding(new_fact)
|
| 79 |
-
results = col.query(query_embeddings=[embedding], n_results=1)
|
| 80 |
-
if not results["distances"][0]:
|
| 81 |
return False
|
| 82 |
-
|
| 83 |
-
return
|
| 84 |
|
| 85 |
|
| 86 |
def get_contradiction_candidate(new_fact: str, user_id: str = "guest") -> dict | None:
|
| 87 |
-
col =
|
| 88 |
-
|
|
|
|
| 89 |
return None
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
return None
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
return {
|
| 98 |
-
"id": results["ids"][0][0],
|
| 99 |
-
"fact": results["documents"][0][0],
|
| 100 |
-
"similarity": similarity,
|
| 101 |
-
}
|
| 102 |
return None
|
| 103 |
|
| 104 |
|
| 105 |
def correct_memory(old_memory_id: str, new_fact: str, user_id: str = "guest") -> None:
|
| 106 |
-
col =
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
| 120 |
)
|
| 121 |
|
| 122 |
|
| 123 |
def delete_all_memories(user_id: str = "guest") -> None:
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
import uuid
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
from qdrant_client import QdrantClient
|
| 8 |
+
from qdrant_client.models import Distance, PointStruct, VectorParams
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 14 |
+
_EMBEDDING_DIM = 384
|
| 15 |
+
_client = QdrantClient(
|
| 16 |
+
url=os.getenv("QDRANT_CLUSTER_ENDPOINT"),
|
| 17 |
+
api_key=os.getenv("QDRANT_API_KEY"),
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _col(user_id: str) -> str:
|
| 22 |
+
return "user_" + re.sub(r"[^a-z0-9]", "_", user_id.lower())
|
| 23 |
|
| 24 |
|
| 25 |
+
def _ensure_collection(name: str) -> None:
|
| 26 |
+
existing = {c.name for c in _client.get_collections().collections}
|
| 27 |
+
if name not in existing:
|
| 28 |
+
_client.create_collection(
|
| 29 |
+
collection_name=name,
|
| 30 |
+
vectors_config=VectorParams(size=_EMBEDDING_DIM, distance=Distance.COSINE),
|
| 31 |
)
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
def get_embedding(text: str) -> list[float]:
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def add_memory(fact: str, metadata: dict, user_id: str = "guest") -> str:
|
| 39 |
+
col = _col(user_id)
|
| 40 |
+
_ensure_collection(col)
|
| 41 |
memory_id = str(uuid.uuid4())
|
| 42 |
+
payload = {
|
| 43 |
+
"fact": fact,
|
| 44 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 45 |
"usage_count": 0,
|
| 46 |
"type": metadata.get("type", "general"),
|
|
|
|
| 47 |
}
|
| 48 |
+
_client.upsert(
|
| 49 |
+
collection_name=col,
|
| 50 |
+
points=[PointStruct(id=memory_id, vector=get_embedding(fact), payload=payload)],
|
|
|
|
|
|
|
| 51 |
)
|
| 52 |
return memory_id
|
| 53 |
|
| 54 |
|
| 55 |
def retrieve_relevant(query: str, user_id: str = "guest", top_k: int = 5) -> list[dict]:
|
| 56 |
+
col = _col(user_id)
|
| 57 |
+
_ensure_collection(col)
|
| 58 |
+
count = _client.get_collection(col).points_count
|
| 59 |
if count == 0:
|
| 60 |
return []
|
| 61 |
+
response = _client.query_points(
|
| 62 |
+
collection_name=col,
|
| 63 |
+
query=get_embedding(query),
|
| 64 |
+
limit=min(top_k, count),
|
| 65 |
+
with_payload=True,
|
| 66 |
+
)
|
| 67 |
memories = []
|
| 68 |
+
for hit in response.points:
|
| 69 |
+
memories.append({"id": hit.id, "fact": hit.payload["fact"], "metadata": hit.payload})
|
| 70 |
+
_client.set_payload(
|
| 71 |
+
collection_name=col,
|
| 72 |
+
payload={"usage_count": hit.payload.get("usage_count", 0) + 1},
|
| 73 |
+
points=[hit.id],
|
| 74 |
+
)
|
| 75 |
return memories
|
| 76 |
|
| 77 |
|
| 78 |
def get_all_memories(user_id: str = "guest") -> list[dict]:
|
| 79 |
+
col = _col(user_id)
|
| 80 |
+
_ensure_collection(col)
|
| 81 |
+
points, _ = _client.scroll(collection_name=col, limit=500, with_payload=True)
|
| 82 |
memories = [
|
| 83 |
+
{"id": str(p.id), "fact": p.payload["fact"], "metadata": p.payload}
|
| 84 |
+
for p in points
|
|
|
|
|
|
|
| 85 |
]
|
| 86 |
+
return sorted(memories, key=lambda m: m["metadata"].get("timestamp", ""), reverse=True)
|
|
|
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
def is_duplicate(new_fact: str, user_id: str = "guest", threshold: float = 0.92) -> bool:
|
| 90 |
+
col = _col(user_id)
|
| 91 |
+
_ensure_collection(col)
|
| 92 |
+
if _client.get_collection(col).points_count == 0:
|
|
|
|
|
|
|
|
|
|
| 93 |
return False
|
| 94 |
+
response = _client.query_points(collection_name=col, query=get_embedding(new_fact), limit=1)
|
| 95 |
+
return bool(response.points) and response.points[0].score >= threshold
|
| 96 |
|
| 97 |
|
| 98 |
def get_contradiction_candidate(new_fact: str, user_id: str = "guest") -> dict | None:
|
| 99 |
+
col = _col(user_id)
|
| 100 |
+
_ensure_collection(col)
|
| 101 |
+
if _client.get_collection(col).points_count == 0:
|
| 102 |
return None
|
| 103 |
+
response = _client.query_points(
|
| 104 |
+
collection_name=col,
|
| 105 |
+
query=get_embedding(new_fact),
|
| 106 |
+
limit=1,
|
| 107 |
+
with_payload=True,
|
| 108 |
+
)
|
| 109 |
+
if not response.points:
|
| 110 |
return None
|
| 111 |
+
hit = response.points[0]
|
| 112 |
+
if 0.75 <= hit.score < 0.92:
|
| 113 |
+
return {"id": str(hit.id), "fact": hit.payload["fact"], "similarity": hit.score}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
return None
|
| 115 |
|
| 116 |
|
| 117 |
def correct_memory(old_memory_id: str, new_fact: str, user_id: str = "guest") -> None:
|
| 118 |
+
col = _col(user_id)
|
| 119 |
+
existing = _client.retrieve(collection_name=col, ids=[old_memory_id], with_payload=True)
|
| 120 |
+
old_payload = existing[0].payload if existing else {}
|
| 121 |
+
_client.upsert(
|
| 122 |
+
collection_name=col,
|
| 123 |
+
points=[
|
| 124 |
+
PointStruct(
|
| 125 |
+
id=old_memory_id,
|
| 126 |
+
vector=get_embedding(new_fact),
|
| 127 |
+
payload={
|
| 128 |
+
**old_payload,
|
| 129 |
+
"fact": new_fact,
|
| 130 |
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 131 |
+
"corrected": True,
|
| 132 |
+
},
|
| 133 |
+
)
|
| 134 |
+
],
|
| 135 |
)
|
| 136 |
|
| 137 |
|
| 138 |
def delete_all_memories(user_id: str = "guest") -> None:
|
| 139 |
+
try:
|
| 140 |
+
_client.delete_collection(_col(user_id))
|
| 141 |
+
except Exception:
|
| 142 |
+
pass
|
requirements.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
streamlit>=1.32.0
|
| 2 |
groq>=0.4.0
|
| 3 |
-
|
| 4 |
sentence-transformers>=3.0.0
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
fastapi>=0.110.0
|
|
|
|
| 1 |
streamlit>=1.32.0
|
| 2 |
groq>=0.4.0
|
| 3 |
+
qdrant-client>=1.9.0
|
| 4 |
sentence-transformers>=3.0.0
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
fastapi>=0.110.0
|