-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
82 lines (56 loc) · 1.36 KB
/
Copy pathmemory.py
File metadata and controls
82 lines (56 loc) · 1.36 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
# memory.py
import json
import os
from datetime import datetime
MEMORY_FILE = "memory.json"
def load_memories():
if not os.path.exists(MEMORY_FILE):
return []
try:
with open(MEMORY_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
return data.get("memories", [])
except Exception:
return []
def save_memories(memories):
with open(MEMORY_FILE, "w", encoding="utf-8") as f:
json.dump(
{"memories": memories},
f,
indent=2,
ensure_ascii=False
)
def remember(text):
memories = load_memories()
memories.append({
"timestamp": datetime.now().isoformat(),
"text": text
})
save_memories(memories)
def retrieve_memories(query, limit=10):
memories = load_memories()
query_words = set(
query.lower().split()
)
scored = []
for memory in memories:
memory_words = set(
memory["text"].lower().split()
)
score = len(
query_words.intersection(
memory_words
)
)
if score > 0:
scored.append(
(score, memory)
)
scored.sort(
reverse=True,
key=lambda x: x[0]
)
return [
item[1]["text"]
for item in scored[:limit]
]