-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
76 lines (52 loc) · 1.7 KB
/
Copy pathmemory.py
File metadata and controls
76 lines (52 loc) · 1.7 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
import json
import os
from langchain_core.messages import HumanMessage, AIMessage
# save the chat inside the json file
def save_history(chat_history, chat_id):
messages = []
for message in chat_history:
messages.append(
{
"type": message.type,
"content": message.content
}
)
history = {
"chat_name": chat_history[0].content,
"chat_id": chat_id,
"messages": messages
}
with open(f"history/{chat_id}.json", "w") as f:
json.dump(history, f, indent=4)
# get all chat names to display in sidebar
def get_all_chats():
chats = []
for file in os.listdir("history"):
if file.endswith(".json"):
with open(f"history/{file}", "r") as f:
chat = json.load(f)
chats.append(chat)
return chats
# load a particular chat on main screen when user clicks on that chat
def load_chat(chat_id):
with open(f"history/{chat_id}.json", "r") as f:
chat = json.load(f)
chat_history = []
for message in chat["messages"]:
if message["type"] == "human":
chat_history.append(
HumanMessage(content=message["content"])
)
elif message["type"] == "ai":
chat_history.append(
AIMessage(content=message["content"])
)
return chat_history
def delete_chat(chat_id):
file_path = f"history/{chat_id}.json"
if os.path.exists(file_path):
os.remove(file_path)
# """
# One small note: chat_history[0].content assumes the first message is always a HumanMessage,
# which is true for your application. So this is a good solution for now.
# """