import json import streamlit as st import os from set_context import set_context import uuid set_context_all = {"不设置": ""} set_context_all.update(set_context) # 用户名 user_name = 'User' gpt_name = 'ChatGPT' # 头像(svg格式) 来自 https://www.dicebear.com/playground?style=identicon user_svg = """ """ gpt_svg = """ """ # 聊天记录文件夹名称 history_chats_filename = 'chat_history' initial_content_history = [{"role": 'system', "content": '当你的回复中涉及代码块时,请在markdown语法中标明语言类型。如果不涉及,请忽略这句话。'}] initial_content_all = {"history": initial_content_history, "paras": { "temperature": 1.0, "top_p": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, }, "contexts": { 'context_select': '不设置', 'context_input': '', 'context_level': 5 } } def get_history_chats(file_name=history_chats_filename): try: os.mkdir(file_name) except FileExistsError: pass files = [f for f in os.listdir(f'./{file_name}') if f.endswith('.json')] files_with_time = [(f, os.stat(f'./{file_name}/' + f).st_ctime) for f in files] sorted_files = sorted(files_with_time, key=lambda x: x[1], reverse=True) chat_names = [os.path.splitext(f[0])[0] for f in sorted_files] if len(chat_names) == 0: chat_names.append('New Chat_' + str(uuid.uuid4())) return chat_names def save_data(current_chat: str, history: list, paras: dict, contexts: dict, **kwargs): with open(f"./{history_chats_filename}/{current_chat}.json", 'w', encoding='utf-8') as f: json.dump({"history": history, "paras": paras, "contexts": contexts, **kwargs}, f) def remove_data(current_chat: str): os.remove(f"./{history_chats_filename}/{current_chat}.json") def load_data(current_chat: str) -> dict: try: with open(f"./{history_chats_filename}/{current_chat}.json", 'r', encoding='utf-8') as f: data = json.load(f) return data except FileNotFoundError: with open(f"./{history_chats_filename}/{current_chat}.json", 'w', encoding='utf-8') as f: f.write(json.dumps(initial_content_all)) return initial_content_all def show_each_message(message, role, area=None): if area is None: area = [st.markdown] * 2 if role == 'user': icon = user_svg name = user_name background_color = '#ffffff' else: icon = gpt_svg name = gpt_name background_color = '#fafbfc' area[0](f"\n