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 []