nomem-ai 0.3.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.
nomem/__init__.py ADDED
@@ -0,0 +1,47 @@
1
+ """NoMem — Not Only Memory.
2
+
3
+ A transparent, token-budgeted memory layer for agentic and RAG applications.
4
+ Framework-neutral core; local-first (SQLite); no LLM anywhere, by design.
5
+ """
6
+
7
+ from .compactor import Compactor, ExtractiveCompactor, NullCompactor
8
+ from .conflicts import ConflictConfig
9
+ from .core import NoMem
10
+ from .embed import Embedder, HashingEmbedder, Model2VecEmbedder, SentenceTransformerEmbedder
11
+ from .retrieval import Hit, RetrievalConfig
12
+ from .models import ContextResult, LogEntry, Message
13
+ from .service import MemoryService
14
+ from .store import SQLiteStore
15
+ from .tokens import (
16
+ AnthropicCounter,
17
+ ApproxCounter,
18
+ OpenAICounter,
19
+ TokenCounter,
20
+ default_counter,
21
+ )
22
+
23
+ __version__ = "0.3.0"
24
+
25
+ __all__ = [
26
+ "NoMem",
27
+ "Message",
28
+ "LogEntry",
29
+ "ContextResult",
30
+ "SQLiteStore",
31
+ "MemoryService",
32
+ "TokenCounter",
33
+ "ApproxCounter",
34
+ "OpenAICounter",
35
+ "AnthropicCounter",
36
+ "default_counter",
37
+ "Compactor",
38
+ "ExtractiveCompactor",
39
+ "NullCompactor",
40
+ "RetrievalConfig",
41
+ "ConflictConfig",
42
+ "Hit",
43
+ "Embedder",
44
+ "HashingEmbedder",
45
+ "Model2VecEmbedder",
46
+ "SentenceTransformerEmbedder",
47
+ ]
nomem/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
nomem/annotate.py ADDED
@@ -0,0 +1,410 @@
1
+ """Deterministic, LLM-free annotation of a message.
2
+
3
+ Every function here is a rule, a pattern or a hash: no model, no network, no
4
+ randomness. The output is stored *beside* the verbatim message (never instead
5
+ of it), so a wrong annotation can cost a little ranking quality but can never
6
+ corrupt or lose what the user actually said.
7
+
8
+ - :func:`entities` capitalised spans, acronyms, numbers with units
9
+ - :func:`keyphrases` RAKE-style content-word phrases
10
+ - :func:`parse_times` "yesterday", "two weeks ago", "7 May 2023", "last Friday"
11
+ - :func:`extract_slots` first-person facts as (subject, attribute, value)
12
+ - :func:`importance` a feature score in [0, 1]
13
+ - :func:`simhash` / :func:`norm_hash` near-duplicate and exact-duplicate keys
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import re
20
+ from dataclasses import dataclass
21
+ from datetime import datetime, timedelta
22
+ from typing import Optional
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Tokenising
26
+
27
+ STOPWORDS = frozenset("""
28
+ a about above after again against all am an and any are aren't as at be because
29
+ been before being below between both but by can can't cannot could couldn't did
30
+ didn't do does doesn't doing don't down during each few for from further get got
31
+ had hadn't has hasn't have haven't having he he'd he'll he's her here here's hers
32
+ herself him himself his how how's i i'd i'll i'm i've if in into is isn't it it's
33
+ its itself just let's me more most mustn't my myself no nor not now of off on once
34
+ only or other ought our ours ourselves out over own really same shan't she she'd
35
+ she'll she's should shouldn't so some such than that that's the their theirs them
36
+ themselves then there there's these they they'd they'll they're they've this those
37
+ through to too under until up us very was wasn't we we'd we'll we're we've were
38
+ weren't what what's when when's where where's which while who who's whom why why's
39
+ will with won't would wouldn't yeah yes you you'd you'll you're you've your yours
40
+ yourself yourselves also oh ok okay hey hi hello thanks thank wow lol well like
41
+ going go went gonna sure great good nice cool awesome thing things lot lots much
42
+ many something anything everything one ones did do does done make made know think
43
+ """.split())
44
+
45
+ _WORD = re.compile(r"[A-Za-z0-9][A-Za-z0-9'\-]*")
46
+ _SENT_SPLIT = re.compile(r"(?<=[.!?])\s+")
47
+
48
+
49
+ def words(text: str) -> list[str]:
50
+ return _WORD.findall(text)
51
+
52
+
53
+ def content_terms(text: str) -> list[str]:
54
+ """Lower-cased non-stopword terms."""
55
+ return [w.lower() for w in words(text) if w.lower() not in STOPWORDS and len(w) > 1]
56
+
57
+
58
+ def sentences(text: str) -> list[str]:
59
+ return [s for s in _SENT_SPLIT.split(text.strip()) if s]
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Entities
64
+
65
+ _COMMON_CAPS = frozenset("""
66
+ i i'm i've i'll i'd the a an and but so oh hey hi hello yes no yeah wow thanks
67
+ thank that this it what when where who why how my we you they he she just
68
+ really well ok okay sure great good nice cool awesome congrats congratulations
69
+ monday tuesday wednesday thursday friday saturday sunday
70
+ january february march april may june july august september october november december
71
+ """.split())
72
+ _CAP_SPAN = re.compile(r"\b([A-Z][a-zA-Z'\-]+(?:\s+(?:of|the|de|van|von|&)?\s*[A-Z][a-zA-Z'\-]+)*)")
73
+ _ACRONYM = re.compile(r"\b[A-Z]{2,}[A-Z0-9+]*\b")
74
+ _NUMBER = re.compile(r"(?:[$£€]\s?)?\b\d[\d,.]*\s?(?:%|k|m|bn|dollars|euros|pounds|years?|kg|km|miles)?\b")
75
+ _SPEAKER_PREFIX = re.compile(r"^\s*([A-Z][\w'\-]*(?: [A-Z][\w'\-]*)?):\s+")
76
+
77
+
78
+ def entities(text: str) -> list[str]:
79
+ """Named-thing candidates, lower-cased and de-duplicated, in order."""
80
+ out: list[str] = []
81
+ body = _SPEAKER_PREFIX.sub("", text)
82
+ for span in _CAP_SPAN.findall(body):
83
+ span = span.strip(" '")
84
+ first = span.split()[0].lower()
85
+ if first in _COMMON_CAPS and len(span.split()) == 1:
86
+ continue
87
+ if first in _COMMON_CAPS:
88
+ span = " ".join(span.split()[1:])
89
+ if span and span.lower() not in STOPWORDS:
90
+ out.append(span.lower())
91
+ out += [a.lower() for a in _ACRONYM.findall(body)]
92
+ seen: set[str] = set()
93
+ return [e for e in out if not (e in seen or seen.add(e))]
94
+
95
+
96
+ def numbers(text: str) -> list[str]:
97
+ return [n.strip() for n in _NUMBER.findall(text) if n.strip()]
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Keyphrases (RAKE-style: runs of content words between stopwords/punctuation)
102
+
103
+ def keyphrases(text: str, max_words: int = 3, limit: int = 8) -> list[str]:
104
+ phrases: list[str] = []
105
+ run: list[str] = []
106
+ for tok in re.findall(r"[A-Za-z0-9'\-]+|[^\sA-Za-z0-9]", _SPEAKER_PREFIX.sub("", text)):
107
+ low = tok.lower()
108
+ if not tok[0].isalnum() or low in STOPWORDS or len(low) < 2:
109
+ if run:
110
+ phrases.append(" ".join(run[:max_words]))
111
+ run = []
112
+ else:
113
+ run.append(low)
114
+ if run:
115
+ phrases.append(" ".join(run[:max_words]))
116
+ # longer phrases first (more specific), then keep order
117
+ seen: set[str] = set()
118
+ uniq = [p for p in phrases if not (p in seen or seen.add(p))]
119
+ uniq.sort(key=lambda p: -len(p.split()))
120
+ return uniq[:limit]
121
+
122
+
123
+ # ---------------------------------------------------------------------------
124
+ # Time expressions -> (start, end) epoch ranges, anchored to the message time
125
+
126
+ _MONTHS = {m: i for i, m in enumerate(
127
+ "january february march april may june july august september october november december".split(), 1)}
128
+ _MONTHS.update({m[:3]: i for m, i in list(_MONTHS.items())})
129
+ _MONTHS["sept"] = 9
130
+ _WEEKDAYS = {d: i for i, d in enumerate("monday tuesday wednesday thursday friday saturday sunday".split())}
131
+ _NUMWORDS = {"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6,
132
+ "seven": 7, "eight": 8, "nine": 9, "ten": 10, "few": 3, "couple of": 2, "couple": 2,
133
+ "several": 4}
134
+ _MONTH_RE = r"(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sept?(?:ember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)"
135
+ _UNIT_RE = r"(day|week|month|year|weekend)s?"
136
+
137
+
138
+ def _day(dt: datetime) -> tuple[float, float]:
139
+ start = dt.replace(hour=0, minute=0, second=0, microsecond=0)
140
+ return start.timestamp(), (start + timedelta(days=1)).timestamp() - 1
141
+
142
+
143
+ def _month(y: int, m: int) -> tuple[float, float]:
144
+ start = datetime(y, m, 1)
145
+ end = datetime(y + (m == 12), m % 12 + 1, 1)
146
+ return start.timestamp(), end.timestamp() - 1
147
+
148
+
149
+ def _span(unit: str, anchor: datetime) -> tuple[float, float]:
150
+ if unit == "day":
151
+ return _day(anchor)
152
+ if unit in ("week", "weekend"):
153
+ start = anchor - timedelta(days=anchor.weekday())
154
+ if unit == "weekend":
155
+ start += timedelta(days=5)
156
+ return _day(start)[0], _day(start + timedelta(days=1))[1]
157
+ return _day(start)[0], _day(start + timedelta(days=6))[1]
158
+ if unit == "month":
159
+ return _month(anchor.year, anchor.month)
160
+ return datetime(anchor.year, 1, 1).timestamp(), datetime(anchor.year + 1, 1, 1).timestamp() - 1
161
+
162
+
163
+ def _shift(anchor: datetime, unit: str, n: int) -> datetime:
164
+ if unit in ("day",):
165
+ return anchor + timedelta(days=n)
166
+ if unit in ("week", "weekend"):
167
+ return anchor + timedelta(weeks=n)
168
+ if unit == "month":
169
+ m = anchor.month - 1 + n
170
+ return anchor.replace(year=anchor.year + m // 12, month=m % 12 + 1, day=1)
171
+ return anchor.replace(year=anchor.year + n, month=1, day=1)
172
+
173
+
174
+ def parse_times(text: str, ref: float) -> list[tuple[float, float]]:
175
+ """Time ranges a message talks about, resolved against its timestamp ``ref``."""
176
+ t = text.lower()
177
+ now = datetime.fromtimestamp(ref)
178
+ out: list[tuple[float, float]] = []
179
+
180
+ for word, delta in (("yesterday", -1), ("last night", -1), ("today", 0), ("tonight", 0),
181
+ ("this morning", 0), ("tomorrow", 1)):
182
+ if re.search(rf"\b{word}\b", t):
183
+ out.append(_day(now + timedelta(days=delta)))
184
+
185
+ num = r"(\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten|few|couple of|couple|several)"
186
+ for n, unit in re.findall(rf"\b{num}\s+{_UNIT_RE}\s+ago\b", t):
187
+ k = int(n) if n.isdigit() else _NUMWORDS[n]
188
+ try:
189
+ out.append(_span(unit, _shift(now, unit, -k)))
190
+ except (ValueError, OverflowError, OSError):
191
+ continue # "4000 years ago": outside what datetime can represent
192
+
193
+ for which, unit in re.findall(rf"\b(last|this|next|past)\s+{_UNIT_RE}\b", t):
194
+ k = {"last": -1, "past": -1, "this": 0, "next": 1}[which]
195
+ out.append(_span(unit, _shift(now, unit, k)))
196
+
197
+ for which, day in re.findall(r"\b(last|this|next|on)\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b", t):
198
+ diff = _WEEKDAYS[day] - now.weekday()
199
+ if which in ("last", "on"):
200
+ diff = diff - 7 if diff >= 0 else diff
201
+ elif which == "next":
202
+ diff = diff + 7 if diff <= 0 else diff
203
+ out.append(_day(now + timedelta(days=diff)))
204
+
205
+ # "7 May 2023", "7th of May", "May 7, 2023", "May 7th"
206
+ for d, m, y in re.findall(rf"\b(\d{{1,2}})(?:st|nd|rd|th)?\s+(?:of\s+)?{_MONTH_RE}\b,?\s*(\d{{4}})?", t):
207
+ out.append(_safe_day(y or now.year, _MONTHS[m[:4] if m.startswith("sept") else m[:3]], d))
208
+ for m, d, y in re.findall(rf"\b{_MONTH_RE}\s+(\d{{1,2}})(?:st|nd|rd|th)?\b,?\s*(\d{{4}})?", t):
209
+ out.append(_safe_day(y or now.year, _MONTHS[m[:4] if m.startswith("sept") else m[:3]], d))
210
+ # "in May 2023", "in May", "May 2023"
211
+ for m, y in re.findall(rf"\b(?:in|during|since|until)\s+{_MONTH_RE}\b(?:\s+(\d{{4}}))?", t):
212
+ out.append(_month(int(y) if y else now.year, _MONTHS[m[:4] if m.startswith("sept") else m[:3]]))
213
+ for y in re.findall(r"\b(?:in|since|during)\s+((?:19|20)\d{2})\b", t):
214
+ out.append((datetime(int(y), 1, 1).timestamp(), datetime(int(y) + 1, 1, 1).timestamp() - 1))
215
+
216
+ seen: set = set()
217
+ return [r for r in out if r and not (r in seen or seen.add(r))]
218
+
219
+
220
+ def _safe_day(y, m: int, d) -> Optional[tuple[float, float]]:
221
+ try:
222
+ return _day(datetime(int(y), m, int(d)))
223
+ except ValueError:
224
+ return None
225
+
226
+
227
+ # ---------------------------------------------------------------------------
228
+ # Slot facts: first-person statements -> (subject, attribute, value)
229
+
230
+ @dataclass(frozen=True)
231
+ class Slot:
232
+ subject: str
233
+ attribute: str
234
+ value: str
235
+ multi: bool = False # several values may hold at once (likes, allergies)
236
+ negated: bool = False # "I no longer like X" closes a "likes: X" slot
237
+
238
+
239
+ _VALUE = r"([^.,;!?\n]{2,60}?)(?=\s+(?:and|but|because|since|so|which|who|now|anymore|these days|nowadays|at|for|with|last|this|next|yesterday|today|tomorrow|recently|ago|on|in \d{4})\b|[.,;!?\n]|$)"
240
+ _SINGLE_PATTERNS = [
241
+ (r"\bmy name is\s+" + _VALUE, "name"),
242
+ (r"\b(?:i'm|i am)\s+(\d{1,3})\s+years?\s+old\b", "age"),
243
+ (r"\bi\s+(?:now\s+)?(?:live|am living|'m living|reside)\s+in\s+" + _VALUE, "location"),
244
+ (r"\bi(?:'ve| have)?\s+(?:just\s+)?(?:moved|relocated)\s+to\s+" + _VALUE, "location"),
245
+ (r"\bi(?:'m| am)\s+(?:now\s+)?(?:based|living)\s+in\s+" + _VALUE, "location"),
246
+ (r"\bi\s+(?:now\s+)?work\s+(?:as)\s+(?:an?\s+)?" + _VALUE, "job"),
247
+ (r"\bi(?:'m| am)\s+(?:now\s+)?(?:working\s+)?as\s+(?:an?\s+)?" + _VALUE, "job"),
248
+ (r"\bmy job is\s+(?:an?\s+)?" + _VALUE, "job"),
249
+ (r"\bi\s+(?:now\s+)?work(?:\s+as\s+(?:an?\s+)?[a-z]+)?\s+(?:at|for)\s+" + _VALUE, "employer"),
250
+ (r"\bi(?:'m| am)\s+(?:a\s+)?(vegetarian|vegan|pescatarian|keto)\b", "diet"),
251
+ (r"\bmy\s+(?:new\s+)?(?:favou?rite\s+)?([a-z]+(?:\s[a-z]+)?)\s+is\s+(?:called\s+|named\s+)?" + _VALUE, None),
252
+ ]
253
+ _MULTI_PATTERNS = [
254
+ (r"\bi(?:'m| am)\s+(?:severely\s+|very\s+|really\s+|mildly\s+)?allergic\s+to\s+" + _VALUE, "allergy"),
255
+ (r"\bi\s+(?:really\s+|absolutely\s+)?(?:love|like|enjoy|adore|prefer)\s+" + _VALUE, "likes"),
256
+ (r"\bi\s+(?:really\s+)?(?:hate|dislike|can't stand|cannot stand)\s+" + _VALUE, "dislikes"),
257
+ ]
258
+ _NEG_LIKE = re.compile(r"\bi\s+(?:don't|do not|no longer|don't really|stopped)\s+(?:like|love|enjoy|liking|eating|drinking)\s+" + _VALUE)
259
+ _NEG_BEFORE = re.compile(r"\b(?:not|n't|never|no longer)\b[^.]{0,12}$")
260
+ _GENERIC_ATTR_BLOCK = frozenset("""
261
+ day week life time point goal question guess bad fault pleasure turn idea plan way
262
+ thing problem issue dream hope pick favorite favourite god heart mind work job name
263
+ """.split())
264
+
265
+
266
+ def _clean_value(v: str) -> str:
267
+ v = v.strip(" '\"")
268
+ v = re.sub(r"^(?:the|a|an|my)\s+", "", v, flags=re.I)
269
+ return v
270
+
271
+
272
+ def speaker_of(text: str) -> Optional[str]:
273
+ """``"Caroline: ..."`` -> ``"Caroline"`` (transcripts that prefix the speaker)."""
274
+ m = _SPEAKER_PREFIX.match(text)
275
+ if not m or m.group(1).lower() in _NOT_SPEAKERS:
276
+ return None
277
+ return m.group(1)
278
+
279
+
280
+ # Words that end in a colon at the start of a message without naming anyone.
281
+ _NOT_SPEAKERS = frozenset("""
282
+ correction update note reminder edit ps fyi btw news important update todo question
283
+ answer tip warning also actually ok okay so well
284
+ """.split())
285
+
286
+
287
+ def extract_slots(text: str, subject: str = "user") -> list[Slot]:
288
+ """First-person facts. Conservative by design: precision over recall."""
289
+ body = _SPEAKER_PREFIX.sub("", text)
290
+ out: list[Slot] = []
291
+ for sent in sentences(body):
292
+ low = sent.lower()
293
+ if low.rstrip().endswith("?"):
294
+ continue # questions are not statements of fact
295
+ for m in _NEG_LIKE.finditer(low):
296
+ out.append(Slot(subject, "likes", _clean_value(m.group(1)), multi=True, negated=True))
297
+ for pattern, attr in _SINGLE_PATTERNS:
298
+ for m in re.finditer(pattern, low):
299
+ if _NEG_BEFORE.search(low[: m.start() + 6]):
300
+ continue
301
+ if attr is None:
302
+ a, v = m.group(1).strip(), m.group(2)
303
+ if a in _GENERIC_ATTR_BLOCK or a in STOPWORDS:
304
+ continue
305
+ attr_name = a.replace(" ", "_")
306
+ else:
307
+ attr_name, v = attr, m.group(1)
308
+ v = _clean_value(_restore_case(sent, v))
309
+ if v and len(v.split()) <= 6:
310
+ out.append(Slot(subject, attr_name, v))
311
+ for pattern, attr in _MULTI_PATTERNS:
312
+ for m in re.finditer(pattern, low):
313
+ if _NEG_BEFORE.search(low[max(0, m.start() - 12): m.start() + 2]):
314
+ continue
315
+ v = _clean_value(_restore_case(sent, m.group(1)))
316
+ if v and len(v.split()) <= 6:
317
+ out.append(Slot(subject, attr, v, multi=True))
318
+ seen: set = set()
319
+ return [s for s in out if not ((s.attribute, s.value.lower(), s.negated) in seen
320
+ or seen.add((s.attribute, s.value.lower(), s.negated)))]
321
+
322
+
323
+ def _restore_case(original: str, lowered_value: str) -> str:
324
+ i = original.lower().find(lowered_value)
325
+ return original[i:i + len(lowered_value)] if i >= 0 else lowered_value
326
+
327
+
328
+ # ---------------------------------------------------------------------------
329
+ # Importance (replaces the "rate this memory 1-10" LLM call)
330
+
331
+ _CUES = re.compile(r"\b(remember|important|never|always|allergic|allergy|birthday|anniversary|"
332
+ r"deadline|password|address|diagnosed|married|divorced|pregnant|promoted|"
333
+ r"moved|started|quit|graduated|passed away|died|born|favou?rite|prefer)\b", re.I)
334
+ _FILLER = re.compile(r"^\W*(ok(ay)?|thanks?( you)?|thank you|nice|cool|great|sure|yes|no|yeah|lol|"
335
+ r"haha|wow|hi|hello|hey|bye|got it|sounds good)\W*$", re.I)
336
+ _FIRST_PERSON = re.compile(r"\b(i|i'm|i've|i'd|my|me|mine)\b", re.I)
337
+
338
+
339
+ def importance(text: str, slots: Optional[list[Slot]] = None, ents: Optional[list[str]] = None) -> float:
340
+ body = _SPEAKER_PREFIX.sub("", text).strip()
341
+ if not body or _FILLER.match(body):
342
+ return 0.0
343
+ score = 0.2
344
+ if _FIRST_PERSON.search(body):
345
+ score += 0.1
346
+ if slots:
347
+ score += 0.3
348
+ if _CUES.search(body):
349
+ score += 0.2
350
+ score += min(0.15, 0.05 * len(ents or []))
351
+ if numbers(body):
352
+ score += 0.05
353
+ if body.endswith("?"):
354
+ score -= 0.1
355
+ n = len(words(body))
356
+ if n < 4:
357
+ score -= 0.1
358
+ return round(max(0.0, min(1.0, score)), 3)
359
+
360
+
361
+ # ---------------------------------------------------------------------------
362
+ # Duplicate keys
363
+
364
+ def norm_hash(text: str) -> str:
365
+ norm = " ".join(w.lower() for w in words(_SPEAKER_PREFIX.sub("", text)))
366
+ return hashlib.blake2b(norm.encode(), digest_size=8).hexdigest()
367
+
368
+
369
+ def simhash(text: str, bits: int = 64) -> int:
370
+ """64-bit SimHash over word 2-shingles (signed, so it fits SQLite INTEGER)."""
371
+ toks = [w.lower() for w in words(_SPEAKER_PREFIX.sub("", text))]
372
+ shingles = [" ".join(toks[i:i + 2]) for i in range(max(1, len(toks) - 1))] or [""]
373
+ acc = [0] * bits
374
+ for sh in shingles:
375
+ h = int.from_bytes(hashlib.blake2b(sh.encode(), digest_size=8).digest(), "big")
376
+ for b in range(bits):
377
+ acc[b] += 1 if (h >> b) & 1 else -1
378
+ v = sum(1 << b for b in range(bits) if acc[b] > 0)
379
+ return v - (1 << 64) if v >= (1 << 63) else v
380
+
381
+
382
+ def hamming(a: int, b: int) -> int:
383
+ return bin((a ^ b) & ((1 << 64) - 1)).count("1")
384
+
385
+
386
+ # ---------------------------------------------------------------------------
387
+
388
+ @dataclass
389
+ class Annotation:
390
+ entities: list[str]
391
+ keyphrases: list[str]
392
+ times: list[tuple[float, float]]
393
+ slots: list[Slot]
394
+ importance: float
395
+ norm_hash: str
396
+ simhash: int
397
+
398
+
399
+ def annotate(text: str, ref_time: float, subject: str = "user") -> Annotation:
400
+ ents = entities(text)
401
+ sl = extract_slots(text, subject)
402
+ return Annotation(
403
+ entities=ents,
404
+ keyphrases=keyphrases(text),
405
+ times=parse_times(text, ref_time),
406
+ slots=sl,
407
+ importance=importance(text, sl, ents),
408
+ norm_hash=norm_hash(text),
409
+ simhash=simhash(text),
410
+ )
nomem/cli.py ADDED
@@ -0,0 +1,63 @@
1
+ """Command line: ``nomem serve`` (HTTP API) and ``nomem mcp`` (MCP server)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+
9
+
10
+ def _common(p: argparse.ArgumentParser) -> None:
11
+ p.add_argument("--db", default=os.environ.get("NOMEM_DB", "nomem.db"),
12
+ help="SQLite file (default: nomem.db, or $NOMEM_DB)")
13
+ p.add_argument("--max-tokens", type=int, default=3000, help="default context budget")
14
+ p.add_argument("--core", default="", help="persona/rules placed first in every context")
15
+ p.add_argument("--embedder", default=os.environ.get("NOMEM_EMBEDDER", "none"),
16
+ choices=["none", "model2vec", "hashing"],
17
+ help="optional vector ranker (model2vec needs nomem[embed])")
18
+
19
+
20
+ def main(argv=None) -> int:
21
+ from . import __version__
22
+
23
+ ap = argparse.ArgumentParser(prog="nomem", description="NoMem: LLM-free memory for agents.")
24
+ ap.add_argument("--version", action="version", version=f"nomem {__version__}")
25
+ sub = ap.add_subparsers(dest="cmd", required=True)
26
+
27
+ s = sub.add_parser("serve", help="run the JSON HTTP API")
28
+ _common(s)
29
+ s.add_argument("--host", default="127.0.0.1")
30
+ s.add_argument("--port", type=int, default=8420)
31
+ s.add_argument("--api-key", default=os.environ.get("NOMEM_API_KEY"),
32
+ help="require 'Authorization: Bearer <key>' (or set $NOMEM_API_KEY)")
33
+ s.add_argument("--verbose", action="store_true", help="log every request")
34
+
35
+ m = sub.add_parser("mcp", help="run the MCP server (stdio by default)")
36
+ _common(m)
37
+ m.add_argument("--user-id", default=os.environ.get("NOMEM_USER_ID", "default"))
38
+ m.add_argument("--session-id", default=os.environ.get("NOMEM_SESSION_ID", "default"))
39
+ m.add_argument("--transport", default="stdio", choices=["stdio", "sse", "streamable-http"])
40
+ m.add_argument("--host", default=None)
41
+ m.add_argument("--port", type=int, default=None)
42
+
43
+ args = ap.parse_args(argv)
44
+
45
+ from .service import MemoryService
46
+
47
+ service = MemoryService(args.db, max_tokens=args.max_tokens, core=args.core,
48
+ embedder=args.embedder)
49
+ if args.cmd == "serve":
50
+ from .http_api import serve
51
+
52
+ if args.host not in ("127.0.0.1", "localhost", "::1") and not args.api_key:
53
+ print("warning: listening beyond localhost with no --api-key", file=sys.stderr)
54
+ serve(service, args.host, args.port, args.api_key, args.verbose)
55
+ else:
56
+ from .mcp_server import run
57
+
58
+ run(service, args.user_id, args.session_id, args.transport, args.host, args.port)
59
+ return 0
60
+
61
+
62
+ if __name__ == "__main__":
63
+ raise SystemExit(main())
nomem/compactor.py ADDED
@@ -0,0 +1,123 @@
1
+ """Compaction: fold turns that fell out of the window into a short summary.
2
+
3
+ NoMem's compactors are *extractive*: every line of a summary is a sentence
4
+ the user or assistant actually wrote, quoted with its date. Nothing is
5
+ paraphrased, so nothing can be invented, and the transparency log can point
6
+ at the source of every line. There is no LLM compactor by design.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from abc import ABC, abstractmethod
13
+ from collections import Counter
14
+ from datetime import datetime
15
+ from typing import Optional
16
+
17
+ from . import annotate as A
18
+ from .models import Message
19
+
20
+
21
+ class Compactor(ABC):
22
+ @abstractmethod
23
+ def compact(
24
+ self,
25
+ messages: list[Message],
26
+ previous_summary: str = "",
27
+ *,
28
+ max_tokens: Optional[int] = None,
29
+ counter=None,
30
+ ) -> str:
31
+ """Fold ``messages`` (oldest first) into a summary of at most ``max_tokens``."""
32
+ ...
33
+
34
+
35
+ class NullCompactor(Compactor):
36
+ """No-op: overflow is dropped without a summary (a pure sliding window)."""
37
+
38
+ def compact(self, messages, previous_summary="", *, max_tokens=None, counter=None) -> str:
39
+ return previous_summary
40
+
41
+
42
+ class ExtractiveCompactor(Compactor):
43
+ """Pick the most informative sentences that fit the budget.
44
+
45
+ Each sentence is scored by its rule-based importance (facts, names,
46
+ numbers, cue words) and its centrality (how much of the dropped stretch's
47
+ vocabulary it shares). Selection is greedy with a Maximal Marginal
48
+ Relevance penalty so near-repeats don't crowd out other topics. Chosen
49
+ sentences are emitted in their original order.
50
+
51
+ Args:
52
+ importance_weight: Share of the score from importance vs centrality.
53
+ redundancy: MMR penalty for overlap with already chosen sentences.
54
+ min_importance: Sentences scoring below this (pure filler) are skipped.
55
+ """
56
+
57
+ def __init__(self, importance_weight: float = 0.6, redundancy: float = 0.5,
58
+ min_importance: float = 0.2):
59
+ self.importance_weight = importance_weight
60
+ self.redundancy = redundancy
61
+ self.min_importance = min_importance
62
+
63
+ def compact(self, messages, previous_summary="", *, max_tokens=None, counter=None) -> str:
64
+ cands = [] # (order, text_line, terms, importance)
65
+ for m in messages:
66
+ for j, sent in enumerate(A.sentences(m.content)):
67
+ imp = A.importance(sent, A.extract_slots(sent), A.entities(sent))
68
+ if imp < self.min_importance:
69
+ continue
70
+ terms = set(A.content_terms(sent))
71
+ if not terms:
72
+ continue
73
+ line = f"- [{_date(m.created_at)}] {m.role}: {sent.strip()}"
74
+ cands.append(((m.id or 0, j), line, terms, imp))
75
+ if not cands:
76
+ return previous_summary
77
+
78
+ df = Counter(t for c in cands for t in c[2])
79
+ n = len(cands)
80
+ def centrality(terms):
81
+ return sum(math.log(1 + df[t]) for t in terms) / (1 + math.log(1 + n) * len(terms))
82
+ cent = [centrality(c[2]) for c in cands]
83
+ top = max(cent) or 1.0
84
+ base = [self.importance_weight * c[3] + (1 - self.importance_weight) * (ce / top)
85
+ for c, ce in zip(cands, cent)]
86
+
87
+ head = "Earlier conversation (key sentences):"
88
+ fits = (lambda text: True) if max_tokens is None or counter is None else \
89
+ (lambda text: counter.count_message("system", text) <= max_tokens)
90
+ order = lambda idx: sorted(idx, key=lambda i: cands[i][0])
91
+ chosen: list[int] = []
92
+ maxov = [0.0] * n
93
+ remaining = set(range(n))
94
+ while remaining:
95
+ best = max(remaining, key=lambda i: (base[i] - self.redundancy * maxov[i], -cands[i][0][0]))
96
+ remaining.discard(best)
97
+ if base[best] - self.redundancy * maxov[best] <= 0:
98
+ break
99
+ trial = chosen + [best]
100
+ if not fits(_render(head, previous_summary, [cands[i] for i in order(trial)])):
101
+ continue
102
+ chosen = trial
103
+ for i in remaining:
104
+ maxov[i] = max(maxov[i], _jaccard(cands[i][2], cands[best][2]))
105
+ if not chosen:
106
+ return previous_summary
107
+ return _render(head, previous_summary, [cands[i] for i in order(chosen)])
108
+
109
+
110
+ def _render(head: str, previous: str, items) -> str:
111
+ lines = [head]
112
+ if previous:
113
+ lines.append(previous)
114
+ lines += [c[1] for c in items]
115
+ return "\n".join(lines)
116
+
117
+
118
+ def _jaccard(a: set, b: set) -> float:
119
+ return len(a & b) / len(a | b) if a and b else 0.0
120
+
121
+
122
+ def _date(ts: float) -> str:
123
+ return datetime.fromtimestamp(ts).strftime("%d %b %Y").lstrip("0")