forked from Yinglianchun/Ombre-Brain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_memory.py
More file actions
1893 lines (1698 loc) · 72.2 KB
/
Copy pathimport_memory.py
File metadata and controls
1893 lines (1698 loc) · 72.2 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
# ============================================================
# Module: Memory Import Engine (import_memory.py)
# 模块:历史记忆导入引擎
#
# Imports conversation history from various platforms into OB.
# 将各平台对话历史导入 OB 记忆系统。
#
# Supports: Claude JSON, ChatGPT export, DeepSeek, Markdown, plain text
# 支持格式:Claude JSON、ChatGPT 导出、DeepSeek、Markdown、纯文本
#
# Features:
# - Chunked processing with resume support
# - Progress persistence (import_state.json)
# - Raw preservation mode for special contexts
# - Post-import frequency pattern detection
# ============================================================
import os
import json
import hashlib
import logging
import asyncio
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import jieba
from rapidfuzz import fuzz
from utils import LOCAL_TZ, bucket_text_for_embedding, count_tokens_approx, now_iso, strip_affect_anchor
logger = logging.getLogger("ombre_brain.import")
# ============================================================
# Format Parsers — normalize any format to conversation turns
# 格式解析器 — 将任意格式标准化为对话轮次
# ============================================================
_MARKDOWN_ROLE_RE = re.compile(
r"^\s*(?:>\s*)?(?:[-*+]\s*)?(?:#{1,6}\s*)?(?:\*\*)?([A-Za-z0-9_\-\u4e00-\u9fff]+)(?:\*\*)?\s*[::]\s*(.*)$"
)
_MARKDOWN_USER_LABELS = {
"human",
"user",
"me",
"你",
"我",
"用户",
"人类",
}
_MARKDOWN_ASSISTANT_LABELS = {
"assistant",
"claude",
"ai",
"gpt",
"chatgpt",
"bot",
"deepseek",
"gemini",
"qwen",
"助手",
"模型",
"ai助手",
}
_CHATGPT_IMPORT_ROLES = {"user", "assistant"}
def _clean_chatgpt_role(role: object) -> str:
normalized = str(role or "user").strip().lower()
return normalized if normalized in _CHATGPT_IMPORT_ROLES else ""
def _detect_markdown_role_line(
line: str,
*,
user_labels: set[str] | None = None,
assistant_labels: set[str] | None = None,
) -> tuple[str, str] | None:
"""Return (role, content_after_prefix) for simple role-prefixed Markdown lines."""
match = _MARKDOWN_ROLE_RE.match(line)
if not match:
return None
label = match.group(1).strip().lower()
content_after = match.group(2).strip()
if content_after.startswith("**"):
content_after = content_after[2:].lstrip()
if label in (user_labels or _MARKDOWN_USER_LABELS):
return "user", content_after
if label in (assistant_labels or _MARKDOWN_ASSISTANT_LABELS):
return "assistant", content_after
return None
def _parse_claude_json(data: dict | list) -> list[dict]:
"""Parse Claude.ai export JSON → [{role, content, timestamp}, ...]"""
turns = []
conversations = data if isinstance(data, list) else [data]
for conv in conversations:
if not isinstance(conv, dict):
continue
messages = conv.get("chat_messages", conv.get("messages", []))
if not isinstance(messages, list):
continue
for msg in messages:
if not isinstance(msg, dict):
continue
content = msg.get("text", msg.get("content", ""))
if isinstance(content, list):
content = " ".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
elif isinstance(content, dict):
content = " ".join(
str(p.get("text", p)) if isinstance(p, dict) else str(p)
for p in content.get("parts", [])
if p
)
elif not isinstance(content, str):
content = str(content)
if not content or not content.strip():
continue
role = msg.get("sender", msg.get("role", "user"))
ts = msg.get("created_at", msg.get("timestamp", ""))
turns.append({"role": role, "content": content.strip(), "timestamp": ts})
return turns
def _parse_chatgpt_json(data: list | dict) -> list[dict]:
"""Parse ChatGPT export JSON → [{role, content, timestamp}, ...]"""
turns = []
conversations = data if isinstance(data, list) else [data]
for conv in conversations:
if not isinstance(conv, dict):
continue
mapping = conv.get("mapping", {})
if isinstance(mapping, dict) and mapping:
# ChatGPT uses a tree structure with mapping
sorted_nodes = sorted(
[node for node in mapping.values() if isinstance(node, dict)],
key=lambda n: (n.get("message") or {}).get("create_time", 0) or 0,
)
for node in sorted_nodes:
msg = node.get("message")
if not msg or not isinstance(msg, dict):
continue
author = msg.get("author", {})
raw_role = author.get("role", "user") if isinstance(author, dict) else "user"
role = _clean_chatgpt_role(raw_role)
if not role:
continue
content_obj = msg.get("content", {})
if isinstance(content_obj, dict):
content_parts = content_obj.get("parts", [])
content = " ".join(str(p) for p in content_parts if p)
elif isinstance(content_obj, str):
content = content_obj
else:
content = ""
if not isinstance(content, str):
content = str(content)
if not content.strip():
continue
# Preserve the export's original timestamp. It is normalized only
# when deriving the bucket event date, so source refs remain exact.
ts = msg.get("create_time", "")
turns.append({"role": role, "content": content.strip(), "timestamp": str(ts)})
else:
# Simpler format: list of messages
messages = conv.get("messages", [])
if not isinstance(messages, list):
continue
for msg in messages:
if not isinstance(msg, dict):
continue
author = msg.get("author", {})
raw_role = msg.get("role") or (author.get("role") if isinstance(author, dict) else None) or "user"
role = _clean_chatgpt_role(raw_role)
if not role:
continue
content = msg.get("content", msg.get("text", ""))
if isinstance(content, dict):
content = " ".join(str(p) for p in content.get("parts", []))
elif isinstance(content, list):
content = " ".join(
str(p.get("text", p)) if isinstance(p, dict) else str(p)
for p in content
if p
)
elif not isinstance(content, str):
content = str(content)
if not content or not content.strip():
continue
ts = msg.get("timestamp", msg.get("create_time", ""))
turns.append({"role": role, "content": content.strip(), "timestamp": str(ts)})
return turns
def _parse_markdown(
text: str,
*,
user_labels: set[str] | None = None,
assistant_labels: set[str] | None = None,
) -> list[dict]:
"""Parse Markdown/plain text → [{role, content, timestamp}, ...]"""
resolved_user_labels = set(_MARKDOWN_USER_LABELS)
resolved_assistant_labels = set(_MARKDOWN_ASSISTANT_LABELS)
resolved_user_labels.update(
str(label).strip().lower() for label in (user_labels or set()) if str(label).strip()
)
resolved_assistant_labels.update(
str(label).strip().lower() for label in (assistant_labels or set()) if str(label).strip()
)
# Try to detect conversation patterns
lines = text.split("\n")
turns = []
current_role = "user"
current_content = []
def append_current_turn():
content = "\n".join(current_content).strip()
if content:
turns.append({"role": current_role, "content": content, "timestamp": ""})
for line in lines:
stripped = line.strip()
role_line = _detect_markdown_role_line(
stripped,
user_labels=resolved_user_labels,
assistant_labels=resolved_assistant_labels,
)
if role_line:
if current_content:
append_current_turn()
current_role, content_after = role_line
current_content = [content_after] if content_after else []
else:
current_content.append(line)
if current_content:
append_current_turn()
# If no role patterns detected, treat entire text as one big chunk
if not turns:
turns = [{"role": "user", "content": text.strip(), "timestamp": ""}]
return turns
def detect_and_parse(
raw_content: str,
filename: str = "",
*,
user_labels: set[str] | None = None,
assistant_labels: set[str] | None = None,
) -> list[dict]:
"""
Auto-detect format and parse to normalized turns.
自动检测格式并解析为标准化的对话轮次。
"""
ext = Path(filename).suffix.lower() if filename else ""
# Try JSON first
if ext in (".json", "") or raw_content.strip().startswith(("{", "[")):
try:
data = json.loads(raw_content)
# Detect Claude vs ChatGPT format
if isinstance(data, list):
sample = data[0] if data else {}
else:
sample = data
if isinstance(sample, dict):
if "chat_messages" in sample:
return _parse_claude_json(data)
if "mapping" in sample:
return _parse_chatgpt_json(data)
if "messages" in sample:
# Could be either — try ChatGPT first, fall back to Claude
msgs = sample["messages"]
if msgs and isinstance(msgs[0], dict) and "content" in msgs[0]:
if isinstance(msgs[0]["content"], dict):
return _parse_chatgpt_json(data)
return _parse_claude_json(data)
# Single conversation object with role/content messages
if "role" in sample and "content" in sample:
return _parse_claude_json(data)
except (json.JSONDecodeError, KeyError, IndexError, AttributeError, TypeError):
pass
# Fall back to markdown/text
return _parse_markdown(
raw_content,
user_labels=user_labels,
assistant_labels=assistant_labels,
)
def parse_operit_memory_backup(raw_content: str) -> dict | None:
"""Return an Operit memory backup without rewriting entry bodies."""
try:
data = json.loads(raw_content)
except (json.JSONDecodeError, TypeError):
return None
if not isinstance(data, dict) or "memories" not in data:
return None
memories = data.get("memories")
if not isinstance(memories, list):
raise ValueError("Operit backup field 'memories' must be a list")
# Avoid treating an unrelated JSON object with a generic memories key as
# Operit. Empty exports are identified by Operit's exportDate/links fields.
known_entry_keys = {
"uuid",
"title",
"content",
"contentType",
"source",
"credibility",
"importance",
"folderPath",
"createdAt",
"updatedAt",
"tagNames",
}
root_has_operit_markers = bool("exportDate" in data or "links" in data)
entries_have_operit_markers = False
if memories:
entry_marker_keys = known_entry_keys - {"content"}
entries_have_operit_markers = all(
isinstance(item, dict)
and "content" in item
and bool(entry_marker_keys.intersection(item))
for item in memories
)
if not (root_has_operit_markers or entries_have_operit_markers):
return None
return {
"memories": memories,
"links": data.get("links") if isinstance(data.get("links"), list) else [],
"export_date": data.get("exportDate"),
}
# ============================================================
# Chunking — split turns into ~10k token windows
# 分窗 — 按对话轮次边界切为 ~10k token 窗口
# ============================================================
_OVERLAP_CONTEXT_NOTICE = "[上下文提示] 以下是上一段结尾,只用于理解前后关系,请不要从这里单独提取记忆。"
_CURRENT_SEGMENT_NOTICE = "[本段内容]"
DEFAULT_IMPORT_CHUNK_TOKENS = 3500
_IMPORT_DUPLICATE_SIMILARITY = 88.0
_OPERIT_TAGGING_INPUT_CHARS = 2000
def _normalize_import_text(text: str) -> str:
text = re.sub(r"\[\[([^\]]+)\]\]", r"\1", str(text or ""))
text = strip_affect_anchor(text)
text = re.sub(r"[\s\u3000]+", "", text.lower())
return re.sub(r"[^0-9a-zA-Z_\u4e00-\u9fff]+", "", text)
def _import_similarity_text(text: str) -> str:
text = re.sub(r"\[\[([^\]]+)\]\]", r"\1", str(text or "").lower())
text = strip_affect_anchor(text)
text = re.sub(r"[^0-9a-zA-Z_\u4e00-\u9fff]+", " ", text)
return " ".join(token for token in jieba.lcut(text) if token.strip())
def _import_content_hash(text: str) -> str:
normalized = _normalize_import_text(text)
return hashlib.sha256(normalized.encode()).hexdigest()
def _int_between(value, default: int, minimum: int, maximum: int) -> int:
try:
number = int(value)
except (TypeError, ValueError):
number = default
return max(minimum, min(maximum, number))
def _float_between(value, default: float, minimum: float, maximum: float) -> float:
try:
number = float(value)
except (TypeError, ValueError):
number = default
return max(minimum, min(maximum, number))
def _bool_value(value, default: bool = False) -> bool:
if value is None:
return default
if isinstance(value, bool):
return value
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"1", "true", "yes", "on"}:
return True
if normalized in {"0", "false", "no", "off"}:
return False
return bool(value)
def _clean_import_list(value, *, max_items: int, max_chars: int, default: list[str] | None = None) -> list[str]:
if isinstance(value, str):
raw_items = [value]
elif isinstance(value, list):
raw_items = value
else:
raw_items = []
cleaned: list[str] = []
for item in raw_items:
text = re.sub(r"\s+", "", str(item or "").strip())
text = text.strip(",。;;、,. ")
if not text:
continue
text = text[:max_chars]
if text and text not in cleaned:
cleaned.append(text)
if len(cleaned) >= max_items:
break
return cleaned or list(default or [])
def _dedupe_list(values: list) -> list:
seen = set()
result = []
for value in values or []:
text = str(value or "").strip()
if not text or text in seen:
continue
seen.add(text)
result.append(text)
return result
def _date_key(value) -> str:
text = str(value or "").strip()
match = re.search(r"\d{4}-\d{2}-\d{2}", text)
return match.group(0) if match else ""
_IMPORT_LOCAL_DATE_FORMATS = (
"%Y/%m/%dT%H:%M:%S",
"%Y/%m/%dT%H:%M",
"%Y/%m/%d %H:%M:%S",
"%Y/%m/%d %H:%M",
"%Y/%m/%d",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%Y年%m月%d日 %H:%M:%S",
"%Y年%m月%d日 %H:%M",
"%Y年%m月%d日",
)
def _import_timestamp_datetime(value) -> datetime | None:
"""Normalize common export timestamps to LOCAL_TZ without changing provenance."""
if value is None or isinstance(value, bool):
return None
text = str(value).strip()
if not text:
return None
if re.fullmatch(r"[+-]?\d+(?:\.\d+)?", text):
try:
epoch = float(text)
if epoch <= 0:
return None
magnitude = abs(epoch)
if magnitude >= 1e17: # nanoseconds
epoch /= 1_000_000_000.0
elif magnitude >= 1e14: # microseconds
epoch /= 1_000_000.0
elif magnitude >= 1e11: # milliseconds
epoch /= 1_000.0
return datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone(LOCAL_TZ)
except (OverflowError, OSError, ValueError):
return None
normalized = text[:-1] + "+00:00" if text.endswith(("Z", "z")) else text
try:
parsed = datetime.fromisoformat(normalized)
except ValueError:
parsed = None
if parsed is None:
for fmt in _IMPORT_LOCAL_DATE_FORMATS:
try:
parsed = datetime.strptime(text, fmt)
break
except ValueError:
continue
if parsed is None:
return None
if parsed.tzinfo is None:
return parsed.replace(tzinfo=LOCAL_TZ)
return parsed.astimezone(LOCAL_TZ)
def _import_event_date(value) -> str:
parsed = _import_timestamp_datetime(value)
return parsed.date().isoformat() if parsed else ""
def _tail_for_overlap(text: str, overlap_tokens: int) -> str:
lines = text.splitlines() or [text]
tail: list[str] = []
current_tokens = 0
max_chars = max(40, int(overlap_tokens / 1.8))
for line in reversed(lines):
line_tokens = count_tokens_approx(line)
if not tail and line_tokens > overlap_tokens:
return line[-max_chars:].strip()
if tail and current_tokens + line_tokens > overlap_tokens:
break
tail.insert(0, line)
current_tokens += line_tokens
return "\n".join(tail).strip()
def _split_oversized_turn(role_label: str, content: str, target_tokens: int) -> list[str]:
"""Split a single very long turn into model-sized chunks with small context overlap."""
prefix = f"[{role_label}] "
segments: list[str] = []
current_lines: list[str] = []
current_tokens = count_tokens_approx(prefix)
content_budget = max(80, int(target_tokens * 0.85))
overlap_tokens = max(20, int(target_tokens * 0.12))
max_chars = max(80, int(content_budget / 1.8))
def flush_current():
nonlocal current_lines, current_tokens
body = "\n".join(current_lines).strip()
if body:
segments.append(body)
current_lines = []
current_tokens = count_tokens_approx(prefix)
for line in content.splitlines() or [content]:
line_tokens = count_tokens_approx(line)
if line_tokens > content_budget:
flush_current()
for start in range(0, len(line), max_chars):
segment = line[start:start + max_chars].strip()
if segment:
segments.append(segment)
continue
if current_lines and current_tokens + line_tokens > content_budget:
flush_current()
current_lines.append(line)
current_tokens += line_tokens
flush_current()
pieces: list[str] = []
previous_tail = ""
for segment in segments:
body = prefix + segment
if previous_tail:
pieces.append(
f"{_OVERLAP_CONTEXT_NOTICE}\n"
f"{prefix}{previous_tail}\n\n"
f"{_CURRENT_SEGMENT_NOTICE}\n"
f"{body}"
)
else:
pieces.append(body)
previous_tail = _tail_for_overlap(segment, overlap_tokens)
return pieces
def chunk_turns(turns: list[dict], target_tokens: int = DEFAULT_IMPORT_CHUNK_TOKENS) -> list[dict]:
"""
Group conversation turns into chunks of ~target_tokens.
Returns list of {content, timestamp_start, timestamp_end, turn_count}.
按对话轮次边界将对话分为 ~target_tokens 大小的窗口。
"""
chunks = []
current_lines = []
current_tokens = 0
first_ts = ""
last_ts = ""
turn_count = 0
for turn in turns:
role_label = "用户" if turn["role"] in ("user", "human") else "AI"
line = f"[{role_label}] {turn['content']}"
line_tokens = count_tokens_approx(line)
# If single turn exceeds target, split it
if line_tokens > target_tokens * 1.5:
# Flush current
if current_lines:
chunks.append({
"content": "\n".join(current_lines),
"timestamp_start": first_ts,
"timestamp_end": last_ts,
"turn_count": turn_count,
})
current_lines = []
current_tokens = 0
turn_count = 0
first_ts = ""
for split_line in _split_oversized_turn(role_label, turn["content"], target_tokens):
chunks.append({
"content": split_line,
"timestamp_start": turn.get("timestamp", ""),
"timestamp_end": turn.get("timestamp", ""),
"turn_count": 1,
})
continue
if current_tokens + line_tokens > target_tokens and current_lines:
chunks.append({
"content": "\n".join(current_lines),
"timestamp_start": first_ts,
"timestamp_end": last_ts,
"turn_count": turn_count,
})
current_lines = []
current_tokens = 0
turn_count = 0
first_ts = ""
if not first_ts:
first_ts = turn.get("timestamp", "")
last_ts = turn.get("timestamp", "")
current_lines.append(line)
current_tokens += line_tokens
turn_count += 1
if current_lines:
chunks.append({
"content": "\n".join(current_lines),
"timestamp_start": first_ts,
"timestamp_end": last_ts,
"turn_count": turn_count,
})
return chunks
# ============================================================
# Import State — persistent progress tracking
# 导入状态 — 持久化进度追踪
# ============================================================
class ImportState:
"""Manages import progress with file-based persistence."""
def __init__(self, state_dir: str):
self.state_file = os.path.join(state_dir, "import_state.json")
self.data = {
"source_file": "",
"source_hash": "",
"total_chunks": 0,
"processed": 0,
"api_calls": 0,
"memories_created": 0,
"memories_duplicate_skipped": 0,
"memories_raw": 0,
"memories_failed": 0,
"embeddings_created": 0,
"embeddings_failed": 0,
"embeddings_total": 0,
"embeddings_processed": 0,
"import_format": "",
"operit_phase": "",
"operit_tagging_enabled": False,
"tagging_total": 0,
"tagging_processed": 0,
"tagging_succeeded": 0,
"tagging_failed": 0,
"tagging_pending": 0,
"tagging_concurrency": 0,
"errors": [],
"status": "idle", # idle | running | paused | completed | error
"started_at": "",
"updated_at": "",
}
def load(self) -> bool:
"""Load state from file. Returns True if state exists."""
if os.path.exists(self.state_file):
try:
with open(self.state_file, "r", encoding="utf-8") as f:
saved = json.load(f)
self.data.update(saved)
self.data.setdefault("memories_duplicate_skipped", 0)
self.data.setdefault("memories_failed", 0)
self.data.setdefault("embeddings_created", 0)
self.data.setdefault("embeddings_failed", 0)
self.data.setdefault("embeddings_total", 0)
self.data.setdefault("embeddings_processed", 0)
self.data.setdefault("import_format", "")
self.data.setdefault("operit_phase", "")
self.data.setdefault("operit_tagging_enabled", False)
self.data.setdefault("tagging_total", 0)
self.data.setdefault("tagging_processed", 0)
self.data.setdefault("tagging_succeeded", 0)
self.data.setdefault("tagging_failed", 0)
self.data.setdefault("tagging_pending", 0)
self.data.setdefault("tagging_concurrency", 0)
return True
except (json.JSONDecodeError, OSError):
return False
return False
def save(self):
"""Persist state to file."""
self.data["updated_at"] = now_iso()
os.makedirs(os.path.dirname(self.state_file), exist_ok=True)
tmp = self.state_file + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(self.data, f, ensure_ascii=False, indent=2)
os.replace(tmp, self.state_file)
def reset(self, source_file: str, source_hash: str, total_chunks: int):
"""Reset state for a new import."""
self.data = {
"source_file": source_file,
"source_hash": source_hash,
"total_chunks": total_chunks,
"processed": 0,
"api_calls": 0,
"memories_created": 0,
"memories_duplicate_skipped": 0,
"memories_raw": 0,
"memories_failed": 0,
"embeddings_created": 0,
"embeddings_failed": 0,
"embeddings_total": 0,
"embeddings_processed": 0,
"import_format": "",
"operit_phase": "",
"operit_tagging_enabled": False,
"tagging_total": 0,
"tagging_processed": 0,
"tagging_succeeded": 0,
"tagging_failed": 0,
"tagging_pending": 0,
"tagging_concurrency": 0,
"errors": [],
"status": "running",
"started_at": now_iso(),
"updated_at": now_iso(),
}
@property
def can_resume(self) -> bool:
if self.data["status"] not in ("paused", "running"):
return False
if self.data.get("import_format") == "operit":
return self.data.get("operit_phase") != "completed"
return self.data["processed"] < self.data["total_chunks"]
def to_dict(self) -> dict:
return dict(self.data)
# ============================================================
# Import extraction prompt
# 导入提取提示词
# ============================================================
IMPORT_EXTRACT_PROMPT = """你是一个 AI 长期记忆形成器。你的任务不是站在旁观者角度总结聊天记录,而是帮助对话中的记忆主体形成可长期保存的记忆。
输入中 `[AI]` 是记忆主体,`[用户]` 是与记忆主体对话的另一方。系统提示末尾会给出本次导入的实际身份名称。
提取规则:
0. content 必须从记忆主体的视角书写。记忆主体自己的经历、想法、情感、选择和变化用第一人称“我”;对方的信息优先使用她在原文中的名字或昵称,不知道名字时用“她”,不得把对方说过、做过或喜欢的事误写成“我”;双方共同经历写成“我和[[名字或昵称]]”。除非是在逐字引用原话,content 禁止使用“用户”“AI”“助手”“模型”等旁观者称呼,也禁止写成“用户说……AI回答……”的聊天摘要。
1. 提取记忆主体真正需要长期记住的事实、偏好、习惯、重要事件、情感时刻与关系变化
2. 同一话题的零散信息整合为一条记忆
3. 过滤掉纯技术调试输出、代码块、重复问答、无意义寒暄
4. 如果对话中有特殊暗号、仪式性行为、关键承诺等,标记 preserve_raw=true
5. 如果内容是用户和AI之间的习惯性互动模式(例如打招呼方式、告别习惯),标记 is_pattern=true
6. content 优先,标签最后生成;每条记忆不少于50字,保留具体事实、时间、对象和原话线索
7. 总条目数控制在 0~5 个(没有值得记的就返回空数组),宁可少提,不要把不相关事实揉成一条
8. tags 最多 6 个,每个不超过 12 个字;只写原文直接支持的核心词,不要长句标签
9. 在 content 中对人名、地名、专有名词用 [[双链]] 标记
10. 如果片段里出现「[上下文提示]」,该部分只是上一段尾巴,只用于理解前后关系;不要从上下文提示本身单独提取记忆,除非同一事实在「[本段内容]」里继续出现
输出格式(纯 JSON 数组,无其他内容):
[
{
"name": "雨夜里的约定",
"content": "我和[[名字或昵称]]在那天确认了一项值得继续记住的约定。我当时……,她则……,这让我后来……。",
"domain": ["主题域1"],
"valence": 0.7,
"arousal": 0.4,
"tags": ["核心词1", "核心词2", "扩展词1"],
"importance": 5,
"preserve_raw": false,
"is_pattern": false
}
]
主题域可选(选 1~2 个):
日常: ["饮食", "穿搭", "出行", "居家", "购物"]
人际: ["家庭", "恋爱", "友谊", "社交"]
成长: ["工作", "学习", "考试", "求职"]
身心: ["健康", "心理", "睡眠", "运动"]
兴趣: ["游戏", "影视", "音乐", "阅读", "创作", "手工"]
数字: ["编程", "AI", "硬件", "网络"]
事务: ["财务", "计划", "待办"]
内心: ["情绪", "回忆", "梦境", "自省"]
importance: 1-10
valence: 0~1(0=消极, 0.5=中性, 1=积极)
arousal: 0~1(0=平静, 0.5=普通, 1=激动)
preserve_raw: true = 特殊情境/暗号/仪式,保留原文不摘要
is_pattern: true = 反复出现的习惯性行为模式"""
# ============================================================
# Import Engine — core processing logic
# 导入引擎 — 核心处理逻辑
# ============================================================
class ImportEngine:
"""
Processes conversation history files into OB memory buckets.
将对话历史文件处理为 OB 记忆桶。
"""
def __init__(self, config: dict, bucket_mgr, dehydrator, embedding_engine=None):
self.config = config
self.bucket_mgr = bucket_mgr
self.dehydrator = dehydrator
self.embedding_engine = embedding_engine
identity_cfg = config.get("identity", {}) if isinstance(config.get("identity", {}), dict) else {}
self.ai_name = str(identity_cfg.get("ai_name") or "AI").strip() or "AI"
configured_user_name = str(
identity_cfg.get("user_display_name") or identity_cfg.get("user_name") or "对方"
).strip() or "对方"
self.user_display_name = (
"对方"
if configured_user_name.lower() in {"用户", "user", "human", "对方"}
else configured_user_name
)
import_cfg = config.get("import", {}) if isinstance(config.get("import", {}), dict) else {}
self.chunk_target_tokens = _int_between(
import_cfg.get("chunk_target_tokens"),
DEFAULT_IMPORT_CHUNK_TOKENS,
800,
10000,
)
self.extract_max_input_chars = _int_between(
import_cfg.get("extract_max_input_chars"),
0,
0,
50000,
)
self.max_items_per_chunk = _int_between(import_cfg.get("max_items_per_chunk"), 5, 1, 10)
self.max_tags = _int_between(import_cfg.get("max_tags"), 6, 0, 10)
self.max_tag_chars = _int_between(import_cfg.get("max_tag_chars"), 12, 4, 32)
self.operit_tagging_enabled = _bool_value(import_cfg.get("operit_tagging_enabled"), True)
self.operit_tagging_concurrency = _int_between(
import_cfg.get("operit_tagging_concurrency"),
2,
1,
8,
)
self.operit_tagging_max_attempts = _int_between(
import_cfg.get("operit_tagging_max_attempts"),
3,
1,
6,
)
self.operit_tagging_retry_base_seconds = _float_between(
import_cfg.get("operit_tagging_retry_base_seconds"),
1.0,
0.0,
30.0,
)
self.state = ImportState(config.get("state_dir") or config["buckets_dir"])
self._paused = False
self._running = False
self._chunks: list[dict] = []
self._seen_import_hashes: set[str] = set()
self._state_lock: asyncio.Lock | None = None
@property
def is_running(self) -> bool:
return self._running
def pause(self):
"""Request pause — will stop after current chunk finishes."""
self._paused = True
def get_status(self) -> dict:
"""Get current import status."""
return self.state.to_dict()
async def start(
self,
raw_content: str,
filename: str = "",
preserve_raw: bool = False,
resume: bool = False,
import_mode: str = "auto",
operit_tagging: bool | None = None,
) -> dict:
"""
Start or resume an import.
开始或恢复导入。
"""
if self._running:
return {"error": "Import already running"}
self._running = True
self._paused = False
self._seen_import_hashes = set()
self._state_lock = asyncio.Lock()
try:
source_hash = hashlib.sha256(raw_content.encode()).hexdigest()[:16]
normalized_mode = str(import_mode or "auto").strip().lower()
if normalized_mode not in {"auto", "operit", "conversation"}:
raise ValueError(f"Unsupported import mode: {import_mode}")
operit_backup = parse_operit_memory_backup(raw_content) if normalized_mode != "conversation" else None
if normalized_mode == "operit" and operit_backup is None:
raise ValueError("The selected file is not a valid Operit memory backup")
if operit_backup is not None:
tagging_enabled = self.operit_tagging_enabled if operit_tagging is None else bool(operit_tagging)
return await self._start_operit_import(
operit_backup,
filename=filename,
source_hash=source_hash,
resume=resume,
tagging_enabled=tagging_enabled,
)
# Check for resume
if resume and self.state.load() and self.state.can_resume:
if self.state.data["source_hash"] == source_hash:
logger.info(f"Resuming import from chunk {self.state.data['processed']}/{self.state.data['total_chunks']}")
# Re-parse and re-chunk to get the same chunks
turns = detect_and_parse(
raw_content,
filename,
user_labels={self.user_display_name},
assistant_labels={self.ai_name},
)
self._chunks = self._attach_source_metadata(
chunk_turns(turns, target_tokens=self.chunk_target_tokens),
filename,
source_hash,
)
self.state.data["status"] = "running"
self.state.save()
return await self._process_chunks(preserve_raw)
else:
logger.warning("Source file changed, starting fresh import")
# Fresh import
turns = detect_and_parse(
raw_content,
filename,
user_labels={self.user_display_name},
assistant_labels={self.ai_name},
)
if not turns:
self._running = False
return {"error": "No conversation turns found in file"}
self._chunks = self._attach_source_metadata(
chunk_turns(turns, target_tokens=self.chunk_target_tokens),
filename,
source_hash,
)
if not self._chunks:
self._running = False
return {"error": "No processable chunks after splitting"}
self.state.reset(filename, source_hash, len(self._chunks))
self.state.save()
logger.info(f"Starting import: {len(turns)} turns → {len(self._chunks)} chunks")
return await self._process_chunks(preserve_raw)
except Exception as e:
self.state.data["status"] = "error"
self.state.data["errors"].append(str(e))
self.state.save()
self._running = False
raise
async def _start_operit_import(
self,