Spaces:
Runtime error
Runtime error
File size: 8,080 Bytes
36dc044 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | import sqlite3
import json
import time
import numpy as np
from sentence_transformers import SentenceTransformer
class Memory:
def __init__(
self,
db_path="memory.db",
embedding_model="intfloat/multilingual-e5-large"
):
self.db = sqlite3.connect(db_path)
self.db.row_factory = sqlite3.Row
self.model = SentenceTransformer(embedding_model)
self._create_tables()
self._setup_prototypes()
# ---------------------------
# DB SETUP
# ---------------------------
def _create_tables(self):
self.db.execute("""
CREATE TABLE IF NOT EXISTS memories(
id INTEGER PRIMARY KEY AUTOINCREMENT,
role TEXT,
content TEXT,
timestamp REAL,
importance REAL,
recalls INTEGER DEFAULT 0,
last_accessed REAL DEFAULT 0,
embedding TEXT
)
""")
self.db.commit()
# ---------------------------
# EMBEDDINGS
# ---------------------------
def embed(self, text):
return self.model.encode(
text,
normalize_embeddings=True
).tolist()
def cosine_similarity(self, a, b):
a = np.array(a)
b = np.array(b)
return float(np.dot(a, b)) # normalized embeddings => dot = cosine
# ---------------------------
# PROTOTYPES (SEMANTIC TYPES)
# ---------------------------
def _setup_prototypes(self):
self.prototype_categories = {
"identity": [
"My name is John",
"I am 25 years old",
"I live in Berlin",
"I work as a teacher"
],
"preferences": [
"My favorite game is Minecraft",
"I love pizza",
"I prefer cats"
],
"relationships": [
"I have a sister",
"My wife is a doctor",
"My best friend is Alex"
],
"goals": [
"I want to learn Python",
"I plan to move abroad",
"I am saving money"
],
"health": [
"I am allergic to peanuts",
"I have diabetes",
"I take medication"
],
"temporary": [
"I ate pizza today",
"I watched a movie",
"The weather is nice"
]
}
self.prototype_embeddings = {}
for cat, examples in self.prototype_categories.items():
self.prototype_embeddings[cat] = self.model.encode(
examples,
normalize_embeddings=True
)
# ---------------------------
# CATEGORY DETECTION
# ---------------------------
def detect_memory_category(self, text, embedding):
best_category = "temporary"
best_score = -1.0
for category, prototypes in self.prototype_embeddings.items():
sims = [
self.cosine_similarity(embedding, p)
for p in prototypes
]
score = max(sims)
if score > best_score:
best_score = score
best_category = category
return best_category, best_score
# ---------------------------
# NOVELTY
# ---------------------------
def novelty_score(self, embedding):
rows = self.db.execute(
"SELECT embedding FROM memories"
).fetchall()
if not rows:
return 1.0
max_sim = 0.0
for row in rows:
stored = json.loads(row["embedding"])
sim = self.cosine_similarity(embedding, stored)
if sim > max_sim:
max_sim = sim
return float(max(0.0, 1.0 - max_sim))
# ---------------------------
# DUPLICATE CHECK
# ---------------------------
def is_duplicate(self, embedding, threshold=0.92):
rows = self.db.execute(
"SELECT embedding FROM memories"
).fetchall()
for row in rows:
stored = json.loads(row["embedding"])
sim = self.cosine_similarity(embedding, stored)
if sim >= threshold:
return True
return False
# ---------------------------
# IMPORTANCE
# ---------------------------
def calculate_importance(self, text, embedding):
category, confidence = self.detect_memory_category(
text,
embedding
)
novelty = self.novelty_score(embedding)
weights = {
"identity": 1.0,
"health": 1.0,
"relationships": 0.95,
"goals": 0.9,
"preferences": 0.75,
"temporary": 0.2
}
semantic_importance = confidence * weights[category]
importance = (
semantic_importance * 0.7 +
novelty * 0.3
)
return float(np.clip(importance, 0.0, 1.0))
# ---------------------------
# ADD MEMORY
# ---------------------------
def add(self, role, content):
embedding = self.embed(content)
if self.is_duplicate(embedding):
return
importance = self.calculate_importance(content, embedding)
self.db.execute("""
INSERT INTO memories(
role,
content,
timestamp,
importance,
embedding
)
VALUES (?, ?, ?, ?, ?)
""", (
role,
content,
time.time(),
importance,
json.dumps(embedding)
))
self.db.commit()
# ---------------------------
# RETRIEVAL
# ---------------------------
def retrieve(self, query, top_k=10):
query_embedding = self.embed(query)
rows = self.db.execute(
"SELECT * FROM memories"
).fetchall()
now = time.time()
scored = []
for row in rows:
embedding = json.loads(row["embedding"])
similarity = self.cosine_similarity(
query_embedding,
embedding
)
age_days = (now - row["timestamp"]) / 86400
recency = 1 / (1 + age_days * 0.05)
recall_bonus = min(row["recalls"] * 0.02, 0.2)
final_score = (
similarity
* (1 + row["importance"])
* (1 + recency * 0.3)
* (1 + recall_bonus)
)
scored.append((final_score, row))
scored.sort(key=lambda x: x[0], reverse=True)
memories = []
for _, row in scored[:top_k]:
self.db.execute("""
UPDATE memories
SET recalls = recalls + 1,
last_accessed = ?
WHERE id = ?
""", (now, row["id"]))
memories.append({
"id": row["id"],
"role": row["role"],
"content": row["content"],
"importance": row["importance"]
})
self.db.commit()
return memories
# ---------------------------
# CONTEXT BUILDER
# ---------------------------
def build_context(self, query, top_k=10):
memories = self.retrieve(query, top_k)
return "\n".join(
f"{m['role']}: {m['content']}"
for m in memories
)
# ---------------------------
# UTILITIES
# ---------------------------
def recent(self, limit=20):
rows = self.db.execute("""
SELECT * FROM memories
ORDER BY id DESC
LIMIT ?
""", (limit,)).fetchall()
return [dict(r) for r in rows]
def count(self):
return self.db.execute(
"SELECT COUNT(*) FROM memories"
).fetchone()[0]
def clear(self):
self.db.execute("DELETE FROM memories")
self.db.commit()
def close(self):
self.db.close() |