-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
39 lines (33 loc) · 1.14 KB
/
memory.py
File metadata and controls
39 lines (33 loc) · 1.14 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
import json
class Memory:
def __init__(self, json_file: str):
self.m_json = json_file
self._initialize_file()
def _initialize_file(self):
try:
with open(self.m_json, 'r+') as f:
try:
data = json.load(f)
except json.JSONDecodeError:
data = {}
if "History" not in data:
data["History"] = []
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()
except FileNotFoundError:
with open(self.m_json, 'w') as f:
json.dump({"History": []}, f, indent=4)
def load(self):
with open(self.m_json, "r") as f:
try:
return json.load(f)
except json.JSONDecodeError:
return {"History": []}
def save(self, input_text, output_text):
with open(self.m_json, "r+") as f:
data = self.load()
data["History"].append({"user": input_text, "assistant": output_text})
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()