File size: 1,763 Bytes
d7dfeff |
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 |
import pickle
import os
FILE_PATH = "chat_history.pkl"
if not os.path.exists(FILE_PATH):
with open(FILE_PATH, "wb") as file:
pickle.dump({}, file)
def save_chat_entry(session_id, role, transcript):
try:
with open(FILE_PATH, "rb") as file:
data = pickle.load(file)
if session_id not in data:
data[session_id] = []
if role == "user":
data[session_id].append({
"role": role,
"transcript": transcript
})
else:
if data[session_id] and data[session_id][-1]['role'] == "assistant":
data[session_id][-1]['transcript'] += " " + transcript
else:
data[session_id].append({
"role": role,
"transcript": transcript
})
with open(FILE_PATH, "wb") as file:
pickle.dump(data, file)
except Exception as e:
print(f"Error saving chat entry: {e}")
def get_chat_history(session_id):
try:
with open(FILE_PATH, "rb") as file:
data = pickle.load(file)
chat_history = data.get(session_id, [])
if not chat_history:
return []
message_history = []
for entry in chat_history:
role = entry.get('role', '')
transcript = entry.get('transcript', '')
if role and transcript:
message_history.append({"role": role, "content": transcript})
return message_history
except (FileNotFoundError, pickle.UnpicklingError) as e:
print(f"Error reading or parsing the file: {e}")
return []
except Exception as e:
print(f"Unexpected error: {e}")
return []
|