-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.py
More file actions
1761 lines (1511 loc) · 57.1 KB
/
database.py
File metadata and controls
1761 lines (1511 loc) · 57.1 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import asyncio
import aiosqlite
import json
import sqlite3
import logging
import os
import re
from dataclasses import dataclass
from typing import Any, Mapping, Optional
import numpy as np
from app.rag_embeddings import (
EmbeddingMetadata,
embed_text_with_metadata,
get_runtime_embedding_metadata,
pack_embedding,
unpack_embedding,
)
from app.runtime_config import get_runtime_bool, get_runtime_int, get_runtime_value
DB_FILE = get_runtime_value("DB_FILE")
logger = logging.getLogger(__name__)
def _db_file_path() -> str:
# Prefer runtime env override while preserving compatibility with test monkeypatching.
return get_runtime_value("DB_FILE") or DB_FILE
def _ensure_db_parent_dir(db_file: str) -> None:
parent_dir = os.path.dirname(db_file)
if parent_dir:
os.makedirs(parent_dir, exist_ok=True)
def _get_env_int(name: str, default: int) -> int:
value = get_runtime_int(name, default)
if value == default:
raw = get_runtime_value(name)
if raw and raw != str(default):
logger.warning("Invalid %s=%r, using default=%d", name, raw, default)
return value
def _rag_top_k() -> int:
return _get_env_int("RAG_TOP_K", 12)
def _rag_enabled() -> bool:
return get_runtime_bool("RAG_ENABLED", True)
def _message_review_back() -> int:
return _get_env_int("MESSAGE_REVIEW_BACK", 80)
def _rag_keyword_scan_back() -> int:
return _get_env_int("RAG_KEYWORD_SCAN_BACK", 500)
def _recent_context_max_chars() -> int:
return _get_env_int("RECENT_CONTEXT_MAX_CHARS", 12000)
def _rag_context_max_chars() -> int:
return _get_env_int("RAG_CONTEXT_MAX_CHARS", 6000)
@dataclass(frozen=True)
class MessageRow:
id: int
chat_id: int
username: str
content: str
timestamp: str
reply_to_username: Optional[str] = None
@dataclass(frozen=True)
class UserMemoryRow:
telegram_user_key: str
latest_display_name: str
memory_text: str
last_refreshed_date: Optional[str] = None
@dataclass(frozen=True)
class UserMemoryFactRow:
id: int
telegram_user_key: str
fact_type: str
fact_text: str
confidence: float
evidence_message_ids: list[int]
first_observed_at: Optional[str] = None
last_confirmed_at: Optional[str] = None
@dataclass(frozen=True)
class UserMemoryOverviewRow:
telegram_user_key: str
latest_display_name: str
memory_text: str
last_refreshed_date: Optional[str]
fact_count: int
latest_message_at: Optional[str]
@dataclass(frozen=True)
class UserMemorySearchRow:
telegram_user_key: str
latest_display_name: str
source: str
text: str
@dataclass(frozen=True)
class UserMemoryCandidateRow:
id: int
telegram_user_key: str
fact_type: str
fact_text: str
confidence: float
evidence_message_ids: list[int]
source_message_id: Optional[int]
priority: str
status: str
created_at: Optional[str]
updated_at: Optional[str]
def _format_message(row: MessageRow, *, max_chars: int = 800) -> str:
content = (row.content or "").replace("\r\n", "\n").strip()
if len(content) > max_chars:
content = content[: max_chars - 1] + "…"
if row.reply_to_username:
content = f"[reply to {row.reply_to_username}] {content}"
return f"[{row.timestamp}] {row.username}: {content}"
def _trim_context_lines(lines: list[str], *, max_chars: int, keep: str = "last") -> list[str]:
if max_chars <= 0 or not lines:
return lines
selected: list[str] = []
total = 0
source = reversed(lines) if keep == "last" else iter(lines)
for line in source:
text = str(line)
cost = len(text) + 1
if selected and total + cost > max_chars:
break
if cost > max_chars:
text = text[: max_chars - 1].rstrip() + "…"
cost = len(text) + 1
selected.append(text)
total += cost
if keep == "last":
selected.reverse()
return selected
async def _enable_foreign_keys(db: aiosqlite.Connection) -> None:
try:
await db.execute("PRAGMA foreign_keys = ON")
except Exception:
# Best effort; if it fails, DB still works but cascade deletes won't.
pass
def _get_message_columns(db: sqlite3.Connection) -> set[str]:
cursor = db.execute("PRAGMA table_info(messages)")
return {str(row[1]) for row in cursor.fetchall()}
def _migrate_messages_table(db: sqlite3.Connection) -> None:
columns = _get_message_columns(db)
if "telegram_message_id" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN telegram_message_id INTEGER")
if "reply_to_telegram_message_id" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN reply_to_telegram_message_id INTEGER")
if "reply_to_db_message_id" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN reply_to_db_message_id INTEGER")
if "reply_to_username" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN reply_to_username TEXT")
if "telegram_user_key" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN telegram_user_key TEXT")
db.execute("CREATE INDEX IF NOT EXISTS idx_messages_chat_tg ON messages (chat_id, telegram_message_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_messages_reply_db ON messages (reply_to_db_message_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_messages_user_date ON messages (telegram_user_key, timestamp)")
# Best-effort backfill for old rows that embedded reply target in content.
db.execute(
'''
UPDATE messages
SET reply_to_username = TRIM(SUBSTR(content, 11, INSTR(SUBSTR(content, 11), ']') - 1))
WHERE reply_to_username IS NULL
AND content LIKE '[reply_to:%'
AND INSTR(SUBSTR(content, 11), ']') > 0
'''
)
def _get_message_embedding_columns(db: sqlite3.Connection) -> set[str]:
cursor = db.execute("PRAGMA table_info(message_embeddings)")
return {str(row[1]) for row in cursor.fetchall()}
def _migrate_message_embeddings_table(db: sqlite3.Connection) -> None:
columns = _get_message_embedding_columns(db)
if "backend" not in columns:
db.execute("ALTER TABLE message_embeddings ADD COLUMN backend TEXT")
if "signature" not in columns:
db.execute("ALTER TABLE message_embeddings ADD COLUMN signature TEXT")
db.execute("CREATE INDEX IF NOT EXISTS idx_embed_chat_signature ON message_embeddings (chat_id, signature)")
def _init_stickers_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS sticker_descriptions (
file_unique_id TEXT PRIMARY KEY,
file_id TEXT,
emoji TEXT,
set_name TEXT,
description TEXT NOT NULL,
description_source TEXT NOT NULL DEFAULT 'fallback',
is_animated INTEGER NOT NULL DEFAULT 0,
is_video INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
'''
)
db.execute("CREATE INDEX IF NOT EXISTS idx_sticker_set_name ON sticker_descriptions (set_name)")
def _init_user_memories_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS user_memories (
telegram_user_key TEXT PRIMARY KEY,
latest_display_name TEXT NOT NULL,
memory_text TEXT NOT NULL DEFAULT '',
last_refreshed_date TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
'''
)
def _init_user_memory_facts_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS user_memory_facts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
telegram_user_key TEXT NOT NULL,
fact_type TEXT NOT NULL,
fact_text TEXT NOT NULL,
confidence REAL NOT NULL DEFAULT 0.5,
evidence_message_ids TEXT NOT NULL DEFAULT '[]',
first_observed_at TEXT,
last_confirmed_at TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(telegram_user_key, fact_type, fact_text)
)
'''
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_user_memory_facts_user ON user_memory_facts "
"(telegram_user_key, is_active, fact_type, confidence)"
)
def _init_user_memory_candidates_table(db: sqlite3.Connection) -> None:
db.execute(
'''
CREATE TABLE IF NOT EXISTS user_memory_candidates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
telegram_user_key TEXT NOT NULL,
fact_type TEXT NOT NULL,
fact_text TEXT NOT NULL,
confidence REAL NOT NULL DEFAULT 0.5,
evidence_message_ids TEXT NOT NULL DEFAULT '[]',
source_message_id INTEGER,
priority TEXT NOT NULL DEFAULT 'slow',
status TEXT NOT NULL DEFAULT 'pending',
review_note TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
reviewed_at DATETIME
)
'''
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_user_memory_candidates_user_status ON user_memory_candidates "
"(telegram_user_key, status, priority, id)"
)
db.execute(
"CREATE INDEX IF NOT EXISTS idx_user_memory_candidates_status ON user_memory_candidates "
"(status, priority, id)"
)
async def _embed_message_content(username: str, content: str) -> tuple[np.ndarray, EmbeddingMetadata]:
return await embed_text_with_metadata(f"{username}: {content}")
def init_db():
"""Initializes the database and creates the messages table if it doesn't exist."""
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
with sqlite3.connect(db_file) as db:
db.execute("PRAGMA foreign_keys = ON")
db.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
username TEXT NOT NULL,
content TEXT NOT NULL,
telegram_message_id INTEGER,
reply_to_telegram_message_id INTEGER,
reply_to_db_message_id INTEGER,
reply_to_username TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
_migrate_messages_table(db)
db.execute('CREATE INDEX IF NOT EXISTS idx_chat_timestamp ON messages (chat_id, timestamp)')
db.execute('''
CREATE TABLE IF NOT EXISTS message_embeddings (
message_id INTEGER PRIMARY KEY,
chat_id INTEGER NOT NULL,
embedding BLOB NOT NULL,
dim INTEGER NOT NULL,
model TEXT,
backend TEXT,
signature TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(message_id) REFERENCES messages(id) ON DELETE CASCADE
)
''')
_migrate_message_embeddings_table(db)
db.execute('CREATE INDEX IF NOT EXISTS idx_embed_chat ON message_embeddings (chat_id)')
db.execute('CREATE INDEX IF NOT EXISTS idx_embed_chat_msg ON message_embeddings (chat_id, message_id)')
_init_stickers_table(db)
_init_user_memories_table(db)
_init_user_memory_facts_table(db)
_init_user_memory_candidates_table(db)
db.commit()
logger.info("Database initialized: %s", db_file)
async def add_message(
chat_id: int,
username: str,
content: str,
*,
telegram_user_key: Optional[str] = None,
telegram_message_id: Optional[int] = None,
reply_to_telegram_message_id: Optional[int] = None,
reply_to_username: Optional[str] = None,
) -> Optional[int]:
"""Adds a message to the history with optional reply-chain metadata."""
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
await _enable_foreign_keys(db)
# Add the new message
cursor = await db.execute(
"""
INSERT INTO messages (
chat_id,
username,
content,
telegram_user_key,
telegram_message_id,
reply_to_telegram_message_id,
reply_to_username
) VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(chat_id, username, content, telegram_user_key, telegram_message_id, reply_to_telegram_message_id, reply_to_username)
)
lastrowid = cursor.lastrowid
if lastrowid is None:
await db.commit()
return None
message_id = int(lastrowid)
# Resolve parent DB row for reply chain when Telegram parent id is known.
if reply_to_telegram_message_id is not None:
parent_cursor = await db.execute(
'''
SELECT id
FROM messages
WHERE chat_id = ? AND telegram_message_id = ?
ORDER BY id DESC
LIMIT 1
''',
(chat_id, reply_to_telegram_message_id),
)
parent_row = await parent_cursor.fetchone()
if parent_row:
await db.execute(
"UPDATE messages SET reply_to_db_message_id = ? WHERE id = ?",
(int(parent_row[0]), message_id),
)
await db.commit()
# Store local embedding best-effort after committing the message row. This
# keeps slow model work from holding a SQLite write transaction open.
try:
vec, metadata = await _embed_message_content(username, content)
blob, dim = pack_embedding(vec)
async with aiosqlite.connect(db_file) as db:
await _enable_foreign_keys(db)
await db.execute(
"INSERT OR REPLACE INTO message_embeddings (message_id, chat_id, embedding, dim, model, backend, signature) VALUES (?, ?, ?, ?, ?, ?, ?)",
(message_id, chat_id, blob, dim, metadata.model, metadata.backend, metadata.signature),
)
await db.commit()
except Exception as e:
logger.warning("Embedding failed for message %s: %s", message_id, e)
return message_id
async def get_recent_messages(chat_id: int, *, limit: Optional[int] = None) -> list[MessageRow]:
effective_limit = _message_review_back() if limit is None else limit
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
await _enable_foreign_keys(db)
cursor = await db.execute(
'''
SELECT id, chat_id, username, content, timestamp, reply_to_username FROM messages
WHERE chat_id = ?
ORDER BY id DESC
LIMIT ?
''',
(chat_id, effective_limit),
)
rows = list(await cursor.fetchall())
# reverse to chronological
rows.reverse()
return [MessageRow(*row) for row in rows]
def _cosine_top_k(query_vec: np.ndarray, matrix: np.ndarray, *, top_k: int) -> np.ndarray:
q = np.asarray(query_vec, dtype=np.float32)
qn = np.linalg.norm(q) + 1e-8
mn = np.linalg.norm(matrix, axis=1) + 1e-8
sims = (matrix @ q) / (mn * qn)
if top_k <= 0:
top_k = 1
top_k = min(top_k, sims.shape[0])
# argpartition for speed, then sort selected
idx = np.argpartition(-sims, top_k - 1)[:top_k]
idx = idx[np.argsort(-sims[idx])]
return idx
async def vector_search_messages(
chat_id: int,
query: str,
*,
top_k: Optional[int] = None,
) -> list[MessageRow]:
if not query.strip():
return []
query_vec, query_metadata = await embed_text_with_metadata(query)
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
await _enable_foreign_keys(db)
cursor = await db.execute(
'''
SELECT m.id, m.chat_id, m.username, m.content, m.timestamp, m.reply_to_username, e.embedding, e.dim, e.signature
FROM message_embeddings e
JOIN messages m ON m.id = e.message_id
WHERE e.chat_id = ?
''',
(chat_id,),
)
rows = await cursor.fetchall()
if not rows:
return []
query_dim = int(query_metadata.dim)
message_rows: list[MessageRow] = []
vectors: list[np.ndarray] = []
for row in rows:
msg = MessageRow(id=row[0], chat_id=row[1], username=row[2], content=row[3], timestamp=row[4], reply_to_username=row[5])
blob = row[6]
dim = int(row[7])
signature = row[8]
if signature:
if signature != query_metadata.signature:
continue
elif dim != query_dim:
continue
vec = unpack_embedding(blob, dim)
message_rows.append(msg)
vectors.append(vec)
if not vectors:
return []
try:
matrix = np.vstack(vectors).astype(np.float32, copy=False)
except Exception:
# Fallback if shapes inconsistent
return []
effective_top_k = _rag_top_k() if top_k is None else top_k
idx = _cosine_top_k(query_vec, matrix, top_k=effective_top_k)
selected = [message_rows[int(i)] for i in idx]
selected.sort(key=lambda r: r.id)
return selected
RAG_TERM_STOPWORDS = {
"the", "and", "for", "with", "that", "this", "from", "have", "has", "you", "your",
"are", "was", "were", "been", "being", "about", "just", "what", "when", "where", "why",
}
def _query_terms(query: str, *, max_terms: int = 12) -> list[str]:
terms: list[str] = []
seen: set[str] = set()
for token in re.findall(r"[A-Za-z0-9_]{2,}|[\u4e00-\u9fff]{2,}", (query or "").lower()):
if token in RAG_TERM_STOPWORDS or token in seen:
continue
seen.add(token)
terms.append(token)
if len(terms) >= max_terms:
break
return terms
def _keyword_score(row: MessageRow, terms: list[str], raw_query: str) -> int:
content = (row.content or "").lower()
username = (row.username or "").lower()
reply_to = (row.reply_to_username or "").lower()
haystack = f"{username} {reply_to} {content}"
score = 0
normalized_query = (raw_query or "").strip().lower()
if normalized_query and len(normalized_query) >= 4 and normalized_query in content:
score += 6
for term in terms:
if term in content:
score += 3
elif term in username or term in reply_to:
score += 1
elif term in haystack:
score += 1
return score
async def keyword_search_messages(
chat_id: int,
query: str,
*,
top_k: Optional[int] = None,
scan_limit: Optional[int] = None,
) -> list[MessageRow]:
terms = _query_terms(query)
if not terms and not (query or "").strip():
return []
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
effective_scan_limit = _rag_keyword_scan_back() if scan_limit is None else scan_limit
async with aiosqlite.connect(db_file) as db:
await _enable_foreign_keys(db)
cursor = await db.execute(
'''
SELECT id, chat_id, username, content, timestamp, reply_to_username
FROM messages
WHERE chat_id = ?
ORDER BY id DESC
LIMIT ?
''',
(chat_id, effective_scan_limit),
)
rows = [MessageRow(*row) for row in await cursor.fetchall()]
scored = [(_keyword_score(row, terms, query), row) for row in rows]
scored = [(score, row) for score, row in scored if score > 0]
scored.sort(key=lambda item: (-item[0], -item[1].id))
effective_top_k = _rag_top_k() if top_k is None else top_k
selected = [row for _, row in scored[:effective_top_k]]
selected.sort(key=lambda row: row.id)
return selected
def _merge_retrieved_messages(*groups: list[MessageRow], top_k: int) -> list[MessageRow]:
seen: set[int] = set()
merged: list[MessageRow] = []
for group in groups:
for row in group:
if row.id in seen:
continue
seen.add(row.id)
merged.append(row)
if len(merged) >= top_k:
return merged
return merged
async def get_rag_context(
chat_id: int,
query: str,
*,
recent_n: Optional[int] = None,
retrieved_k: Optional[int] = None,
) -> list[str]:
"""Return context lines where the last line is the newest message.
We place retrieved history first, then recent chat, so the model's
"last message is most recent" rule stays true.
"""
recent_lines, retrieved_lines = await get_prompt_context_parts(
chat_id,
query,
recent_n=recent_n,
retrieved_k=retrieved_k,
)
lines: list[str] = []
if retrieved_lines:
lines.append("### RETRIEVED RELEVANT HISTORY")
lines.extend(retrieved_lines)
lines.append("### RECENT CHAT")
lines.extend(recent_lines)
return lines
async def get_prompt_context_parts(
chat_id: int,
query: str,
*,
recent_n: Optional[int] = None,
retrieved_k: Optional[int] = None,
) -> tuple[list[str], list[str]]:
"""Return context split into recent history and retrieved RAG lines.
Returns:
(recent_lines, retrieved_lines)
"""
effective_recent_n = _message_review_back() if recent_n is None else recent_n
effective_retrieved_k = _rag_top_k() if retrieved_k is None else retrieved_k
recent = await get_recent_messages(chat_id, limit=effective_recent_n)
retrieved: list[MessageRow] = []
if _rag_enabled():
try:
search_k = max(effective_retrieved_k * 2, effective_retrieved_k)
vector_retrieved = await vector_search_messages(chat_id, query, top_k=search_k)
keyword_retrieved = await keyword_search_messages(chat_id, query, top_k=search_k)
retrieved = _merge_retrieved_messages(vector_retrieved, keyword_retrieved, top_k=search_k)
except Exception as e:
logger.exception("Vector search failed: %s", e)
retrieved = []
recent_ids = {m.id for m in recent}
retrieved = [m for m in retrieved if m.id not in recent_ids]
retrieved = retrieved[:effective_retrieved_k]
retrieved.sort(key=lambda m: m.id)
recent_lines = [_format_message(m) for m in recent]
retrieved_lines = [_format_message(m) for m in retrieved]
recent_lines = _trim_context_lines(recent_lines, max_chars=_recent_context_max_chars(), keep="last")
retrieved_lines = _trim_context_lines(retrieved_lines, max_chars=_rag_context_max_chars(), keep="first")
return recent_lines, retrieved_lines
async def get_messages(chat_id: int) -> list[str]:
"""Retrieves the last messages for a given chat, formatted as strings."""
# Back-compat: return recent chat only.
recent = await get_recent_messages(chat_id, limit=_message_review_back())
logger.info(recent[-1] if recent else "No messages found for this chat.")
return [_format_message(m) for m in recent]
async def get_user_memory(telegram_user_key: str) -> Optional[UserMemoryRow]:
if not telegram_user_key:
return None
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
cursor = await db.execute(
'''
SELECT telegram_user_key, latest_display_name, memory_text, last_refreshed_date
FROM user_memories
WHERE telegram_user_key = ?
''',
(telegram_user_key,),
)
row = await cursor.fetchone()
if not row:
return None
return UserMemoryRow(*row)
async def upsert_user_memory(
telegram_user_key: str,
*,
latest_display_name: str,
memory_text: str,
last_refreshed_date: Optional[str],
) -> None:
if not telegram_user_key:
return
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
await db.execute(
'''
INSERT INTO user_memories (
telegram_user_key,
latest_display_name,
memory_text,
last_refreshed_date,
updated_at
) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(telegram_user_key) DO UPDATE SET
latest_display_name = excluded.latest_display_name,
memory_text = excluded.memory_text,
last_refreshed_date = excluded.last_refreshed_date,
updated_at = CURRENT_TIMESTAMP
''',
(telegram_user_key, latest_display_name, memory_text, last_refreshed_date),
)
await db.commit()
def _decode_evidence_ids(raw_value: Any) -> list[int]:
if not raw_value:
return []
if isinstance(raw_value, list):
source = raw_value
else:
try:
source = json.loads(str(raw_value))
except json.JSONDecodeError:
return []
evidence_ids: list[int] = []
for item in source if isinstance(source, list) else []:
try:
value = int(item)
except (TypeError, ValueError):
continue
if value not in evidence_ids:
evidence_ids.append(value)
return evidence_ids
def _encode_evidence_ids(values: list[int]) -> str:
unique: list[int] = []
for value in values:
if value not in unique:
unique.append(value)
return json.dumps(unique, ensure_ascii=False)
def _clamp_confidence(value: Any) -> float:
try:
confidence = float(value)
except (TypeError, ValueError):
confidence = 0.5
return min(1.0, max(0.0, confidence))
async def get_user_memory_facts(
telegram_user_key: str,
*,
limit: int = 8,
min_confidence: float = 0.0,
) -> list[UserMemoryFactRow]:
if not telegram_user_key:
return []
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
cursor = await db.execute(
'''
SELECT id, telegram_user_key, fact_type, fact_text, confidence,
evidence_message_ids, first_observed_at, last_confirmed_at
FROM user_memory_facts
WHERE telegram_user_key = ? AND is_active = 1 AND confidence >= ?
ORDER BY confidence DESC, updated_at DESC, id DESC
LIMIT ?
''',
(telegram_user_key, min_confidence, limit),
)
rows = await cursor.fetchall()
return [
UserMemoryFactRow(
id=int(row[0]),
telegram_user_key=str(row[1]),
fact_type=str(row[2]),
fact_text=str(row[3]),
confidence=float(row[4]),
evidence_message_ids=_decode_evidence_ids(row[5]),
first_observed_at=row[6],
last_confirmed_at=row[7],
)
for row in rows
]
async def get_user_memory_fact_by_id(fact_id: int) -> Optional[UserMemoryFactRow]:
if fact_id <= 0:
return None
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
cursor = await db.execute(
'''
SELECT id, telegram_user_key, fact_type, fact_text, confidence,
evidence_message_ids, first_observed_at, last_confirmed_at
FROM user_memory_facts
WHERE id = ? AND is_active = 1
''',
(fact_id,),
)
row = await cursor.fetchone()
if not row:
return None
return UserMemoryFactRow(
id=int(row[0]),
telegram_user_key=str(row[1]),
fact_type=str(row[2]),
fact_text=str(row[3]),
confidence=float(row[4]),
evidence_message_ids=_decode_evidence_ids(row[5]),
first_observed_at=row[6],
last_confirmed_at=row[7],
)
async def update_user_memory_fact(
fact_id: int,
*,
fact_text: Optional[str] = None,
fact_type: Optional[str] = None,
confidence: Optional[float] = None,
) -> bool:
if fact_id <= 0:
return False
assignments: list[str] = []
params: list[Any] = []
if fact_text is not None:
cleaned_text = fact_text.strip()
if not cleaned_text:
return False
assignments.append("fact_text = ?")
params.append(cleaned_text)
if fact_type is not None:
cleaned_type = fact_type.strip().lower() or "note"
assignments.append("fact_type = ?")
params.append(cleaned_type)
if confidence is not None:
assignments.append("confidence = ?")
params.append(_clamp_confidence(confidence))
if not assignments:
return False
assignments.append("updated_at = CURRENT_TIMESTAMP")
params.append(fact_id)
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
cursor = await db.execute(
f"UPDATE user_memory_facts SET {', '.join(assignments)} WHERE id = ? AND is_active = 1",
tuple(params),
)
await db.commit()
return cursor.rowcount > 0
async def archive_user_memory_fact(fact_id: int) -> bool:
if fact_id <= 0:
return False
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
cursor = await db.execute(
'''
UPDATE user_memory_facts
SET is_active = 0, updated_at = CURRENT_TIMESTAMP
WHERE id = ? AND is_active = 1
''',
(fact_id,),
)
await db.commit()
return cursor.rowcount > 0
async def archive_user_memory_facts(fact_ids: list[int]) -> int:
valid_ids = [int(fact_id) for fact_id in fact_ids if int(fact_id) > 0]
if not valid_ids:
return 0
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
placeholders = ",".join("?" for _ in valid_ids)
async with aiosqlite.connect(db_file) as db:
cursor = await db.execute(
f'''
UPDATE user_memory_facts
SET is_active = 0, updated_at = CURRENT_TIMESTAMP
WHERE id IN ({placeholders}) AND is_active = 1
''',
tuple(valid_ids),
)
await db.commit()
return cursor.rowcount
async def upsert_user_memory_candidate(
telegram_user_key: str,
*,
fact_type: str,
fact_text: str,
confidence: float = 0.5,
evidence_message_ids: Optional[list[int]] = None,
source_message_id: Optional[int] = None,
priority: str = "slow",
status: str = "pending",
) -> Optional[int]:
if not telegram_user_key or not fact_text.strip():
return None
cleaned_type = fact_type.strip().lower() or "note"
cleaned_text = fact_text.strip()
cleaned_priority = priority.strip().lower() if priority else "slow"
if cleaned_priority not in {"fast", "slow"}:
cleaned_priority = "slow"
cleaned_status = status.strip().lower() if status else "pending"
db_file = _db_file_path()
_ensure_db_parent_dir(db_file)
async with aiosqlite.connect(db_file) as db:
cursor = await db.execute(
'''
SELECT id, confidence, evidence_message_ids, priority
FROM user_memory_candidates
WHERE telegram_user_key = ?
AND fact_type = ?
AND fact_text = ?
AND status = 'pending'
ORDER BY id DESC
LIMIT 1
''',
(telegram_user_key, cleaned_type, cleaned_text),
)
existing = await cursor.fetchone()