-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
71 lines (63 loc) · 2.02 KB
/
Copy pathmemory.py
File metadata and controls
71 lines (63 loc) · 2.02 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
import os
import json
import datetime
MEMORY_FILE = "memory/conversations.json"
TOPICS_FILE = "memory/learned_topics.json"
def load_memory():
os.makedirs("memory", exist_ok=True)
if os.path.exists(MEMORY_FILE):
with open(MEMORY_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return []
def save_memory(history, rating=None):
memory = load_memory()
session = {
"date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
"messages": history,
"rating": rating
}
memory.append(session)
with open(MEMORY_FILE, "w", encoding="utf-8") as f:
json.dump(memory, f, indent=2, ensure_ascii=False)
print("[Memory] Session saved!")
def get_memory_context():
memory = load_memory()
if not memory:
return ""
context = ""
# All recent conversations use
for session in memory[-5:]:
for msg in session["messages"]:
if msg["role"] == "user":
context += f"Past Q: {msg['content']}\n"
elif msg["role"] == "assistant":
context += f"Past A: {msg['content'][:300]}\n"
context += "\n"
return context[:3000]
def save_learned_topic(topic):
os.makedirs("memory", exist_ok=True)
topics = []
if os.path.exists(TOPICS_FILE):
with open(TOPICS_FILE, "r") as f:
topics = json.load(f)
if topic not in topics:
topics.append(topic)
with open(TOPICS_FILE, "w") as f:
json.dump(topics, f, indent=2)
def get_learned_topics():
if os.path.exists(TOPICS_FILE):
with open(TOPICS_FILE, "r") as f:
return json.load(f)
return []
def get_feedback():
while True:
try:
rating = input("\n[Feedback] Rate Me (1-5 OR Enter skip): ").strip()
if rating == "":
return None
rating = int(rating)
if 1 <= rating <= 5:
return rating
print("write in between 1 to 5")
except ValueError:
return None