Tpayne101 commited on
Commit
9e84bed
·
verified ·
1 Parent(s): 93d62e3

Create semantic_memory.py

Browse files
Files changed (1) hide show
  1. semantic_memory.py +132 -13
semantic_memory.py CHANGED
@@ -1,19 +1,138 @@
 
 
 
1
  from sentence_transformers import SentenceTransformer, util
2
- import torch
 
 
 
 
 
 
 
 
3
 
4
  class SemanticMemory:
5
- def __init__(self):
6
- self.model = SentenceTransformer("all-MiniLM-L6-v2")
7
- self.entries = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- def add(self, text):
10
- emb = self.model.encode(text, convert_to_tensor=True)
11
- self.entries.append((text, emb))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- def recall(self, query, top_k=3):
14
- if not self.entries:
15
- return ["No stored context yet."]
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  q_emb = self.model.encode(query, convert_to_tensor=True)
17
- scores = [(t, float(util.cos_sim(q_emb, e))) for t, e in self.entries]
18
- scores.sort(key=lambda x: x[1], reverse=True)
19
- return [t for t, s in scores[:top_k]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # semantic_memory.py
2
+ import json, os, math, time
3
+ from typing import List, Dict, Any, Tuple
4
  from sentence_transformers import SentenceTransformer, util
5
+
6
+ DEFAULT_STORE = "mem_store.json"
7
+ MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
8
+
9
+ EMOTION_WORDS = {
10
+ "love": 0.25, "hate": 0.25, "excited": 0.2, "hyped": 0.2, "proud": 0.2,
11
+ "stressed": 0.2, "angry": 0.2, "furious": 0.25, "grateful": 0.15,
12
+ "dream": 0.15, "goal": 0.15, "mission": 0.15, "ambitious": 0.15
13
+ }
14
 
15
  class SemanticMemory:
16
+ """
17
+ Vector memory with importance weighting, recency decay, and simple emotion boost.
18
+ Persists to a small JSON file so it survives restarts.
19
+ """
20
+ def __init__(self, store_path: str = DEFAULT_STORE):
21
+ self.store_path = store_path
22
+ os.environ.setdefault("TRANSFORMERS_CACHE", "/home/user/.cache")
23
+ self.model = SentenceTransformer(MODEL_NAME)
24
+ self._load()
25
+
26
+ # ---------- persistence ----------
27
+ def _load(self):
28
+ if os.path.exists(self.store_path):
29
+ with open(self.store_path, "r") as f:
30
+ self.store: List[Dict[str, Any]] = json.load(f)
31
+ else:
32
+ self.store = []
33
+ self._flush()
34
+
35
+ def _flush(self):
36
+ with open(self.store_path, "w") as f:
37
+ json.dump(self.store, f, indent=2)
38
+
39
+ # ---------- scoring helpers ----------
40
+ @staticmethod
41
+ def _now() -> float:
42
+ return time.time()
43
+
44
+ @staticmethod
45
+ def _base_weight_from_text(text: str) -> float:
46
+ """
47
+ 0.2 base + features:
48
+ - caps/emphasis
49
+ - contains numbers (often facts)
50
+ - emotion keywords
51
+ """
52
+ t = text.strip()
53
+ weight = 0.2
54
+ if any(c.isupper() for c in t) and sum(map(str.isupper, t)) > 6:
55
+ weight += 0.15
56
+ if any(ch.isdigit() for ch in t):
57
+ weight += 0.1
58
+ lower = t.lower()
59
+ for w, boost in EMOTION_WORDS.items():
60
+ if w in lower:
61
+ weight += boost
62
+ return max(0.2, min(weight, 1.0))
63
+
64
+ @staticmethod
65
+ def _decay(age_hours: float, half_life_hours: float = 48.0) -> float:
66
+ """
67
+ Exponential decay: 0.5 every `half_life_hours`.
68
+ """
69
+ if age_hours <= 0:
70
+ return 1.0
71
+ # factor = 0.5 ** (age/half_life)
72
+ return 0.5 ** (age_hours / half_life_hours)
73
 
74
+ # ---------- public API ----------
75
+ def add(self, text: str, source: str = "user", tags: List[str] = None, weight: float = None):
76
+ if not text or not text.strip():
77
+ return
78
+ tags = tags or []
79
+ emb = self.model.encode(text, convert_to_tensor=True).tolist()
80
+ w = weight if weight is not None else self._base_weight_from_text(text)
81
+ item = {
82
+ "text": text.strip(),
83
+ "source": source,
84
+ "tags": tags,
85
+ "ts": self._now(),
86
+ "weight": float(round(w, 4)),
87
+ "embedding": emb
88
+ }
89
+ self.store.append(item)
90
+ self._flush()
91
 
92
+ def _torch_tensor(self, x):
93
+ # Lazy import torch to keep import time snappy
94
+ import torch
95
+ return torch.tensor(x)
96
+
97
+ def search(self, query: str, top_k: int = 5,
98
+ alpha: float = 0.65, beta: float = 0.35) -> List[Tuple[Dict[str, Any], float]]:
99
+ """
100
+ Returns list of (memory_item, score) sorted by score desc.
101
+
102
+ score = alpha * cosine_similarity + beta * (weight * recency_decay)
103
+ """
104
+ if not self.store:
105
+ return []
106
+
107
+ import torch
108
  q_emb = self.model.encode(query, convert_to_tensor=True)
109
+ mem_embs = self._torch_tensor([m["embedding"] for m in self.store])
110
+
111
+ sims = util.cos_sim(q_emb, mem_embs).squeeze(0) # shape [N]
112
+
113
+ now = self._now()
114
+ scored: List[Tuple[int, float]] = []
115
+ for i, m in enumerate(self.store):
116
+ age_hours = (now - m["ts"]) / 3600.0
117
+ decay = self._decay(age_hours)
118
+ weighted = m["weight"] * decay
119
+ score = float(alpha * sims[i].item() + beta * weighted)
120
+ scored.append((i, score))
121
+
122
+ scored.sort(key=lambda x: x[1], reverse=True)
123
+ results: List[Tuple[Dict[str, Any], float]] = []
124
+ for idx, sc in scored[:top_k]:
125
+ results.append((self.store[idx], float(round(sc, 4))))
126
+ return results
127
+
128
+ def summarize_context(self, query: str, top_k: int = 5) -> str:
129
+ """
130
+ Lightweight summarizer over top_k hits.
131
+ """
132
+ hits = self.search(query, top_k=top_k)
133
+ if not hits:
134
+ return "No memory yet."
135
+ bullets = []
136
+ for m, sc in hits:
137
+ bullets.append(f"- {m['text']} (score: {sc})")
138
+ return "Relevant memories:\n" + "\n".join(bullets)