killbizz commited on
Commit
d6c1f0b
·
1 Parent(s): f37d148

feat: swap ChromaDB for Qdrant Cloud — persistent cross-session memory

Browse files
Files changed (2) hide show
  1. memory.py +90 -73
  2. requirements.txt +1 -1
memory.py CHANGED
@@ -1,21 +1,34 @@
 
 
1
  import uuid
2
  from datetime import datetime, timezone
3
 
4
- import chromadb
 
 
5
  from sentence_transformers import SentenceTransformer
6
 
 
 
7
  _model = SentenceTransformer("all-MiniLM-L6-v2")
8
- _client = chromadb.PersistentClient(path="./chroma_store")
9
- _collections: dict[str, chromadb.Collection] = {}
 
 
 
 
 
 
 
10
 
11
 
12
- def _get_collection(user_id: str) -> chromadb.Collection:
13
- if user_id not in _collections:
14
- _collections[user_id] = _client.get_or_create_collection(
15
- name=f"user_{user_id}",
16
- metadata={"hnsw:space": "cosine"},
 
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
- embedding = get_embedding(fact)
28
- meta = {
29
  "timestamp": datetime.now(timezone.utc).isoformat(),
30
  "usage_count": 0,
31
  "type": metadata.get("type", "general"),
32
- **metadata,
33
  }
34
- _get_collection(user_id).add(
35
- ids=[memory_id],
36
- embeddings=[embedding],
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 = _get_collection(user_id)
45
- count = col.count()
 
46
  if count == 0:
47
  return []
48
- n = min(top_k, count)
49
- embedding = get_embedding(query)
50
- results = col.query(query_embeddings=[embedding], n_results=n)
 
 
 
51
  memories = []
52
- for memory_id, fact, meta in zip(
53
- results["ids"][0], results["documents"][0], results["metadatas"][0]
54
- ):
55
- memories.append({"id": memory_id, "fact": fact, "metadata": meta})
56
- updated_meta = {**meta, "usage_count": meta.get("usage_count", 0) + 1}
57
- col.update(ids=[memory_id], metadatas=[updated_meta])
 
58
  return memories
59
 
60
 
61
  def get_all_memories(user_id: str = "guest") -> list[dict]:
62
- results = _get_collection(user_id).get()
 
 
63
  memories = [
64
- {"id": mid, "fact": doc, "metadata": meta}
65
- for mid, doc, meta in zip(
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 = _get_collection(user_id)
76
- if col.count() == 0:
77
- return False
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
- similarity = 1 - results["distances"][0][0]
83
- return similarity >= threshold
84
 
85
 
86
  def get_contradiction_candidate(new_fact: str, user_id: str = "guest") -> dict | None:
87
- col = _get_collection(user_id)
88
- if col.count() == 0:
 
89
  return None
90
- embedding = get_embedding(new_fact)
91
- results = col.query(query_embeddings=[embedding], n_results=1)
92
- if not results["distances"][0]:
 
 
 
 
93
  return None
94
- distance = results["distances"][0][0]
95
- similarity = 1 - distance
96
- if 0.75 <= similarity < 0.92:
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 = _get_collection(user_id)
107
- embedding = get_embedding(new_fact)
108
- existing = col.get(ids=[old_memory_id])
109
- old_meta = existing["metadatas"][0] if existing["metadatas"] else {}
110
- updated_meta = {
111
- **old_meta,
112
- "timestamp": datetime.now(timezone.utc).isoformat(),
113
- "corrected": True,
114
- }
115
- col.update(
116
- ids=[old_memory_id],
117
- embeddings=[embedding],
118
- documents=[new_fact],
119
- metadatas=[updated_meta],
 
 
 
120
  )
121
 
122
 
123
  def delete_all_memories(user_id: str = "guest") -> None:
124
- _client.delete_collection(f"user_{user_id}")
125
- _collections.pop(user_id, None)
 
 
 
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
- chromadb>=0.5.0
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