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.
Files changed (89) hide show
  1. recallic_engine/__init__.py +10 -0
  2. recallic_engine/api/__init__.py +0 -0
  3. recallic_engine/api/deps.py +36 -0
  4. recallic_engine/brain/__init__.py +0 -0
  5. recallic_engine/brain/features/__init__.py +1 -0
  6. recallic_engine/brain/features/aggregation_check.py +796 -0
  7. recallic_engine/brain/features/answer_check.default.json +23 -0
  8. recallic_engine/brain/features/answer_check.py +199 -0
  9. recallic_engine/brain/features/answer_check_learning.py +164 -0
  10. recallic_engine/brain/features/answer_verify.py +78 -0
  11. recallic_engine/brain/features/as_of.py +122 -0
  12. recallic_engine/brain/features/calibration.py +119 -0
  13. recallic_engine/brain/features/dates.py +124 -0
  14. recallic_engine/brain/features/facts.py +472 -0
  15. recallic_engine/brain/features/implicit.py +208 -0
  16. recallic_engine/brain/features/learned_facts.py +121 -0
  17. recallic_engine/brain/features/modes.py +70 -0
  18. recallic_engine/brain/features/query.py +297 -0
  19. recallic_engine/brain/features/reranker.py +87 -0
  20. recallic_engine/brain/features/schemas.py +222 -0
  21. recallic_engine/brain/features/summarize.py +72 -0
  22. recallic_engine/brain/features/trust.default.json +37 -0
  23. recallic_engine/brain/features/trust.py +165 -0
  24. recallic_engine/brain/memory/__init__.py +0 -0
  25. recallic_engine/brain/memory/archive/__init__.py +0 -0
  26. recallic_engine/brain/memory/archive/archive_store.py +64 -0
  27. recallic_engine/brain/memory/audit.py +84 -0
  28. recallic_engine/brain/memory/episodic/__init__.py +0 -0
  29. recallic_engine/brain/memory/episodic/episodic_memory.py +500 -0
  30. recallic_engine/brain/memory/freshness.py +104 -0
  31. recallic_engine/brain/memory/index_key.py +55 -0
  32. recallic_engine/brain/memory/index_sync.py +109 -0
  33. recallic_engine/brain/memory/long_term/__init__.py +0 -0
  34. recallic_engine/brain/memory/long_term/long_term_memory.py +80 -0
  35. recallic_engine/brain/memory/manager.py +326 -0
  36. recallic_engine/brain/memory/proactive.py +81 -0
  37. recallic_engine/brain/memory/reasoning_engine.py +35 -0
  38. recallic_engine/brain/memory/recall_engine.py +1211 -0
  39. recallic_engine/brain/memory/reflective/__init__.py +0 -0
  40. recallic_engine/brain/memory/reflective/reflective_memory.py +58 -0
  41. recallic_engine/brain/memory/semantic/__init__.py +0 -0
  42. recallic_engine/brain/memory/semantic/semantic_memory.py +167 -0
  43. recallic_engine/brain/memory/short_term/__init__.py +0 -0
  44. recallic_engine/brain/memory/short_term/sensory.py +33 -0
  45. recallic_engine/brain/memory/truth_engine.py +110 -0
  46. recallic_engine/brain/memory/update_classifier.py +76 -0
  47. recallic_engine/brain/memory/updates.py +572 -0
  48. recallic_engine/brain/memory/working/__init__.py +0 -0
  49. recallic_engine/brain/memory/working/working_memory.py +74 -0
  50. recallic_engine/brain/memory_ranking/__init__.py +0 -0
  51. recallic_engine/brain/memory_ranking/fit_importance.py +91 -0
  52. recallic_engine/brain/memory_ranking/fit_ranker.py +188 -0
  53. recallic_engine/brain/memory_ranking/importance_ranker.py +166 -0
  54. recallic_engine/brain/memory_ranking/importance_weights.default.json +16 -0
  55. recallic_engine/brain/memory_ranking/importance_weights.prior.json +14 -0
  56. recallic_engine/brain/memory_ranking/logistic.py +72 -0
  57. recallic_engine/brain/memory_ranking/ranker.py +414 -0
  58. recallic_engine/brain/memory_ranking/ranker_model.default.json +54 -0
  59. recallic_engine/brain/memory_ranking/ranker_model.hash.json +54 -0
  60. recallic_engine/brain/memory_ranking/ranker_model.prior.json +22 -0
  61. recallic_engine/brain/memory_ranking/reinforcement_learning.py +57 -0
  62. recallic_engine/brain/memory_ranking/self_improve.py +187 -0
  63. recallic_engine/brain/models/__init__.py +0 -0
  64. recallic_engine/brain/models/model_router.py +189 -0
  65. recallic_engine/brain/models/onnx_runtime.py +149 -0
  66. recallic_engine/brain/prediction/__init__.py +0 -0
  67. recallic_engine/brain/prediction/predictive_recall.py +14 -0
  68. recallic_engine/brain/utils/__init__.py +0 -0
  69. recallic_engine/brain/utils/decay_logic.py +27 -0
  70. recallic_engine/brain/world_model/__init__.py +0 -0
  71. recallic_engine/brain/world_model/planning_engine.py +47 -0
  72. recallic_engine/brain/world_model/prediction_engine.py +87 -0
  73. recallic_engine/brain/world_model/state_inference.py +100 -0
  74. recallic_engine/brain/world_model/timeline_engine.py +67 -0
  75. recallic_engine/config.yaml +518 -0
  76. recallic_engine/embedded.py +65 -0
  77. recallic_engine/settings.py +115 -0
  78. recallic_engine/tools/__init__.py +0 -0
  79. recallic_engine/tools/portable.py +137 -0
  80. recallic_engine/utils/__init__.py +0 -0
  81. recallic_engine/utils/internal_client.py +82 -0
  82. recallic_engine/utils/local_engine.py +136 -0
  83. recallic_engine/utils/paths.py +29 -0
  84. recallic_engine-0.1.0.dist-info/METADATA +48 -0
  85. recallic_engine-0.1.0.dist-info/RECORD +89 -0
  86. recallic_engine-0.1.0.dist-info/WHEEL +5 -0
  87. recallic_engine-0.1.0.dist-info/licenses/LICENSE +105 -0
  88. recallic_engine-0.1.0.dist-info/licenses/NOTICE +19 -0
  89. recallic_engine-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,119 @@
1
+ """
2
+ A guarantee on wrong refusals for the answer check (no LLM, no new model).
3
+
4
+ Why: a decline threshold chosen on one dataset need not transfer to another. On
5
+ LongMemEval the LoCoMo-fitted threshold wrongly declined 20% of answerable questions
6
+ against a 5% target, while the answer-check *signal* still separated answerable
7
+ from unanswerable questions well (AUC 0.80). The fix is to calibrate the threshold
8
+ on the deployment's own questions, and to say how sure we are.
9
+
10
+ Calibration data: the answer-check margins `s_1..s_n` of *answerable* questions
11
+ whose served memories did contain the answer, taken from user feedback (see
12
+ backend/tools/calibrate.py) or a labelled sample.
13
+
14
+ The guarantee (one-sided binomial test, fixed-sequence "learn then test"):
15
+ for a threshold t, the number R of calibration margins below t is Binomial(n, p_t),
16
+ where p_t is the true wrong-refusal rate. If p_t > alpha then
17
+
18
+ P(R <= r) <= BinomCDF(r; n, alpha)
19
+
20
+ so declaring "p_t <= alpha" whenever BinomCDF(R; n, alpha) <= delta is wrong with
21
+ probability at most delta. Candidate thresholds are tested from least to most
22
+ declining (p_t grows with t) and the last one that passes is used; stopping at the
23
+ first failure keeps the overall error probability at delta (Angelopoulos et al.,
24
+ "Learn then Test", 2021). Result: with probability >= 1 - delta over the
25
+ calibration sample, the wrong-refusal rate is <= alpha, *provided future questions
26
+ resemble the calibration questions* (exchangeability). That proviso is why the
27
+ calibration belongs to each deployment.
28
+
29
+ With too few calibration questions no threshold can be certified: (1 - alpha)^n
30
+ must be <= delta, i.e. n >= 59 for alpha = delta = 0.05. Then the result is
31
+ "never decline on this signal" (rate 0, trivially within alpha), stated as such.
32
+ """
33
+ import json
34
+ import math
35
+
36
+ from recallic_engine import settings
37
+
38
+ CALIBRATION_FILE = "answer_check_calibration.json"
39
+
40
+
41
+ def _log_binom_pmf(k, n, p):
42
+ if p <= 0.0:
43
+ return 0.0 if k == 0 else -math.inf
44
+ if p >= 1.0:
45
+ return 0.0 if k == n else -math.inf
46
+ return (math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
47
+ + k * math.log(p) + (n - k) * math.log1p(-p))
48
+
49
+
50
+ def binom_cdf(r, n, p):
51
+ """P(Binomial(n, p) <= r), summed in log space (stable for n in the tens of thousands)."""
52
+ if r < 0:
53
+ return 0.0
54
+ if r >= n:
55
+ return 1.0
56
+ logs = [_log_binom_pmf(k, n, p) for k in range(r + 1)]
57
+ top = max(logs)
58
+ if top == -math.inf:
59
+ return 0.0
60
+ return min(1.0, math.exp(top) * sum(math.exp(x - top) for x in logs))
61
+
62
+
63
+ def min_calibration_size(alpha, delta):
64
+ """Smallest n for which any declining threshold can be certified."""
65
+ return math.ceil(math.log(delta) / math.log1p(-alpha))
66
+
67
+
68
+ def certify_threshold(margins, alpha=0.05, delta=0.05):
69
+ """
70
+ The most declining threshold whose wrong-refusal rate is certified <= alpha with
71
+ confidence 1 - delta, from margins of answerable questions. Returns a certificate dict.
72
+ `threshold` is None when nothing can be certified ("never decline on this signal").
73
+ """
74
+ if not 0 < alpha < 1 or not 0 < delta < 1:
75
+ raise ValueError("alpha and delta must be in (0, 1)")
76
+ s = sorted(float(m) for m in margins if m is not None and math.isfinite(float(m)))
77
+ n = len(s)
78
+ # Candidate thresholds are the distinct margins, least declining first. A threshold t
79
+ # declines a question when its margin < t, so t = u_j refuses every margin below u_j.
80
+ threshold, refused = None, 0
81
+ i = 0
82
+ for u in sorted(set(s)):
83
+ while i < n and s[i] < u:
84
+ i += 1
85
+ if binom_cdf(i, n, alpha) > delta: # cannot certify this one: stop (fixed sequence)
86
+ break
87
+ threshold, refused = u, i
88
+ certified = threshold is not None
89
+ return {
90
+ "method": "binomial learn-then-test",
91
+ "alpha": alpha,
92
+ "delta": delta,
93
+ "n": n,
94
+ "threshold": threshold,
95
+ "calibration_refusal_rate": (refused / n) if n else None,
96
+ "certified": certified,
97
+ "min_n": min_calibration_size(alpha, delta),
98
+ "statement": (f"wrong refusals <= {alpha:.0%} with probability >= {1 - delta:.0%}, "
99
+ "for questions like the calibration questions")
100
+ if certified else
101
+ f"not enough calibration data ({n} < {min_calibration_size(alpha, delta)}): the answer check will not decline",
102
+ }
103
+
104
+
105
+ def save(certificate, model_name):
106
+ path = settings.storage_path(CALIBRATION_FILE)
107
+ with open(path, "w") as f:
108
+ json.dump({**certificate, "model": model_name}, f, indent=2)
109
+ return path
110
+
111
+
112
+ def load(model_name):
113
+ """This deployment's certificate for `model_name`, or None."""
114
+ try:
115
+ with open(settings.storage_path(CALIBRATION_FILE)) as f:
116
+ cert = json.load(f)
117
+ except (OSError, ValueError):
118
+ return None
119
+ return cert if cert.get("model") == model_name else None
@@ -0,0 +1,124 @@
1
+ """
2
+ Relative dates resolved at store time (config memory.resolve_dates).
3
+
4
+ "I went to the support group yesterday", stored on 8 May 2023, also means "7 May 2023". A memory keeps
5
+ its own text; the resolved dates are kept in metadata["dates"] and shown inline wherever the memory is read
6
+ (the answer check, and `content_resolved` in recall results):
7
+
8
+ "...the support group yesterday [7 May 2023]..."
9
+ "...joined a service-focused online group last week [the week before 1 January 2023]..."
10
+
11
+ Rules only, deterministic, no LLM. The reference date is the memory's timestamp (UTC). Only expressions with
12
+ a definite meaning are resolved; vague ones ("lately", "recently", "the other day", "a few weeks ago") are left
13
+ alone rather than guessed. Week-like expressions keep their relative form ("the week before <date>"), because a
14
+ week has no single date; weekday expressions also give the exact date ("last Friday" -> "9 September 2022, the
15
+ Friday before 14 September 2022").
16
+ """
17
+ import re
18
+ from datetime import datetime, timedelta, timezone
19
+
20
+ from recallic_engine import settings
21
+
22
+ WEEKDAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
23
+ NUMBERS = {"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7,
24
+ "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "fifteen": 15, "twenty": 20}
25
+ _NUM = r"(\d{1,2}|a|an|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|fifteen|twenty)"
26
+ _WD = r"(monday|tuesday|wednesday|thursday|friday|saturday|sunday)"
27
+
28
+
29
+ def _day(d):
30
+ return f"{d.day} {d.strftime('%B')} {d.year}"
31
+
32
+
33
+ def _month(d):
34
+ return f"{d.strftime('%B')} {d.year}"
35
+
36
+
37
+ def _shift_month(d, n):
38
+ m = d.month - 1 + n
39
+ return d.replace(year=d.year + m // 12, month=m % 12 + 1, day=1)
40
+
41
+
42
+ def _n(word):
43
+ return int(word) if word.isdigit() else NUMBERS[word.lower()]
44
+
45
+
46
+ def _last_weekday(ref, wd): # "last friday": the most recent one strictly before the reference day
47
+ back = (ref.weekday() - wd) % 7 or 7
48
+ return ref - timedelta(days=back)
49
+
50
+
51
+ def _next_weekday(ref, wd): # "next friday" / "this friday": the next one after the reference day
52
+ ahead = (wd - ref.weekday()) % 7 or 7
53
+ return ref + timedelta(days=ahead)
54
+
55
+
56
+ # (pattern, resolver(ref_date, match) -> text). Longer phrases first: the first match at a position wins.
57
+ _RULES = [
58
+ (r"the day before yesterday", lambda r, m: _day(r - timedelta(days=2))),
59
+ (r"the day after tomorrow", lambda r, m: _day(r + timedelta(days=2))),
60
+ (r"yesterday(?: (?:morning|afternoon|evening|night))?|last night", lambda r, m: _day(r - timedelta(days=1))),
61
+ (r"tomorrow(?: (?:morning|afternoon|evening|night))?", lambda r, m: _day(r + timedelta(days=1))),
62
+ (r"today|tonight|this (?:morning|afternoon|evening)", lambda r, m: _day(r)),
63
+ (rf"last {_WD}", lambda r, m: f"{_day(_last_weekday(r, WEEKDAYS.index(m.group(1).lower())))}, "
64
+ f"the {m.group(1).capitalize()} before {_day(r)}"),
65
+ (rf"(?:next|this|this coming) {_WD}", lambda r, m: f"{_day(_next_weekday(r, WEEKDAYS.index(m.group(1).lower())))}, "
66
+ f"the {m.group(1).capitalize()} after {_day(r)}"),
67
+ (r"(?:last|this past|over the) weekend", lambda r, m: f"the weekend before {_day(r)}"),
68
+ (r"this weekend", lambda r, m: f"the weekend of {_day(r)}"),
69
+ (r"next weekend", lambda r, m: f"the weekend after {_day(r)}"),
70
+ (r"last week|this past week|the past week", lambda r, m: f"the week before {_day(r)}"),
71
+ (r"this week|earlier this week", lambda r, m: f"the week of {_day(r)}"),
72
+ (r"next week", lambda r, m: f"the week after {_day(r)}"),
73
+ (r"last month", lambda r, m: _month(_shift_month(r, -1))),
74
+ (r"this month|earlier this month", lambda r, m: _month(r)),
75
+ (r"next month", lambda r, m: _month(_shift_month(r, 1))),
76
+ (r"last year", lambda r, m: str(r.year - 1)),
77
+ (r"this year|earlier this year", lambda r, m: str(r.year)),
78
+ (r"next year", lambda r, m: str(r.year + 1)),
79
+ (rf"{_NUM} days? ago", lambda r, m: _day(r - timedelta(days=_n(m.group(1))))),
80
+ (rf"{_NUM} weeks? ago", lambda r, m: f"the week of {_day(r - timedelta(weeks=_n(m.group(1))))}"),
81
+ (rf"{_NUM} months? ago", lambda r, m: _month(_shift_month(r, -_n(m.group(1))))),
82
+ (rf"{_NUM} years? ago", lambda r, m: str(r.year - _n(m.group(1)))),
83
+ (rf"in {_NUM} days?", lambda r, m: _day(r + timedelta(days=_n(m.group(1))))),
84
+ (rf"in {_NUM} weeks?", lambda r, m: f"the week of {_day(r + timedelta(weeks=_n(m.group(1))))}"),
85
+ ]
86
+ _COMPILED = [(re.compile(rf"\b(?:{p})\b", re.I), fn) for p, fn in _RULES]
87
+
88
+
89
+ def enabled():
90
+ return bool((settings.get("memory.resolve_dates", {}) or {}).get("enabled", True))
91
+
92
+
93
+ def resolve(text, timestamp):
94
+ """[{"text", "start", "end", "value"}] for each definite relative date in `text`, said at `timestamp`."""
95
+ if not text or timestamp is None:
96
+ return []
97
+ ref = datetime.fromtimestamp(float(timestamp), tz=timezone.utc).date()
98
+ found = []
99
+ taken = []
100
+ for rx, fn in _COMPILED:
101
+ for m in rx.finditer(text):
102
+ if any(m.start() < e and s < m.end() for s, e in taken):
103
+ continue # inside a longer phrase already resolved
104
+ try:
105
+ value = fn(ref, m)
106
+ except (KeyError, ValueError, OverflowError):
107
+ continue
108
+ taken.append((m.start(), m.end()))
109
+ found.append({"text": m.group(0), "start": m.start(), "end": m.end(), "value": value})
110
+ return sorted(found, key=lambda d: d["start"])
111
+
112
+
113
+ def annotate(text, dates):
114
+ """The text with each resolved date added in brackets after its expression."""
115
+ if not dates:
116
+ return text
117
+ out, last = [], 0
118
+ for d in sorted(dates, key=lambda d: d["start"]):
119
+ s, e = int(d["start"]), int(d["end"])
120
+ if s < last or text[s:e].lower() != str(d["text"]).lower():
121
+ continue # spans no longer match the text: skip rather than misplace
122
+ out.append(text[last:e]); out.append(f" [{d['value']}]"); last = e
123
+ out.append(text[last:])
124
+ return "".join(out)