recallic-engine 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- recallic_engine/__init__.py +10 -0
- recallic_engine/api/__init__.py +0 -0
- recallic_engine/api/deps.py +36 -0
- recallic_engine/brain/__init__.py +0 -0
- recallic_engine/brain/features/__init__.py +1 -0
- recallic_engine/brain/features/aggregation_check.py +796 -0
- recallic_engine/brain/features/answer_check.default.json +23 -0
- recallic_engine/brain/features/answer_check.py +199 -0
- recallic_engine/brain/features/answer_check_learning.py +164 -0
- recallic_engine/brain/features/answer_verify.py +78 -0
- recallic_engine/brain/features/as_of.py +122 -0
- recallic_engine/brain/features/calibration.py +119 -0
- recallic_engine/brain/features/dates.py +124 -0
- recallic_engine/brain/features/facts.py +472 -0
- recallic_engine/brain/features/implicit.py +208 -0
- recallic_engine/brain/features/learned_facts.py +121 -0
- recallic_engine/brain/features/modes.py +70 -0
- recallic_engine/brain/features/query.py +297 -0
- recallic_engine/brain/features/reranker.py +87 -0
- recallic_engine/brain/features/schemas.py +222 -0
- recallic_engine/brain/features/summarize.py +72 -0
- recallic_engine/brain/features/trust.default.json +37 -0
- recallic_engine/brain/features/trust.py +165 -0
- recallic_engine/brain/memory/__init__.py +0 -0
- recallic_engine/brain/memory/archive/__init__.py +0 -0
- recallic_engine/brain/memory/archive/archive_store.py +64 -0
- recallic_engine/brain/memory/audit.py +84 -0
- recallic_engine/brain/memory/episodic/__init__.py +0 -0
- recallic_engine/brain/memory/episodic/episodic_memory.py +500 -0
- recallic_engine/brain/memory/freshness.py +104 -0
- recallic_engine/brain/memory/index_key.py +55 -0
- recallic_engine/brain/memory/index_sync.py +109 -0
- recallic_engine/brain/memory/long_term/__init__.py +0 -0
- recallic_engine/brain/memory/long_term/long_term_memory.py +80 -0
- recallic_engine/brain/memory/manager.py +326 -0
- recallic_engine/brain/memory/proactive.py +81 -0
- recallic_engine/brain/memory/reasoning_engine.py +35 -0
- recallic_engine/brain/memory/recall_engine.py +1211 -0
- recallic_engine/brain/memory/reflective/__init__.py +0 -0
- recallic_engine/brain/memory/reflective/reflective_memory.py +58 -0
- recallic_engine/brain/memory/semantic/__init__.py +0 -0
- recallic_engine/brain/memory/semantic/semantic_memory.py +167 -0
- recallic_engine/brain/memory/short_term/__init__.py +0 -0
- recallic_engine/brain/memory/short_term/sensory.py +33 -0
- recallic_engine/brain/memory/truth_engine.py +110 -0
- recallic_engine/brain/memory/update_classifier.py +76 -0
- recallic_engine/brain/memory/updates.py +572 -0
- recallic_engine/brain/memory/working/__init__.py +0 -0
- recallic_engine/brain/memory/working/working_memory.py +74 -0
- recallic_engine/brain/memory_ranking/__init__.py +0 -0
- recallic_engine/brain/memory_ranking/fit_importance.py +91 -0
- recallic_engine/brain/memory_ranking/fit_ranker.py +188 -0
- recallic_engine/brain/memory_ranking/importance_ranker.py +166 -0
- recallic_engine/brain/memory_ranking/importance_weights.default.json +16 -0
- recallic_engine/brain/memory_ranking/importance_weights.prior.json +14 -0
- recallic_engine/brain/memory_ranking/logistic.py +72 -0
- recallic_engine/brain/memory_ranking/ranker.py +414 -0
- recallic_engine/brain/memory_ranking/ranker_model.default.json +54 -0
- recallic_engine/brain/memory_ranking/ranker_model.hash.json +54 -0
- recallic_engine/brain/memory_ranking/ranker_model.prior.json +22 -0
- recallic_engine/brain/memory_ranking/reinforcement_learning.py +57 -0
- recallic_engine/brain/memory_ranking/self_improve.py +187 -0
- recallic_engine/brain/models/__init__.py +0 -0
- recallic_engine/brain/models/model_router.py +189 -0
- recallic_engine/brain/models/onnx_runtime.py +149 -0
- recallic_engine/brain/prediction/__init__.py +0 -0
- recallic_engine/brain/prediction/predictive_recall.py +14 -0
- recallic_engine/brain/utils/__init__.py +0 -0
- recallic_engine/brain/utils/decay_logic.py +27 -0
- recallic_engine/brain/world_model/__init__.py +0 -0
- recallic_engine/brain/world_model/planning_engine.py +47 -0
- recallic_engine/brain/world_model/prediction_engine.py +87 -0
- recallic_engine/brain/world_model/state_inference.py +100 -0
- recallic_engine/brain/world_model/timeline_engine.py +67 -0
- recallic_engine/config.yaml +518 -0
- recallic_engine/embedded.py +65 -0
- recallic_engine/settings.py +115 -0
- recallic_engine/tools/__init__.py +0 -0
- recallic_engine/tools/portable.py +137 -0
- recallic_engine/utils/__init__.py +0 -0
- recallic_engine/utils/internal_client.py +82 -0
- recallic_engine/utils/local_engine.py +136 -0
- recallic_engine/utils/paths.py +29 -0
- recallic_engine-0.1.0.dist-info/METADATA +48 -0
- recallic_engine-0.1.0.dist-info/RECORD +89 -0
- recallic_engine-0.1.0.dist-info/WHEEL +5 -0
- recallic_engine-0.1.0.dist-info/licenses/LICENSE +105 -0
- recallic_engine-0.1.0.dist-info/licenses/NOTICE +19 -0
- recallic_engine-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Query analysis and slot matching for recall (no LLM, no domain-specific rules).
|
|
3
|
+
|
|
4
|
+
analyze_query(q) returns:
|
|
5
|
+
strong_entities named things the question is about: capitalised spans
|
|
6
|
+
("Project Kestrel", "Anita") and "user" for first-person
|
|
7
|
+
questions ("my", "I", "me").
|
|
8
|
+
weak_entities content words; these let "What time is standup?" match an
|
|
9
|
+
event slot "standup::when".
|
|
10
|
+
relations relation words the question asks about, expanded through
|
|
11
|
+
English synonym groups ("where ... live" -> location,
|
|
12
|
+
"due" -> deadline, "how much money" -> budget).
|
|
13
|
+
|
|
14
|
+
Matching is fuzzy where it should be: entity ids match on equality, on
|
|
15
|
+
containment ("kestrel" in "projectkestrel"), or on a string-similarity ratio
|
|
16
|
+
>= 0.85 (typos such as "Kestral").
|
|
17
|
+
"""
|
|
18
|
+
import re
|
|
19
|
+
from functools import lru_cache
|
|
20
|
+
|
|
21
|
+
from recallic_engine.brain.memory_ranking.importance_ranker import content_terms
|
|
22
|
+
|
|
23
|
+
# Each group is a set of words that ask about / name the same relation.
|
|
24
|
+
RELATION_GROUPS = [
|
|
25
|
+
{"location", "live", "lives", "living", "based", "city", "reside", "home", "where", "moved", "hometown"},
|
|
26
|
+
{"employer", "work", "works", "working", "job", "company", "employ", "employs", "employed"},
|
|
27
|
+
{"name", "called", "named", "call", "alias", "alias_of"},
|
|
28
|
+
{"birthday", "birth", "born"},
|
|
29
|
+
{"age", "old"},
|
|
30
|
+
{"deadline", "due", "deliver", "delivery"},
|
|
31
|
+
{"when", "date", "time", "schedule", "scheduled", "day"},
|
|
32
|
+
{"budget", "money", "cost", "price", "spend", "funding", "funds", "much"},
|
|
33
|
+
{"allergy", "allergic", "allergies", "eat", "intolerant"},
|
|
34
|
+
{"phone", "number", "mobile"},
|
|
35
|
+
{"lead", "leads", "manager", "manages", "owner", "owns", "head", "runs"},
|
|
36
|
+
{"email", "mail", "address"},
|
|
37
|
+
{"role", "profession", "occupation"},
|
|
38
|
+
{"status", "state", "phase", "stage"},
|
|
39
|
+
{"password", "code", "passcode", "pin"},
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
_FIRST_PERSON = re.compile(r"\b(i|me|my|mine|myself|i'm|i've|i'd|i'll)\b", re.I)
|
|
43
|
+
_CAP_SPAN = re.compile(r"\b[A-Z][\w'’-]*(?:\s+[A-Z][\w'’-]*)*")
|
|
44
|
+
_BRACKET_PREFIX = re.compile(r"^\s*\[[^\]]*\]\s*") # e.g. a "[date]" header before the text
|
|
45
|
+
_QUESTION_WORDS = {"what", "when", "where", "who", "whom", "which", "why", "how", "do", "does", "did",
|
|
46
|
+
"is", "are", "was", "were", "can", "could", "should", "would", "will", "i", "the",
|
|
47
|
+
"a", "an", "tell", "please", "any", "is there", "what's", "whats"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def norm_id(s):
|
|
51
|
+
s = re.sub(r"['’]s\b", "", s.strip())
|
|
52
|
+
s = re.sub(r"^(?:the|a|an)\s+", "", s, flags=re.I)
|
|
53
|
+
return re.sub(r"[^a-z0-9]+", "", s.lower())
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _norm_token(t):
|
|
57
|
+
return re.sub(r"[^a-z0-9]+", "", re.sub(r"['’]s$", "", t.lower()))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _strip_leading_question_words(span):
|
|
61
|
+
words = span.split()
|
|
62
|
+
while words and words[0].lower().strip("'") in _QUESTION_WORDS:
|
|
63
|
+
words.pop(0)
|
|
64
|
+
return " ".join(words)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def capitalised_spans(text, skip_sentence_initial_words=False, skip_vocatives=False):
|
|
68
|
+
"""
|
|
69
|
+
Capitalised spans as tuples of normalised tokens ("Galaxy X-99 Primary" ->
|
|
70
|
+
("galaxy", "x99", "primary")), leading question words/articles removed.
|
|
71
|
+
|
|
72
|
+
skip_sentence_initial_words: drop a single-word span at the start of a
|
|
73
|
+
sentence unless it contains a digit ("Status of X-77?" -> only ("x77",)).
|
|
74
|
+
Used for questions, where a capitalised first word is usually not a name.
|
|
75
|
+
skip_vocatives: drop direct address — a name immediately followed by , ! or ?
|
|
76
|
+
("Thanks, Caroline!" does not make the text about Caroline).
|
|
77
|
+
"""
|
|
78
|
+
# Recall parses the same memory texts on every query: cached (a pure function of its arguments).
|
|
79
|
+
return list(_capitalised_spans(text, skip_sentence_initial_words, skip_vocatives))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@lru_cache(maxsize=20000)
|
|
83
|
+
def _capitalised_spans(text, skip_sentence_initial_words, skip_vocatives):
|
|
84
|
+
out = []
|
|
85
|
+
for m in _CAP_SPAN.finditer(text):
|
|
86
|
+
span = _strip_leading_question_words(m.group(0))
|
|
87
|
+
if not span or span.lower() in _QUESTION_WORDS:
|
|
88
|
+
continue
|
|
89
|
+
tokens = tuple(t for t in (_norm_token(w) for w in span.split()) if t)
|
|
90
|
+
if not tokens or len("".join(tokens)) < 2:
|
|
91
|
+
continue
|
|
92
|
+
before = text[:m.start()].rstrip()
|
|
93
|
+
sentence_initial = not before or before[-1] in ".!?:\n"
|
|
94
|
+
if skip_sentence_initial_words and sentence_initial and m.group(0) == span and len(tokens) == 1 \
|
|
95
|
+
and not any(c.isdigit() for c in tokens[0]):
|
|
96
|
+
continue
|
|
97
|
+
if skip_vocatives and re.match(r"\s*[,!?]", text[m.end():]):
|
|
98
|
+
continue
|
|
99
|
+
out.append(tokens)
|
|
100
|
+
return tuple(out)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def capitalised_entities(text):
|
|
104
|
+
"""Normalised ids of capitalised spans, ignoring leading question/aux words."""
|
|
105
|
+
return ["".join(t) for t in capitalised_spans(text)]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def spans_match(a, b):
|
|
109
|
+
"""Cached _spans_match (called ~10,000 times per recall); unhashable spans skip the cache."""
|
|
110
|
+
try:
|
|
111
|
+
return _spans_match_cached(a, b)
|
|
112
|
+
except TypeError:
|
|
113
|
+
return _spans_match(a, b)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@lru_cache(maxsize=200000)
|
|
117
|
+
def _spans_match_cached(a, b):
|
|
118
|
+
return _spans_match(a, b)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _spans_match(a, b):
|
|
122
|
+
"""
|
|
123
|
+
Token spans name the same entity if equal, if one is a contiguous run of the
|
|
124
|
+
other ("x99" in "galaxy x99 primary emission"; "kestrel" in "project kestrel"),
|
|
125
|
+
or if their joined forms are a one-edit typo of each other.
|
|
126
|
+
"""
|
|
127
|
+
if not a or not b:
|
|
128
|
+
return False
|
|
129
|
+
if a == b:
|
|
130
|
+
return True
|
|
131
|
+
short, long_ = sorted((a, b), key=len)
|
|
132
|
+
n = len(short)
|
|
133
|
+
if any(long_[i:i + n] == short for i in range(len(long_) - n + 1)):
|
|
134
|
+
return True
|
|
135
|
+
return entity_matches("".join(a), "".join(b))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def strip_header(text):
|
|
139
|
+
"""Text without a leading bracketed header (e.g. a timestamp)."""
|
|
140
|
+
return _BRACKET_PREFIX.sub("", text, count=1)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def is_first_person(text):
|
|
144
|
+
return bool(_FIRST_PERSON.search(text))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def expand_relations(words):
|
|
148
|
+
words = {w.lower() for w in words}
|
|
149
|
+
rels = set(words)
|
|
150
|
+
for group in RELATION_GROUPS:
|
|
151
|
+
if words & group:
|
|
152
|
+
rels |= group
|
|
153
|
+
return rels
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def analyze_query(query):
|
|
157
|
+
spans = capitalised_spans(query, skip_sentence_initial_words=True)
|
|
158
|
+
strong = ["".join(s) for s in spans]
|
|
159
|
+
if _FIRST_PERSON.search(query):
|
|
160
|
+
strong.append("user")
|
|
161
|
+
spans.append(("user",))
|
|
162
|
+
words = re.findall(r"[a-z][a-z'-]*", query.lower())
|
|
163
|
+
weak = [norm_id(t) for t in content_terms(query)]
|
|
164
|
+
return {
|
|
165
|
+
"strong_spans": list(dict.fromkeys(spans)),
|
|
166
|
+
"strong_entities": list(dict.fromkeys(strong)),
|
|
167
|
+
"weak_entities": list(dict.fromkeys(weak)),
|
|
168
|
+
"relations": expand_relations(words),
|
|
169
|
+
"asks_relation": any(set(words) & group for group in RELATION_GROUPS),
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _edit_distance_at_most_one(a, b):
|
|
174
|
+
if abs(len(a) - len(b)) > 1:
|
|
175
|
+
return False
|
|
176
|
+
if len(a) > len(b):
|
|
177
|
+
a, b = b, a
|
|
178
|
+
i = j = edits = 0
|
|
179
|
+
while i < len(a) and j < len(b):
|
|
180
|
+
if a[i] != b[j]:
|
|
181
|
+
edits += 1
|
|
182
|
+
if edits > 1:
|
|
183
|
+
return False
|
|
184
|
+
if len(a) == len(b):
|
|
185
|
+
i += 1
|
|
186
|
+
j += 1
|
|
187
|
+
else:
|
|
188
|
+
i += 1
|
|
189
|
+
j += 1
|
|
190
|
+
return edits + (len(b) - j) <= 1
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def entity_matches(a, b):
|
|
194
|
+
"""Cached _entity_matches; unhashable ids skip the cache."""
|
|
195
|
+
try:
|
|
196
|
+
return _entity_matches_cached(a, b)
|
|
197
|
+
except TypeError:
|
|
198
|
+
return _entity_matches(a, b)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@lru_cache(maxsize=200000)
|
|
202
|
+
def _entity_matches_cached(a, b):
|
|
203
|
+
return _entity_matches(a, b)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _entity_matches(a, b):
|
|
207
|
+
"""
|
|
208
|
+
Same entity if the ids are equal; or one is the other plus a separate word
|
|
209
|
+
(a prefix/suffix remainder of >= 3 chars: "projectkestrel" ~ "kestrel");
|
|
210
|
+
or they differ by a single edit and are long enough for that to be a typo
|
|
211
|
+
("kestral" ~ "kestrel"). "falconet" is NOT "falcon".
|
|
212
|
+
"""
|
|
213
|
+
if not a or not b:
|
|
214
|
+
return False
|
|
215
|
+
if a == b:
|
|
216
|
+
return True
|
|
217
|
+
short, long_ = sorted((a, b), key=len)
|
|
218
|
+
if len(short) >= 4 and (long_.startswith(short) or long_.endswith(short)) and len(long_) - len(short) >= 3:
|
|
219
|
+
return True
|
|
220
|
+
# Typo tolerance is for spelling: identifiers with digits ("x101" vs "x102") must match exactly.
|
|
221
|
+
if any(c.isdigit() for c in a + b):
|
|
222
|
+
return False
|
|
223
|
+
return len(short) >= 5 and _edit_distance_at_most_one(a, b)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def relation_matches(slot_relation, query_relations):
|
|
227
|
+
if not query_relations:
|
|
228
|
+
return False
|
|
229
|
+
parts = set(slot_relation.split("_")) | {slot_relation}
|
|
230
|
+
return bool(expand_relations(parts) & query_relations)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def slot_matches(slot, analysis, allow_weak=True):
|
|
234
|
+
"""Named (strong) entities match fuzzily; plain words (weak) only match a slot entity exactly."""
|
|
235
|
+
ent = slot.get("entity", "")
|
|
236
|
+
ent_ok = any(entity_matches(ent, e) for e in analysis["strong_entities"]) or \
|
|
237
|
+
(allow_weak and ent in analysis["weak_entities"])
|
|
238
|
+
return ent_ok and relation_matches(slot.get("relation", ""), analysis["relations"])
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def memory_entities(memory_text, slots):
|
|
242
|
+
"""Entity ids a memory talks about: its slot entities, capitalised spans, and 'user'."""
|
|
243
|
+
ents = {s.get("entity", "") for s in slots}
|
|
244
|
+
ents.update(capitalised_entities(memory_text))
|
|
245
|
+
if _FIRST_PERSON.search(memory_text):
|
|
246
|
+
ents.add("user")
|
|
247
|
+
return {e for e in ents if e}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def memory_subject(memory_text, speaker=None):
|
|
251
|
+
"""
|
|
252
|
+
Who a memory is about (answer-level attribution):
|
|
253
|
+
owner the speaker of a first-person statement ("I ran a race" said by
|
|
254
|
+
Melanie is about Melanie); the user if no speaker is recorded
|
|
255
|
+
mentions named entities in the text, excluding direct address
|
|
256
|
+
("Thanks, Caroline!") and the header
|
|
257
|
+
`speaker` comes from the store call's metadata, never guessed from the text.
|
|
258
|
+
"""
|
|
259
|
+
owner, mentions = _memory_subject(memory_text, speaker)
|
|
260
|
+
return owner, list(mentions)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@lru_cache(maxsize=20000)
|
|
264
|
+
def _memory_subject(memory_text, speaker):
|
|
265
|
+
body = strip_header(memory_text)
|
|
266
|
+
if speaker:
|
|
267
|
+
sp = re.escape(speaker.strip())
|
|
268
|
+
body = re.sub(rf"^\s*{sp}\s*:\s*", "", body, count=1)
|
|
269
|
+
owner = None
|
|
270
|
+
if is_first_person(body):
|
|
271
|
+
owner = tuple(t for t in (_norm_token(w) for w in speaker.split()) if t) if speaker else ("user",)
|
|
272
|
+
mentions = _capitalised_spans(body, False, True)
|
|
273
|
+
return owner, mentions
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# First-person forms and their third-person rewrites ({s} = speaker). English grammar only.
|
|
277
|
+
_FIRST_PERSON_REWRITES = [
|
|
278
|
+
(r"\bI'm\b|\bI am\b", "{s} is"), (r"\bI've\b|\bI have\b", "{s} has"), (r"\bI'd\b", "{s} would"),
|
|
279
|
+
(r"\bI'll\b", "{s} will"), (r"\bI was\b", "{s} was"), (r"\bmyself\b", "{s}"), (r"\bmine\b", "{s}'s"),
|
|
280
|
+
(r"\bmy\b", "{s}'s"), (r"\bme\b", "{s}"), (r"\bI\b", "{s}"),
|
|
281
|
+
]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def resolve_first_person(text, speaker):
|
|
285
|
+
"""
|
|
286
|
+
Rewrites a speaker's first-person statement in the third person, so a reader that
|
|
287
|
+
does not know who "I" is can tell whose statement it is:
|
|
288
|
+
("Melanie", "Melanie: I'm starting to realize...") -> "Melanie: Melanie is starting to realize..."
|
|
289
|
+
Text without a known speaker is returned unchanged.
|
|
290
|
+
"""
|
|
291
|
+
if not speaker:
|
|
292
|
+
return text
|
|
293
|
+
head = re.match(r"^\s*(?:\[[^\]]*\]\s*)?(?:" + re.escape(speaker.strip()) + r"\s*:\s*)?", text)
|
|
294
|
+
prefix, body = text[:head.end()], text[head.end():]
|
|
295
|
+
for pattern, repl in _FIRST_PERSON_REWRITES:
|
|
296
|
+
body = re.sub(pattern, repl.format(s=speaker.strip()), body, flags=re.I if pattern != r"\bI\b" else 0)
|
|
297
|
+
return prefix + body
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Re-ranker: a small cross-encoder reads the question and each candidate memory *together* and
|
|
3
|
+
scores how well the memory answers it.
|
|
4
|
+
|
|
5
|
+
The first ranking compares the question and each memory separately (embeddings, word overlap,
|
|
6
|
+
fact slots). That misses links which only show when both are read at once: "What indoor
|
|
7
|
+
activities has Andrew done with his girlfriend?" vs "My GF and I volunteered at a pet shelter".
|
|
8
|
+
For questions whose answer is spread over several memories (multi-hop), the evidence is usually
|
|
9
|
+
among the candidates but ranked too low to be served.
|
|
10
|
+
|
|
11
|
+
The default model (cross-encoder/ms-marco-MiniLM-L-6-v2, 22M parameters, Apache 2.0) was
|
|
12
|
+
trained on MS MARCO search queries. No LLM. It runs on CPU.
|
|
13
|
+
|
|
14
|
+
It is slower than the rest of recall (measured on an Apple M4 CPU: median recall 140 ms -> about
|
|
15
|
+
600 ms at 50 candidates), so by default it runs only when a recall asks for it (deep=True, for
|
|
16
|
+
questions whose answer is spread over several memories); `enabled: true` runs it on every recall.
|
|
17
|
+
|
|
18
|
+
Configuration (config.yaml recall.rerank): enabled, model, candidates (how many of the first
|
|
19
|
+
ranking it reads), keep (results that stay exactly where they are), context (also read each
|
|
20
|
+
memory after the message before it), max_length, threads, device (null = GPU if available).
|
|
21
|
+
How it is applied is in recall_engine.RecallEngine._rerank.
|
|
22
|
+
"""
|
|
23
|
+
import os
|
|
24
|
+
import threading
|
|
25
|
+
|
|
26
|
+
from recallic_engine import settings
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def config():
|
|
30
|
+
c = settings.get("recall.rerank", {}) or {}
|
|
31
|
+
enabled = bool(c.get("enabled", False))
|
|
32
|
+
env = os.environ.get("RECALLIC_RERANK") # "0"/"1" overrides config (CI, eval gate)
|
|
33
|
+
if env is not None:
|
|
34
|
+
enabled = env.strip() not in ("0", "false", "no", "")
|
|
35
|
+
return {"enabled": enabled, "model": c.get("model") or "cross-encoder/ms-marco-MiniLM-L-6-v2",
|
|
36
|
+
"candidates": int(c.get("candidates", 100)), "keep": int(c.get("keep", 3)),
|
|
37
|
+
"max_length": int(c.get("max_length", 256)), "threads": c.get("threads"), "device": c.get("device"),
|
|
38
|
+
"preload": bool(c.get("preload", True)), "auto": bool(c.get("auto", False)),
|
|
39
|
+
"context": bool(c.get("context", True)), "context_gap_minutes": float(c.get("context_gap_minutes", 60)),
|
|
40
|
+
"context_max_words": None if c.get("context_max_words") is None else int(c["context_max_words"])}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Reranker:
|
|
44
|
+
_instances = {}
|
|
45
|
+
_lock = threading.Lock()
|
|
46
|
+
|
|
47
|
+
def __init__(self, model_name, max_length=256, threads=None, device=None):
|
|
48
|
+
from recallic_engine.brain.models import onnx_runtime
|
|
49
|
+
if onnx_runtime.runtime() == "onnx": # embedded mode: onnxruntime instead of torch
|
|
50
|
+
self.model_name = model_name
|
|
51
|
+
self.model = onnx_runtime.OnnxCrossEncoder(model_name, max_length=max_length)
|
|
52
|
+
self._infer_lock = threading.Lock()
|
|
53
|
+
return
|
|
54
|
+
from sentence_transformers import CrossEncoder
|
|
55
|
+
if threads:
|
|
56
|
+
import torch
|
|
57
|
+
torch.set_num_threads(int(threads))
|
|
58
|
+
self.model_name = model_name
|
|
59
|
+
self.model = CrossEncoder(model_name, max_length=max_length, device=device) # None: GPU if available, else CPU
|
|
60
|
+
self._infer_lock = threading.Lock()
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_config(cls, force=False):
|
|
64
|
+
"""
|
|
65
|
+
The configured re-ranker, or None if unavailable (logged once). Without `force`, also None
|
|
66
|
+
when recall.rerank.enabled is off (it then runs only for recalls that ask for it: deep=True).
|
|
67
|
+
"""
|
|
68
|
+
cfg = config()
|
|
69
|
+
if not cfg["enabled"] and not force:
|
|
70
|
+
return None
|
|
71
|
+
key = (cfg["model"], cfg["max_length"], cfg["threads"], cfg["device"])
|
|
72
|
+
with cls._lock:
|
|
73
|
+
if key not in cls._instances:
|
|
74
|
+
try:
|
|
75
|
+
cls._instances[key] = cls(cfg["model"], cfg["max_length"], cfg["threads"], cfg["device"])
|
|
76
|
+
except Exception as e: # missing sentence-transformers/torch, no network for the first download, ...
|
|
77
|
+
print(f"[Reranker] disabled: cannot load {cfg['model']}: {e}")
|
|
78
|
+
cls._instances[key] = None
|
|
79
|
+
return cls._instances[key]
|
|
80
|
+
|
|
81
|
+
def scores(self, query, texts):
|
|
82
|
+
"""One relevance score per text (higher = answers the question better)."""
|
|
83
|
+
if not texts:
|
|
84
|
+
return []
|
|
85
|
+
with self._infer_lock:
|
|
86
|
+
out = self.model.predict([(query, t or "") for t in texts], batch_size=32, show_progress_bar=False)
|
|
87
|
+
return [float(x) for x in out]
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Prototype schema classifier (no LLM).
|
|
3
|
+
|
|
4
|
+
Each schema, including "general", is defined by a handful of seed sentences.
|
|
5
|
+
For a memory embedding v (computed by the store path anyway):
|
|
6
|
+
|
|
7
|
+
proto_k = cos(v, centroid_k) # mean of the class's seeds
|
|
8
|
+
nearest_k = max_j cos(v, seed_kj) # closest single seed
|
|
9
|
+
score_k = ALPHA * proto_k + (1 - ALPHA) * nearest_k + CUE_WEIGHT * min(cues_k, 3)
|
|
10
|
+
|
|
11
|
+
The label is argmax_k score_k; additional labels are returned when within TIE
|
|
12
|
+
of the top. Because "general" is an explicit class it competes on equal
|
|
13
|
+
terms, so no model-specific absolute threshold is needed.
|
|
14
|
+
|
|
15
|
+
Seed embeddings are cached on disk per embedding model.
|
|
16
|
+
"""
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import threading
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from recallic_engine.utils.paths import get_db_path, ensure_dir
|
|
24
|
+
|
|
25
|
+
SEEDS = {
|
|
26
|
+
"identity": [
|
|
27
|
+
"My name is Alex.",
|
|
28
|
+
"I am a software engineer.",
|
|
29
|
+
"I was born in Delhi.",
|
|
30
|
+
"I'm originally from Kenya.",
|
|
31
|
+
"I'm 27 years old.",
|
|
32
|
+
"I am a vegetarian and a night owl.",
|
|
33
|
+
"I have been a night-shift worker for years.",
|
|
34
|
+
"I'm a mother of two.",
|
|
35
|
+
],
|
|
36
|
+
"preference": [
|
|
37
|
+
"I like spicy food.",
|
|
38
|
+
"I prefer dark mode in every editor.",
|
|
39
|
+
"I hate waking up early.",
|
|
40
|
+
"My favorite color is blue.",
|
|
41
|
+
"I'd rather take the train than fly.",
|
|
42
|
+
"I don't enjoy crowded places.",
|
|
43
|
+
"Pineapple does not belong on pizza for me.",
|
|
44
|
+
"I love listening to podcasts while cooking.",
|
|
45
|
+
],
|
|
46
|
+
"calendar": [
|
|
47
|
+
"The meeting is on Monday at 3pm.",
|
|
48
|
+
"My flight leaves on March 3.",
|
|
49
|
+
"Dentist appointment next Tuesday morning.",
|
|
50
|
+
"The workshop runs from 9 to 5 on Saturday.",
|
|
51
|
+
"Interview scheduled for the 12th at noon.",
|
|
52
|
+
"The review was moved to next week.",
|
|
53
|
+
"Concert tickets are for Friday night.",
|
|
54
|
+
"Holiday starts on 1 August.",
|
|
55
|
+
],
|
|
56
|
+
"learning": [
|
|
57
|
+
"I am learning Rust.",
|
|
58
|
+
"Explain how recursion works.",
|
|
59
|
+
"I studied linear algebra today.",
|
|
60
|
+
"Reading a paper about neural networks.",
|
|
61
|
+
"Taking an online course in economics.",
|
|
62
|
+
"Memorising new vocabulary every morning.",
|
|
63
|
+
"How does photosynthesis work?",
|
|
64
|
+
"I want to understand quantum computing better.",
|
|
65
|
+
],
|
|
66
|
+
"task": [
|
|
67
|
+
"I need to finish the quarterly report.",
|
|
68
|
+
"Remind me to call mom tonight.",
|
|
69
|
+
"Todo: fix the login bug.",
|
|
70
|
+
"I have to pick up the dry cleaning.",
|
|
71
|
+
"Don't forget to buy milk.",
|
|
72
|
+
"I should reply to the landlord's email.",
|
|
73
|
+
"Next, deploy the hotfix to production.",
|
|
74
|
+
"Must renew the car insurance.",
|
|
75
|
+
],
|
|
76
|
+
"security": [
|
|
77
|
+
"My password is hunter2.",
|
|
78
|
+
"The API key is stored in the vault.",
|
|
79
|
+
"Enable two-factor authentication on the account.",
|
|
80
|
+
"The secret access code is ALPHA-9.",
|
|
81
|
+
"Change the router admin password.",
|
|
82
|
+
"My debit card PIN is 4321.",
|
|
83
|
+
"Shred old bank statements before binning them.",
|
|
84
|
+
"Never share the SSH private key.",
|
|
85
|
+
],
|
|
86
|
+
"social": [
|
|
87
|
+
"My friend Sam is visiting this weekend.",
|
|
88
|
+
"Had dinner with my family.",
|
|
89
|
+
"My sister's baby shower is in May.",
|
|
90
|
+
"Met a colleague at the conference.",
|
|
91
|
+
"Going to a party at Jake's place.",
|
|
92
|
+
"Catching up with college friends at a reunion.",
|
|
93
|
+
"Played football with the neighbours.",
|
|
94
|
+
"Video called my grandmother today.",
|
|
95
|
+
],
|
|
96
|
+
"general": [
|
|
97
|
+
"The sky was clear last night.",
|
|
98
|
+
"Cats sleep a lot during the day.",
|
|
99
|
+
"The river flooded after the storm.",
|
|
100
|
+
"There was a long queue at the shop.",
|
|
101
|
+
"Vegetable prices went up again.",
|
|
102
|
+
"The football match went to extra time.",
|
|
103
|
+
"Some trees lose their leaves in winter.",
|
|
104
|
+
"The new phone has a bigger screen.",
|
|
105
|
+
],
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
CUES = {
|
|
109
|
+
"identity": r"\b(my name|i am|i'm|call me|born|i live|my age|years old|i grew up)\b",
|
|
110
|
+
"preference": r"\b(like|love|hate|prefer|favou?rite|enjoy|dislike|rather)\b",
|
|
111
|
+
"calendar": r"\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday|tomorrow|tonight|deadline|meeting|appointment|schedule[d]?|january|february|march|april|june|july|august|september|october|november|december|\d{1,2}(:\d{2})?\s?(am|pm))\b",
|
|
112
|
+
"learning": r"\b(learn|learning|study|studying|explain|understand|course|tutorial|practi[sc]ing|how does)\b",
|
|
113
|
+
"task": r"\b(todo|to-do|need to|have to|must|remind me|don't let me forget|finish|should|next step|renew)\b",
|
|
114
|
+
"security": r"\b(password|passcode|secret|api key|token|credential|2fa|two-factor|pin|access keys?)\b",
|
|
115
|
+
"social": r"\b(friend|family|mom|mum|dad|mother|father|sister|brother|cousin|wife|husband|partner|colleague|neighbou?rs?|wedding|party)\b",
|
|
116
|
+
"general": r"$^", # no lexical cues: general wins on embedding similarity alone
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
ALPHA = 0.5
|
|
120
|
+
CUE_WEIGHT = 0.04
|
|
121
|
+
TIE = 0.01
|
|
122
|
+
|
|
123
|
+
_CUE_RE = {k: re.compile(v, re.I) for k, v in CUES.items()}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class SchemaClassifier:
|
|
127
|
+
def __init__(self, embed_fn, model_name, cache_path=None):
|
|
128
|
+
"""
|
|
129
|
+
embed_fn: text -> normalised np.ndarray, or None if embedding failed.
|
|
130
|
+
model_name: used to invalidate cached seed embeddings when the model changes.
|
|
131
|
+
"""
|
|
132
|
+
self.embed_fn = embed_fn
|
|
133
|
+
self.model_name = model_name
|
|
134
|
+
self.cache_path = cache_path or get_db_path("backend/storage/schema_prototypes.json")
|
|
135
|
+
self.labels = list(SEEDS.keys())
|
|
136
|
+
# (seeds [n_seeds, dim], seed_labels [n_seeds], centroids [n_labels, dim]); replaced atomically
|
|
137
|
+
self._state = None
|
|
138
|
+
self._lock = threading.Lock()
|
|
139
|
+
|
|
140
|
+
# -- prototypes -------------------------------------------------------
|
|
141
|
+
def _seed_signature(self):
|
|
142
|
+
return {k: list(v) for k, v in SEEDS.items()}
|
|
143
|
+
|
|
144
|
+
def _load_cache(self):
|
|
145
|
+
try:
|
|
146
|
+
with open(self.cache_path) as f:
|
|
147
|
+
data = json.load(f)
|
|
148
|
+
if data.get("model") == self.model_name and data.get("seeds") == self._seed_signature():
|
|
149
|
+
return np.asarray(data["vectors"], dtype=np.float32), np.asarray(data["labels"])
|
|
150
|
+
except (OSError, ValueError, KeyError):
|
|
151
|
+
pass
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
def _build(self):
|
|
155
|
+
vecs, labels = [], []
|
|
156
|
+
for i, label in enumerate(self.labels):
|
|
157
|
+
for s in SEEDS[label]:
|
|
158
|
+
v = self.embed_fn(s)
|
|
159
|
+
if v is None:
|
|
160
|
+
return None
|
|
161
|
+
vecs.append(v)
|
|
162
|
+
labels.append(i)
|
|
163
|
+
vecs = np.vstack(vecs).astype(np.float32)
|
|
164
|
+
labels = np.asarray(labels)
|
|
165
|
+
try:
|
|
166
|
+
ensure_dir(self.cache_path)
|
|
167
|
+
with open(self.cache_path, "w") as f:
|
|
168
|
+
json.dump({"model": self.model_name, "seeds": self._seed_signature(),
|
|
169
|
+
"vectors": vecs.tolist(), "labels": labels.tolist()}, f)
|
|
170
|
+
except OSError:
|
|
171
|
+
pass
|
|
172
|
+
return vecs, labels
|
|
173
|
+
|
|
174
|
+
def _prepare(self, dim):
|
|
175
|
+
"""
|
|
176
|
+
Returns (seeds, seed_labels, centroids) for this dimension, or None.
|
|
177
|
+
Built under a lock and published as one immutable tuple, so concurrent
|
|
178
|
+
requests never see seeds without centroids.
|
|
179
|
+
"""
|
|
180
|
+
state = self._state
|
|
181
|
+
if state is not None and state[0].shape[1] == dim:
|
|
182
|
+
return state
|
|
183
|
+
with self._lock:
|
|
184
|
+
state = self._state
|
|
185
|
+
if state is not None and state[0].shape[1] == dim:
|
|
186
|
+
return state
|
|
187
|
+
loaded = self._load_cache()
|
|
188
|
+
if loaded is None or loaded[0].shape[1] != dim:
|
|
189
|
+
loaded = self._build()
|
|
190
|
+
if loaded is None:
|
|
191
|
+
return None
|
|
192
|
+
seeds, labels = loaded
|
|
193
|
+
cents = np.vstack([seeds[labels == i].mean(axis=0) for i in range(len(self.labels))])
|
|
194
|
+
self._state = (seeds, labels, cents / np.linalg.norm(cents, axis=1, keepdims=True))
|
|
195
|
+
return self._state
|
|
196
|
+
|
|
197
|
+
# -- classification ---------------------------------------------------
|
|
198
|
+
def cue_hits(self, text):
|
|
199
|
+
return np.array([len(_CUE_RE[k].findall(text)) for k in self.labels], dtype=np.float32)
|
|
200
|
+
|
|
201
|
+
def scores(self, text, vec):
|
|
202
|
+
"""Per-label scores, or None when no embedding is available."""
|
|
203
|
+
state = self._prepare(len(vec)) if vec is not None else None
|
|
204
|
+
if state is None:
|
|
205
|
+
return None
|
|
206
|
+
v = np.asarray(vec, dtype=np.float32)
|
|
207
|
+
seeds, seed_labels, centroids = state
|
|
208
|
+
proto = centroids @ v
|
|
209
|
+
seed_sims = seeds @ v
|
|
210
|
+
nearest = np.array([seed_sims[seed_labels == i].max() for i in range(len(self.labels))])
|
|
211
|
+
return ALPHA * proto + (1 - ALPHA) * nearest + CUE_WEIGHT * np.minimum(self.cue_hits(text), 3)
|
|
212
|
+
|
|
213
|
+
def classify(self, text, vec):
|
|
214
|
+
s = self.scores(text, vec)
|
|
215
|
+
if s is None:
|
|
216
|
+
# No embeddings available: fall back to cue counts alone.
|
|
217
|
+
cues = self.cue_hits(text)
|
|
218
|
+
if cues.max() == 0:
|
|
219
|
+
return ["general"]
|
|
220
|
+
return [self.labels[i] for i in range(len(self.labels)) if cues[i] == cues.max()]
|
|
221
|
+
top = float(s.max())
|
|
222
|
+
return [self.labels[i] for i in np.argsort(-s) if s[i] >= top - TIE]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Extractive summarisation without an LLM.
|
|
3
|
+
|
|
4
|
+
Maximal Marginal Relevance over embeddings: repeatedly pick the text that is
|
|
5
|
+
most central (cosine to the centroid of all texts) while being least redundant
|
|
6
|
+
with what was already picked:
|
|
7
|
+
|
|
8
|
+
pick argmax_i LAMBDA * cos(v_i, c) - (1 - LAMBDA) * max_{j in S} cos(v_i, v_j)
|
|
9
|
+
|
|
10
|
+
Selected texts are returned in their original order. When embeddings are
|
|
11
|
+
unavailable, centrality falls back to TF-IDF term overlap.
|
|
12
|
+
"""
|
|
13
|
+
import math
|
|
14
|
+
from collections import Counter
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from recallic_engine.brain.memory_ranking.importance_ranker import content_terms
|
|
19
|
+
|
|
20
|
+
LAMBDA = 0.7
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _tfidf_vectors(texts):
|
|
24
|
+
docs = [Counter(content_terms(t)) for t in texts]
|
|
25
|
+
df = Counter(term for d in docs for term in d)
|
|
26
|
+
n = len(texts)
|
|
27
|
+
vocab = {t: i for i, t in enumerate(df)}
|
|
28
|
+
m = np.zeros((n, len(vocab) or 1), dtype=np.float32)
|
|
29
|
+
for row, d in enumerate(docs):
|
|
30
|
+
for term, tf in d.items():
|
|
31
|
+
m[row, vocab[term]] = tf * math.log(1 + n / df[term])
|
|
32
|
+
norms = np.linalg.norm(m, axis=1, keepdims=True)
|
|
33
|
+
norms[norms == 0] = 1.0
|
|
34
|
+
return m / norms
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def select(texts, embed_fn=None, k=None):
|
|
38
|
+
"""Indices of the k most representative, non-redundant texts (original order)."""
|
|
39
|
+
texts = [t for t in texts if t and t.strip()]
|
|
40
|
+
if not texts:
|
|
41
|
+
return []
|
|
42
|
+
k = k or max(1, math.ceil(math.sqrt(len(texts))))
|
|
43
|
+
vecs = None
|
|
44
|
+
if embed_fn is not None:
|
|
45
|
+
embedded = [embed_fn(t) for t in texts]
|
|
46
|
+
if all(v is not None for v in embedded):
|
|
47
|
+
vecs = np.vstack(embedded).astype(np.float32)
|
|
48
|
+
if vecs is None:
|
|
49
|
+
vecs = _tfidf_vectors(texts)
|
|
50
|
+
|
|
51
|
+
centroid = vecs.mean(axis=0)
|
|
52
|
+
centroid /= (np.linalg.norm(centroid) or 1.0)
|
|
53
|
+
centrality = vecs @ centroid
|
|
54
|
+
sims = vecs @ vecs.T
|
|
55
|
+
|
|
56
|
+
chosen = []
|
|
57
|
+
while len(chosen) < min(k, len(texts)):
|
|
58
|
+
best, best_score = None, -np.inf
|
|
59
|
+
for i in range(len(texts)):
|
|
60
|
+
if i in chosen:
|
|
61
|
+
continue
|
|
62
|
+
redundancy = max((sims[i, j] for j in chosen), default=0.0)
|
|
63
|
+
score = LAMBDA * centrality[i] - (1 - LAMBDA) * redundancy
|
|
64
|
+
if score > best_score:
|
|
65
|
+
best, best_score = i, score
|
|
66
|
+
chosen.append(best)
|
|
67
|
+
return sorted(chosen)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def extractive_summary(texts, embed_fn=None, k=None, sep=" "):
|
|
71
|
+
texts = [t for t in texts if t and t.strip()]
|
|
72
|
+
return sep.join(texts[i] for i in select(texts, embed_fn, k))
|