Spaces:
Runtime error
Runtime error
Update app.py
Browse files3 unmodified lines45678910111213141516171825 unmodified lines444546474849505152532 unmodified lines565758596061625 unmodified lines6869707172737425 unmodified lines1001011021031041051062 unmodified lines10911011111211311411511611711811912012112213 unmodified lines13613713813914014114214311 unmodified lines1551561571581591601611621631641651661 unmodified line1681691701711721731741751761771781791801811821831841851861871881891901911921931941958 unmodified lines20420520620720820911 unmodified lines2212222232242252262272282292302312322332342 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582 unmodified lines26126226326426526626726826927027135 unmodified lines3073083093103 unmodified linesimport copyimport pandas as pdimport openaifrom requests.models import ChunkedEncodingErrorst.set_page_config(page_title='ChatGPT Assistant', layout='wide')# 自定义元素样式# 第一个是减少侧边栏顶部空白,不同版本的st存在区别(此处适用1.19.0)st.markdown("""<style>div.css-1vq4p4l.e1fqkh3o4 {padding-top: 3.5rem !important;}.avatar {display: flex;25 unmodified linesmargin : 2px;}#chat-window{color: black;padding: 10px 0px;text-decoration: none;font-size: 25px;}#chat-window:hover{color: blue;2 unmodified lines""", unsafe_allow_html=True)if "initial_settings" not in st.session_state:# 历史聊天窗口st.session_state['history_chats'] = get_history_chats()# ss参数初始化st.session_state['pre_chat'] = Nonest.session_state['if_chat_change'] = False5 unmodified lineswith st.sidebar:# 此处href与下文的st.header内容相对应,跳转锚点st.markdown("<a href='#chatgpt-assistant' id='chat-window'>🤖 聊天窗口</a>", unsafe_allow_html=True)current_chat = st.radio(label='历史聊天窗口',format_func=lambda x: x.split('_')[0] if '_' in x else x,25 unmodified lineselse:st.session_state["current_chat_index"] = 0st.session_state['history_chats'].remove(current_chat)remove_data(current_chat)c1, c2 = st.columns(2)2 unmodified linesdelete_chat_button = c2.button('删除', use_container_width=True, key='delete_chat_button',on_click=delete_chat_button_callback)# 加载数据if ("history" + current_chat not in st.session_state) or (st.session_state['if_chat_change']):for key, value in load_data(current_chat).items():if key == 'history':st.session_state[key + current_chat] = valueelse:for k, v in value.items():st.session_state[k + current_chat] = vst.session_state['if_chat_change'] = False# 对话展示13 unmodified lines"context_input": st.session_state["context_input" + current_chat],"context_level": st.session_state["context_level" + current_chat],}save_data(new_chat_name, st.session_state["history" + current_chat], st.session_state["paras"],st.session_state["contexts"])# 输入内容展示11 unmodified lineswith tap_context:set_context_list = list(set_context_all.keys())context_select_index = set_context_list.index(st.session_state['context_select' + current_chat])st.selectbox(label='选择上下文', options=set_context_list, key='context_select' + current_chat,index=context_select_index, on_change=write_data)st.caption(set_context_all[st.session_state['context_select' + current_chat]])st.text_area(label='补充或自定义上下文:', key="context_input" + current_chat,value=st.session_state['context_input' + current_chat],on_change=write_data)with tap_set:1 unmodified linest.session_state['history' + current_chat] = copy.deepcopy(initial_content_history)write_data()st.button("清空聊天记录", use_container_width=True, on_click=clear_button_callback)st.caption("包含上下文次数:")st.slider("Context Level", 1, 10, st.session_state['context_level' + current_chat], 1, on_change=write_data,key='context_level' + current_chat, help="表示包含在每次会话中的历史对话次数,预设内容不计算在内。")st.caption("模型参数:")st.slider("Temperature", 0.0, 2.0, st.session_state["temperature" + current_chat], 0.1,help="""在0和2之间,应该使用什么样的采样温度?较高的值(如0.8)会使输出更随机,而较低的值(如0.2)则会使其更加集中和确定性。我们一般建议只更改这个参数或top_p参数中的一个,而不要同时更改两个。""",on_change=write_data, key='temperature' + current_chat)st.slider("Top P", 0.1, 1.0, st.session_state["top_p" + current_chat], 0.1,help="""一种替代采用温度进行采样的方法,称为“基于核心概率”的采样。在该方法中,模型会考虑概率最高的top_p个标记的预测结果。因此,当该参数为0.1时,只有包括前10%概率质量的标记将被考虑。我们一般建议只更改这个参数或采样温度参数中的一个,而不要同时更改两个。""",on_change=write_data, key='top_p' + current_chat)st.slider("Presence Penalty", -2.0, 2.0,st.session_state["presence_penalty" + current_chat], 0.1,help="""该参数的取值范围为-2.0到2.0。正值会根据新标记是否出现在当前生成的文本中对其进行惩罚,从而增加模型谈论新话题的可能性。""",on_change=write_data, key='presence_penalty' + current_chat)st.slider("Frequency Penalty", -2.0, 2.0,st.session_state["frequency_penalty" + current_chat], 0.1,help="""该参数的取值范围为-2.0到2.0。正值会根据新标记在当前生成的文本中的已有频率对其进行惩罚,从而减少模型直接重复相同语句的可能性。""",on_change=write_data, key='frequency_penalty' + current_chat)st.caption("[官网参数说明](https://platform.openai.com/docs/api-reference/completions/create)")8 unmodified linesreturn resdef extract_chars(text, num):char_num = 0chars = ''11 unmodified linesdef user_input_area_callback():# 清空输入框st.session_state['user_input_content'] = st.session_state['user_input_area']st.session_state['user_input_area'] = ''# 修改窗口名称user_input_content = st.session_state['user_input_content']df_history = pd.DataFrame(st.session_state["history" + current_chat])if len(df_history.query('role!="system"')) == 0:remove_data(current_chat)current_chat_index = st.session_state['history_chats'].index(current_chat)new_name = extract_chars(user_input_content, 18) + '_' + str(uuid.uuid4())st.session_state['history_chats'][current_chat_index] = new_name2 unmodified lineswrite_data(new_name)st.text_area("**输入:**", key="user_input_area", on_change=user_input_area_callback,help="点击侧边栏标题可直接跳转此输入区 \n""此功能目前在Hugging Face不可用")if st.session_state['user_input_content'].strip() != '':st.session_state['pre_user_input_content'] = st.session_state['user_input_content']st.session_state['user_input_content'] = ''show_each_message(st.session_state['pre_user_input_content'], 'user',[area_user_svg.markdown, area_user_content.markdown])history_tem = st.session_state["history" + current_chat] + \[{"role": "user", "content": st.session_state['pre_user_input_content'].replace('\n', '\n\n')}]context_level_tem = st.session_state['context_level' + current_chat]history_need_input = ([{"role": "system","content": set_context_all[st.session_state['context_select' + current_chat]]}]+ [{"role": "system","content": st.session_state['context_input' + current_chat]}]+ get_history_input(history_tem, context_level_tem))paras_need_input = {"temperature": st.session_state["temperature" + current_chat],"top_p": st.session_state["top_p" + current_chat],2 unmodified lines}with st.spinner("🤔"):try:openai.api_key = st.secrets["apikey"]r = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=history_need_input, stream=True,**paras_need_input)except (FileNotFoundError, KeyError):area_error.error("缺失 OpenAI API Key,请在st.secrets中完成配置。")except openai.error.AuthenticationError:area_error.error("无效的 OpenAI API Key。")except openai.error.APIConnectionError as e:35 unmodified linesif current_chat + 'report' in st.session_state:st.session_state.pop(current_chat + 'report')if 'r' in st.session_state:st.session_state.pop("r")3 unmodified lines456789101112131415161718192025 unmodified lines46474849505152532 unmodified lines56575859606162635 unmodified lines6970717273747525 unmodified lines1011021031041051061072 unmodified lines11011111211311411511611711811912012112212312412512612713 unmodified lines14114214314414514614714811 unmodified lines1601611621631641651661671681691701711 unmodified line1731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022038 unmodified lines21221321421521621721821922022122211 unmodified lines2342352362372382392402412422432442452462472482 unmodified lines2512522532542552562572582592602612622632642652662672682692702 unmodified lines27327427527627727827928028128228328428528628735 unmodified lines3233243253263 unmodified linesimport copyimport pandas as pdimport openaiimport refrom requests.models import ChunkedEncodingErrorst.set_page_config(page_title='ChatGPT Assistant', layout='wide', page_icon='🤖')# 自定义元素样式# 第一个是减少侧边栏顶部空白,不同版本的st存在区别(此处适用1.19.0)st.markdown("""<style>div.css-1vq4p4l.e1fqkh3o4 {padding-top: 2rem !important;}.avatar {display: flex;25 unmodified linesmargin : 2px;}#chat-window{padding: 10px 0px;text-decoration: none;}#chat-window:hover{color: blue;2 unmodified lines""", unsafe_allow_html=True)if "initial_settings" not in st.session_state:# 历史聊天窗口st.session_state["path"] = set_chats_path()st.session_state['history_chats'] = get_history_chats(st.session_state["path"])# ss参数初始化st.session_state['pre_chat'] = Nonest.session_state['if_chat_change'] = False5 unmodified lineswith st.sidebar:# 此处href与下文的st.header内容相对应,跳转锚点st.markdown("# 🤖 聊天窗口")current_chat = st.radio(label='历史聊天窗口',format_func=lambda x: x.split('_')[0] if '_' in x else x,25 unmodified lineselse:st.session_state["current_chat_index"] = 0st.session_state['history_chats'].remove(current_chat)remove_data(st.session_state["path"], current_chat)c1, c2 = st.columns(2)2 unmodified linesdelete_chat_button = c2.button('删除', use_container_width=True, key='delete_chat_button',on_click=delete_chat_button_callback)st.write("\n")st.write("\n")st.markdown("<a href='#chatgpt-assistant' id='chat-window'>➡️ 直达输入区</a>",unsafe_allow_html=True)# 加载数据if ("history" + current_chat not in st.session_state) or (st.session_state['if_chat_change']):for key, value in load_data(st.session_state["path"], current_chat).items():if key == 'history':st.session_state[key + current_chat] = valueelse:for k, v in value.items():st.session_state[k + current_chat + 'default'] = vst.session_state['if_chat_change'] = False# 对话展示13 unmodified lines"context_input": st.session_state["context_input" + current_chat],"context_level": st.session_state["context_level" + current_chat],}save_data(st.session_state["path"], new_chat_name, st.session_state["history" + current_chat],st.session_state["paras"], st.session_state["contexts"])# 输入内容展示11 unmodified lineswith tap_context:set_context_list = list(set_context_all.keys())context_select_index = set_context_list.index(st.session_state['context_select' + current_chat + "default"])st.selectbox(label='选择上下文', options=set_context_list, key='context_select' + current_chat,index=context_select_index, on_change=write_data)st.caption(set_context_all[st.session_state['context_select' + current_chat]])st.text_area(label='补充或自定义上下文:', key="context_input" + current_chat,value=st.session_state['context_input' + current_chat + "default"],on_change=write_data)with tap_set:1 unmodified linest.session_state['history' + current_chat] = copy.deepcopy(initial_content_history)write_data()st.button("清空聊天记录", use_container_width=True, on_click=clear_button_callback)st.markdown("OpenAI API Key (���选)")st.text_input("OpenAI API Key (可选)", type='password', key='apikey_input', label_visibility='collapsed')st.caption("此Key仅在当前网页有效,且优先级高于Secrets中的配置,仅自己可用,他人无法共享。[官网获取](https://platform.openai.com/account/api-keys)")st.markdown("包含对话次数:")st.slider("Context Level", 0, 10, st.session_state['context_level' + current_chat + "default"], 1, on_change=write_data,key='context_level' + current_chat, help="表示每次会话中包含的历史对话次数,预设内容不计算在内。")st.markdown("模型参数:")st.slider("Temperature", 0.0, 2.0, st.session_state["temperature" + current_chat + "default"], 0.1,help="""在0和2之间,应该使用什么样的采样温度?较高的值(如0.8)会使输出更随机,而较低的值(如0.2)则会使其更加集中和确定性。我们一般建议只更改这个参数或top_p参数中的一个,而不要同时更改两个。""",on_change=write_data, key='temperature' + current_chat)st.slider("Top P", 0.1, 1.0, st.session_state["top_p" + current_chat + "default"], 0.1,help="""一种替代采用温度进行采样的方法,称为“基于核心概率”的采样。在该方法中,模型会考虑概率最高的top_p个标记的预测结果。因此,当该参数为0.1时,只有包括前10%概率质量的标记将被考虑。我们一般建议只更改这个参数或采样温度参数中的一个,而不要同时更改两个。""",on_change=write_data, key='top_p' + current_chat)st.slider("Presence Penalty", -2.0, 2.0,st.session_state["presence_penalty" + current_chat + "default"], 0.1,help="""该参数的取值范围为-2.0到2.0。正值会根据新标记是否出现在当前生成的文本中对其进行惩罚,从而增加模型谈论新话题的可能性。""",on_change=write_data, key='presence_penalty' + current_chat)st.slider("Frequency Penalty", -2.0, 2.0,st.session_state["frequency_penalty" + current_chat + "default"], 0.1,help="""该参数的取值范围为-2.0到2.0。正值会根据新标记在当前生成的文本中的已有频率对其进行惩罚,从而减少模型直接重复相同语句的可能性。""",on_change=write_data, key='frequency_penalty' + current_chat)st.caption("[官网参数说明](https://platform.openai.com/docs/api-reference/completions/create)")8 unmodified linesreturn resdef remove_hashtag_space(text):res = re.sub(r"(#+)\s*", r"\1", text)return resdef extract_chars(text, num):char_num = 0chars = ''11 unmodified linesdef user_input_area_callback():# 清空输入框st.session_state['user_input_content'] = (remove_hashtag_space(st.session_state['user_input_area']).replace('\n', '\n\n'))st.session_state['user_input_area'] = ''# 修改窗口名称user_input_content = st.session_state['user_input_content']df_history = pd.DataFrame(st.session_state["history" + current_chat])if len(df_history.query('role!="system"')) == 0:remove_data(st.session_state["path"], current_chat)current_chat_index = st.session_state['history_chats'].index(current_chat)new_name = extract_chars(user_input_content, 18) + '_' + str(uuid.uuid4())st.session_state['history_chats'][current_chat_index] = new_name2 unmodified lineswrite_data(new_name)st.text_area("**输入:**", key="user_input_area", on_change=user_input_area_callback)if st.session_state['user_input_content'].strip() != '':st.session_state['pre_user_input_content'] = st.session_state['user_input_content']st.session_state['user_input_content'] = ''show_each_message(st.session_state['pre_user_input_content'], 'user',[area_user_svg.markdown, area_user_content.markdown])context_level_tem = st.session_state['context_level' + current_chat]history_tem = get_history_input(st.session_state["history" + current_chat], context_level_tem) + \[{"role": "user", "content": st.session_state['pre_user_input_content']}]history_need_input = ([{"role": "system","content": set_context_all[st.session_state['context_select' + current_chat]]}]+ [{"role": "system","content": st.session_state['context_input' + current_chat]}]+ history_tem)paras_need_input = {"temperature": st.session_state["temperature" + current_chat],"top_p": st.session_state["top_p" + current_chat],2 unmodified lines}with st.spinner("🤔"):try:if apikey := st.session_state['apikey_input']:openai.api_key = apikeyelse:openai.api_key = st.secrets["apikey"]r = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=history_need_input, stream=True,**paras_need_input)except (FileNotFoundError, KeyError):area_error.error("缺失 OpenAI API Key,请在复制项目后配置Secrets,或者在设置中进行临时配置。""详情见[项目仓库](https://github.com/PierXuY/ChatGPT-Assistant)。")except openai.error.AuthenticationError:area_error.error("无效的 OpenAI API Key。")except openai.error.APIConnectionError as e:35 unmodified linesif current_chat + 'report' in st.session_state:st.session_state.pop(current_chat + 'report')if 'r' in st.session_state:st.session_state.pop("r")
app.py+49-33