Pearx commited on
Commit
55fdf91
1 Parent(s): c3fea1d

first commit

Browse files
Files changed (4) hide show
  1. app.py +310 -0
  2. helper.py +95 -0
  3. requirements.txt +4 -0
  4. set_context.py +64 -0
app.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from helper import *
2
+ import streamlit as st
3
+ import uuid
4
+ import copy
5
+ import pandas as pd
6
+ import openai
7
+ from requests.models import ChunkedEncodingError
8
+
9
+ st.set_page_config(page_title='ChatGPT Assistant', layout='wide')
10
+ # 自定义元素样式
11
+ # 第一个是减少侧边栏顶部空白,不同版本的st存在区别(此处适用1.19.0)
12
+ st.markdown("""
13
+ <style>
14
+ div.css-1vq4p4l.e1fqkh3o4 {
15
+ padding-top: 3.5rem !important;
16
+ }
17
+ .avatar {
18
+ display: flex;
19
+ align-items: center;
20
+ gap: 10px;
21
+ pointer-events: none;
22
+ margin:10px;
23
+ }
24
+ .avatar svg {
25
+ width: 30px;
26
+ height: 30px;
27
+ }
28
+ .avatar h2 {
29
+ font-size: 20px;
30
+ margin: 0px;
31
+ }
32
+
33
+ .content-div {
34
+ padding: 5px 20px;
35
+ margin: 5px;
36
+ text-align: left;
37
+ border-radius: 10px;
38
+ border: none;
39
+ line-height: 1.6;
40
+ font-size:17px;
41
+ }
42
+ .content-div p{
43
+ padding: 4px;
44
+ margin : 2px;
45
+ }
46
+ #chat-window{
47
+ color: black;
48
+ padding: 10px 0px;
49
+ text-decoration: none;
50
+ font-size: 25px;
51
+ }
52
+ #chat-window:hover{
53
+ color: blue;
54
+ }
55
+ </style>
56
+ """, unsafe_allow_html=True)
57
+ if "initial_settings" not in st.session_state:
58
+ # 历史聊天窗口
59
+ st.session_state['history_chats'] = get_history_chats()
60
+ # ss参数初始化
61
+ st.session_state['pre_chat'] = None
62
+ st.session_state['if_chat_change'] = False
63
+ st.session_state['error_info'] = ''
64
+ st.session_state['user_input_content'] = ''
65
+ st.session_state["current_chat_index"] = 0
66
+ # 设置完成
67
+ st.session_state["initial_settings"] = True
68
+
69
+ with st.sidebar:
70
+ # 此处href与下文的st.header内容相对应,跳转锚点
71
+ st.markdown("<a href='#chatgpt-assistant' id='chat-window'>🤖 聊天窗口</a>", unsafe_allow_html=True)
72
+ current_chat = st.radio(
73
+ label='历史聊天窗口',
74
+ format_func=lambda x: x.split('_')[0] if '_' in x else x,
75
+ options=st.session_state['history_chats'],
76
+ label_visibility='collapsed',
77
+ index=st.session_state["current_chat_index"],
78
+ key='current_chat' + st.session_state['history_chats'][st.session_state["current_chat_index"]],
79
+ # on_change=current_chat_callback # 此处不适合用回调,无法识别到窗口增减的变动
80
+ )
81
+ if st.session_state['pre_chat'] != current_chat:
82
+ st.session_state['pre_chat'] = current_chat
83
+ st.session_state['if_chat_change'] = True
84
+ st.write("---")
85
+
86
+
87
+ def create_chat_button_callback():
88
+ st.session_state['history_chats'] = ['New Chat_' + str(uuid.uuid4())] + st.session_state['history_chats']
89
+ st.session_state["current_chat_index"] = 0
90
+
91
+
92
+ def delete_chat_button_callback():
93
+ if len(st.session_state['history_chats']) == 1:
94
+ chat_init = 'New Chat_' + str(uuid.uuid4())
95
+ st.session_state['history_chats'].append(chat_init)
96
+ st.session_state['current_chat'] = chat_init
97
+ pre_chat_index = st.session_state['history_chats'].index(current_chat)
98
+ if pre_chat_index > 0:
99
+ st.session_state["current_chat_index"] = st.session_state['history_chats'].index(current_chat) - 1
100
+ else:
101
+ st.session_state["current_chat_index"] = 0
102
+ st.session_state['history_chats'].remove(current_chat)
103
+ remove_data(current_chat)
104
+
105
+
106
+ c1, c2 = st.columns(2)
107
+ create_chat_button = c1.button('新建', use_container_width=True, key='create_chat_button',
108
+ on_click=create_chat_button_callback)
109
+ delete_chat_button = c2.button('删除', use_container_width=True, key='delete_chat_button',
110
+ on_click=delete_chat_button_callback)
111
+
112
+ # 加载数据
113
+ if ("history" + current_chat not in st.session_state) or (st.session_state['if_chat_change']):
114
+ for key, value in load_data(current_chat).items():
115
+ if key == 'history':
116
+ st.session_state[key + current_chat] = value
117
+ else:
118
+ for k, v in value.items():
119
+ st.session_state[k + current_chat] = v
120
+ st.session_state['if_chat_change'] = False
121
+
122
+ # 对话展示
123
+ show_messages(st.session_state["history" + current_chat])
124
+
125
+
126
+ # 数据写入文件
127
+ def write_data(new_chat_name=current_chat):
128
+ st.session_state["paras"] = {
129
+ "temperature": st.session_state["temperature" + current_chat],
130
+ "top_p": st.session_state["top_p" + current_chat],
131
+ "presence_penalty": st.session_state["presence_penalty" + current_chat],
132
+ "frequency_penalty": st.session_state["frequency_penalty" + current_chat],
133
+ }
134
+ st.session_state["contexts"] = {
135
+ "context_select": st.session_state["context_select" + current_chat],
136
+ "context_input": st.session_state["context_input" + current_chat],
137
+ "context_level": st.session_state["context_level" + current_chat],
138
+ }
139
+ save_data(new_chat_name, st.session_state["history" + current_chat], st.session_state["paras"],
140
+ st.session_state["contexts"])
141
+
142
+
143
+ # 输入内容展示
144
+ area_user_svg = st.empty()
145
+ area_user_content = st.empty()
146
+ # 回复展示
147
+ area_gpt_svg = st.empty()
148
+ area_gpt_content = st.empty()
149
+ # 报错展示
150
+ area_error = st.empty()
151
+
152
+ st.write("\n")
153
+ st.header('ChatGPT Assistant')
154
+ tap_input, tap_context, tap_set = st.tabs(['💬 聊天', '🗒️ 预设', '⚙️ 设置'])
155
+
156
+ with tap_context:
157
+ set_context_list = list(set_context_all.keys())
158
+ context_select_index = set_context_list.index(st.session_state['context_select' + current_chat])
159
+ st.selectbox(label='选择上下文', options=set_context_list, key='context_select' + current_chat,
160
+ index=context_select_index, on_change=write_data)
161
+ st.caption(set_context_all[st.session_state['context_select' + current_chat]])
162
+ st.text_area(label='补充或自定义上下文:', key="context_input" + current_chat,
163
+ value=st.session_state['context_input' + current_chat],
164
+ on_change=write_data)
165
+
166
+ with tap_set:
167
+ def clear_button_callback():
168
+ st.session_state['history' + current_chat] = copy.deepcopy(initial_content_history)
169
+ write_data()
170
+
171
+
172
+ st.button("清空聊天记录", use_container_width=True, on_click=clear_button_callback)
173
+
174
+ st.caption("包含上下文次数:")
175
+ st.slider("Context Level", 1, 10, st.session_state['context_level' + current_chat], 1, on_change=write_data,
176
+ key='context_level' + current_chat, help="表示包含在每次会话中的历史对话次数,预设内容不计算在内。")
177
+
178
+ st.caption("模型参数:")
179
+ st.slider("Temperature", 0.0, 2.0, st.session_state["temperature" + current_chat], 0.1,
180
+ help="""在0和2之间,应该使用什么样的采样温度?较高的值(如0.8)会使输出更随机,而较低的值(如0.2)则会使其更加集中和确定性。
181
+ 我们一般建议只更改这个参数或top_p参数中的一个,而不要同时更改两个。""",
182
+ on_change=write_data, key='temperature' + current_chat)
183
+ st.slider("Top P", 0.1, 1.0, st.session_state["top_p" + current_chat], 0.1,
184
+ help="""一种替代采用温度进行采样的方法,称为“基于核心概率”的采样。在该方法中,模型会考虑概率最高的top_p个标记的预测结果。
185
+ 因此,当该参数为0.1时,只有包括前10%概率质量的标记将被考虑。我们一般建议只更改这个参数或采样温度参数中的一个,而不要同时更改两个。""",
186
+ on_change=write_data, key='top_p' + current_chat)
187
+ st.slider("Presence Penalty", -2.0, 2.0,
188
+ st.session_state["presence_penalty" + current_chat], 0.1,
189
+ help="""该参数的取值范围为-2.0到2.0。正值会根据新标记是否出现在当前生成的文本中对其进行惩罚,从而增加模型谈论新话题的可能性。""",
190
+ on_change=write_data, key='presence_penalty' + current_chat)
191
+ st.slider("Frequency Penalty", -2.0, 2.0,
192
+ st.session_state["frequency_penalty" + current_chat], 0.1,
193
+ help="""该参数的取值范围为-2.0到2.0。正值会根据新标记在当前生成的文本中的已有频率对其进行惩罚,从而减少模型直接重复相同语句的可能性。""",
194
+ on_change=write_data, key='frequency_penalty' + current_chat)
195
+ st.caption("[官网参数说明](https://platform.openai.com/docs/api-reference/completions/create)")
196
+
197
+ with tap_input:
198
+ def get_history_input(history, level):
199
+ df_history = pd.DataFrame(history)
200
+ df_system = df_history.query('role=="system"')
201
+ df_input = df_history.query('role!="system"')
202
+ df_input = df_input[-level * 2:]
203
+ res = pd.concat([df_system, df_input], ignore_index=True).to_dict('records')
204
+ return res
205
+
206
+
207
+ def extract_chars(text, num):
208
+ char_num = 0
209
+ chars = ''
210
+ for char in text:
211
+ # 汉字算两个字符
212
+ if '\u4e00' <= char <= '\u9fff':
213
+ char_num += 2
214
+ else:
215
+ char_num += 1
216
+ chars += char
217
+ if char_num >= num:
218
+ break
219
+ return chars
220
+
221
+
222
+ def user_input_area_callback():
223
+ # 清空输入框
224
+ st.session_state['user_input_content'] = st.session_state['user_input_area']
225
+ st.session_state['user_input_area'] = ''
226
+
227
+ # 修改窗口名称
228
+ user_input_content = st.session_state['user_input_content']
229
+ df_history = pd.DataFrame(st.session_state["history" + current_chat])
230
+ if len(df_history.query('role!="system"')) == 0:
231
+ remove_data(current_chat)
232
+ current_chat_index = st.session_state['history_chats'].index(current_chat)
233
+ new_name = extract_chars(user_input_content, 18) + '_' + str(uuid.uuid4())
234
+ st.session_state['history_chats'][current_chat_index] = new_name
235
+ st.session_state["current_chat_index"] = current_chat_index
236
+ # 写入新文件
237
+ write_data(new_name)
238
+
239
+
240
+ st.text_area("**输入:**", key="user_input_area", on_change=user_input_area_callback,
241
+ help="点击侧边栏标题可直接跳转此输入区 \n"
242
+ "此功能目前在Hugging Face不可用")
243
+ if st.session_state['user_input_content'].strip() != '':
244
+ st.session_state['pre_user_input_content'] = st.session_state['user_input_content']
245
+ st.session_state['user_input_content'] = ''
246
+ show_each_message(st.session_state['pre_user_input_content'], 'user',
247
+ [area_user_svg.markdown, area_user_content.markdown])
248
+ history_tem = st.session_state["history" + current_chat] + \
249
+ [{"role": "user", "content": st.session_state['pre_user_input_content'].replace('\n', '\n\n')}]
250
+ context_level_tem = st.session_state['context_level' + current_chat]
251
+ history_need_input = ([{"role": "system",
252
+ "content": set_context_all[st.session_state['context_select' + current_chat]]}]
253
+ + [{"role": "system",
254
+ "content": st.session_state['context_input' + current_chat]}]
255
+ + get_history_input(history_tem, context_level_tem))
256
+ paras_need_input = {
257
+ "temperature": st.session_state["temperature" + current_chat],
258
+ "top_p": st.session_state["top_p" + current_chat],
259
+ "presence_penalty": st.session_state["presence_penalty" + current_chat],
260
+ "frequency_penalty": st.session_state["frequency_penalty" + current_chat],
261
+ }
262
+ with st.spinner("🤔"):
263
+ try:
264
+ openai.api_key = st.secrets["apikey"]
265
+ r = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=history_need_input, stream=True,
266
+ **paras_need_input)
267
+ except (FileNotFoundError, KeyError):
268
+ area_error.error("缺失 OpenAI API Key,请在st.secrets中完成配置。")
269
+ except openai.error.AuthenticationError:
270
+ area_error.error("无效的 OpenAI API Key。")
271
+ except openai.error.APIConnectionError as e:
272
+ area_error.error("连接超时,请重试。报错: \n" + str(e.args[0]))
273
+ except openai.error.InvalidRequestError as e:
274
+ area_error.error("无效的请求,请重试。报错: \n" + str(e.args[0]))
275
+ except openai.error.RateLimitError as e:
276
+ area_error.error("请求速率过快,请重试。报错: \n" + str(e.args[0]))
277
+ else:
278
+ st.session_state["chat_of_r"] = current_chat
279
+ st.session_state["r"] = r
280
+ st.experimental_rerun()
281
+
282
+ if ("r" in st.session_state) and (current_chat == st.session_state["chat_of_r"]):
283
+ if current_chat + 'report' not in st.session_state:
284
+ st.session_state[current_chat + 'report'] = ""
285
+ try:
286
+ for e in st.session_state["r"]:
287
+ if "content" in e["choices"][0]["delta"]:
288
+ st.session_state[current_chat + 'report'] += e["choices"][0]["delta"]["content"]
289
+ show_each_message(st.session_state['pre_user_input_content'], 'user',
290
+ [area_user_svg.markdown, area_user_content.markdown])
291
+ show_each_message(st.session_state[current_chat + 'report'], 'assistant',
292
+ [area_gpt_svg.markdown, area_gpt_content.markdown])
293
+ except ChunkedEncodingError:
294
+ area_error.error("网络状况不佳,请刷新页面重试。")
295
+ # 应对stop情形
296
+ except Exception:
297
+ pass
298
+ else:
299
+ # 保存内容
300
+ st.session_state["history" + current_chat].append(
301
+ {"role": "user", "content": st.session_state['pre_user_input_content']})
302
+ st.session_state["history" + current_chat].append(
303
+ {"role": "assistant", "content": st.session_state[current_chat + 'report']})
304
+ write_data()
305
+
306
+ # 用户在网页点击stop时,ss某些情形下会暂时为空
307
+ if current_chat + 'report' in st.session_state:
308
+ st.session_state.pop(current_chat + 'report')
309
+ if 'r' in st.session_state:
310
+ st.session_state.pop("r")
helper.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import streamlit as st
3
+ import os
4
+ from set_context import set_context
5
+ import uuid
6
+
7
+ set_context_all = {"不设置": ""}
8
+ set_context_all.update(set_context)
9
+
10
+ # 用户名
11
+ user_name = 'User'
12
+ gpt_name = 'ChatGPT'
13
+ # 头像(svg格式) 来自 https://www.dicebear.com/playground?style=identicon
14
+ user_svg = """
15
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 5 5" fill="none" shape-rendering="crispEdges" width="512" height="512"><desc>"Identicon" by "Florian Körner", licensed under "CC0 1.0". / Remix of the original. - Created with dicebear.com</desc><metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:RDF><cc:Work><dc:title>Identicon</dc:title><dc:creator><cc:Agent rdf:about="https://dicebear.com"><dc:title>Florian Körner</dc:title></cc:Agent></dc:creator><dc:source>https://dicebear.com</dc:source><cc:license rdf:resource="https://creativecommons.org/publicdomain/zero/1.0/" /></cc:Work></rdf:RDF></metadata><mask id="viewboxMask"><rect width="5" height="5" rx="0" ry="0" x="0" y="0" fill="#fff" /></mask><g mask="url(#viewboxMask)"><path d="M0 0h1v1H0V0ZM4 0h1v1H4V0ZM3 0H2v1h1V0Z" fill="#00acc1"/><path fill="#00acc1" d="M2 1h1v1H2z"/><path fill="#00acc1" d="M1 2h3v1H1z"/><path fill="#00acc1" d="M2 3h1v1H2z"/><path d="M2 4H1v1h1V4ZM4 4H3v1h1V4Z" fill="#00acc1"/></g></svg>
16
+ """
17
+ gpt_svg = """
18
+ <svg width="41" height="41" viewBox="0 0 41 41" fill="none" xmlns="http://www.w3.org/2000/svg" stroke-width="1.5" class="h-6 w-6"><path d="M37.5324 16.8707C37.9808 15.5241 38.1363 14.0974 37.9886 12.6859C37.8409 11.2744 37.3934 9.91076 36.676 8.68622C35.6126 6.83404 33.9882 5.3676 32.0373 4.4985C30.0864 3.62941 27.9098 3.40259 25.8215 3.85078C24.8796 2.7893 23.7219 1.94125 22.4257 1.36341C21.1295 0.785575 19.7249 0.491269 18.3058 0.500197C16.1708 0.495044 14.0893 1.16803 12.3614 2.42214C10.6335 3.67624 9.34853 5.44666 8.6917 7.47815C7.30085 7.76286 5.98686 8.3414 4.8377 9.17505C3.68854 10.0087 2.73073 11.0782 2.02839 12.312C0.956464 14.1591 0.498905 16.2988 0.721698 18.4228C0.944492 20.5467 1.83612 22.5449 3.268 24.1293C2.81966 25.4759 2.66413 26.9026 2.81182 28.3141C2.95951 29.7256 3.40701 31.0892 4.12437 32.3138C5.18791 34.1659 6.8123 35.6322 8.76321 36.5013C10.7141 37.3704 12.8907 37.5973 14.9789 37.1492C15.9208 38.2107 17.0786 39.0587 18.3747 39.6366C19.6709 40.2144 21.0755 40.5087 22.4946 40.4998C24.6307 40.5054 26.7133 39.8321 28.4418 38.5772C30.1704 37.3223 31.4556 35.5506 32.1119 33.5179C33.5027 33.2332 34.8167 32.6547 35.9659 31.821C37.115 30.9874 38.0728 29.9178 38.7752 28.684C39.8458 26.8371 40.3023 24.6979 40.0789 22.5748C39.8556 20.4517 38.9639 18.4544 37.5324 16.8707ZM22.4978 37.8849C20.7443 37.8874 19.0459 37.2733 17.6994 36.1501C17.7601 36.117 17.8666 36.0586 17.936 36.0161L25.9004 31.4156C26.1003 31.3019 26.2663 31.137 26.3813 30.9378C26.4964 30.7386 26.5563 30.5124 26.5549 30.2825V19.0542L29.9213 20.998C29.9389 21.0068 29.9541 21.0198 29.9656 21.0359C29.977 21.052 29.9842 21.0707 29.9867 21.0902V30.3889C29.9842 32.375 29.1946 34.2791 27.7909 35.6841C26.3872 37.0892 24.4838 37.8806 22.4978 37.8849ZM6.39227 31.0064C5.51397 29.4888 5.19742 27.7107 5.49804 25.9832C5.55718 26.0187 5.66048 26.0818 5.73461 26.1244L13.699 30.7248C13.8975 30.8408 14.1233 30.902 14.3532 30.902C14.583 30.902 14.8088 30.8408 15.0073 30.7248L24.731 25.1103V28.9979C24.7321 29.0177 24.7283 29.0376 24.7199 29.0556C24.7115 29.0736 24.6988 29.0893 24.6829 29.1012L16.6317 33.7497C14.9096 34.7416 12.8643 35.0097 10.9447 34.4954C9.02506 33.9811 7.38785 32.7263 6.39227 31.0064ZM4.29707 13.6194C5.17156 12.0998 6.55279 10.9364 8.19885 10.3327C8.19885 10.4013 8.19491 10.5228 8.19491 10.6071V19.808C8.19351 20.0378 8.25334 20.2638 8.36823 20.4629C8.48312 20.6619 8.64893 20.8267 8.84863 20.9404L18.5723 26.5542L15.206 28.4979C15.1894 28.5089 15.1703 28.5155 15.1505 28.5173C15.1307 28.5191 15.1107 28.516 15.0924 28.5082L7.04046 23.8557C5.32135 22.8601 4.06716 21.2235 3.55289 19.3046C3.03862 17.3858 3.30624 15.3413 4.29707 13.6194ZM31.955 20.0556L22.2312 14.4411L25.5976 12.4981C25.6142 12.4872 25.6333 12.4805 25.6531 12.4787C25.6729 12.4769 25.6928 12.4801 25.7111 12.4879L33.7631 17.1364C34.9967 17.849 36.0017 18.8982 36.6606 20.1613C37.3194 21.4244 37.6047 22.849 37.4832 24.2684C37.3617 25.6878 36.8382 27.0432 35.9743 28.1759C35.1103 29.3086 33.9415 30.1717 32.6047 30.6641C32.6047 30.5947 32.6047 30.4733 32.6047 30.3889V21.188C32.6066 20.9586 32.5474 20.7328 32.4332 20.5338C32.319 20.3348 32.154 20.1698 31.955 20.0556ZM35.3055 15.0128C35.2464 14.9765 35.1431 14.9142 35.069 14.8717L27.1045 10.2712C26.906 10.1554 26.6803 10.0943 26.4504 10.0943C26.2206 10.0943 25.9948 10.1554 25.7963 10.2712L16.0726 15.8858V11.9982C16.0715 11.9783 16.0753 11.9585 16.0837 11.9405C16.0921 11.9225 16.1048 11.9068 16.1207 11.8949L24.1719 7.25025C25.4053 6.53903 26.8158 6.19376 28.2383 6.25482C29.6608 6.31589 31.0364 6.78077 32.2044 7.59508C33.3723 8.40939 34.2842 9.53945 34.8334 10.8531C35.3826 12.1667 35.5464 13.6095 35.3055 15.0128ZM14.2424 21.9419L10.8752 19.9981C10.8576 19.9893 10.8423 19.9763 10.8309 19.9602C10.8195 19.9441 10.8122 19.9254 10.8098 19.9058V10.6071C10.8107 9.18295 11.2173 7.78848 11.9819 6.58696C12.7466 5.38544 13.8377 4.42659 15.1275 3.82264C16.4173 3.21869 17.8524 2.99464 19.2649 3.1767C20.6775 3.35876 22.0089 3.93941 23.1034 4.85067C23.0427 4.88379 22.937 4.94215 22.8668 4.98473L14.9024 9.58517C14.7025 9.69878 14.5366 9.86356 14.4215 10.0626C14.3065 10.2616 14.2466 10.4877 14.2479 10.7175L14.2424 21.9419ZM16.071 17.9991L20.4018 15.4978L24.7325 17.9975V22.9985L20.4018 25.4983L16.071 22.9985V17.9991Z" fill="currentColor"></path></svg>
19
+ """
20
+ # 聊天记录文件夹名称
21
+ history_chats_filename = 'chat_history'
22
+
23
+ initial_content_history = [{"role": 'system',
24
+ "content": '当你的回复中涉及代码块时,请在markdown语法中标明语言类型。如果不涉及,请忽略这句话。'}]
25
+ initial_content_all = {"history": initial_content_history,
26
+ "paras": {
27
+ "temperature": 1.0,
28
+ "top_p": 1.0,
29
+ "presence_penalty": 0.0,
30
+ "frequency_penalty": 0.0,
31
+ },
32
+ "contexts": {
33
+ 'context_select': '不设置',
34
+ 'context_input': '',
35
+ 'context_level': 5
36
+ }
37
+ }
38
+
39
+
40
+ def get_history_chats(file_name=history_chats_filename):
41
+ try:
42
+ os.mkdir(file_name)
43
+ except FileExistsError:
44
+ pass
45
+ files = [f for f in os.listdir(f'./{file_name}') if f.endswith('.json')]
46
+ files_with_time = [(f, os.stat(f'./{file_name}/' + f).st_ctime) for f in files]
47
+ sorted_files = sorted(files_with_time, key=lambda x: x[1], reverse=True)
48
+ chat_names = [os.path.splitext(f[0])[0] for f in sorted_files]
49
+ if len(chat_names) == 0:
50
+ chat_names.append('New Chat_' + str(uuid.uuid4()))
51
+ return chat_names
52
+
53
+
54
+ def save_data(current_chat: str, history: list, paras: dict, contexts: dict, **kwargs):
55
+ with open(f"./{history_chats_filename}/{current_chat}.json", 'w', encoding='utf-8') as f:
56
+ json.dump({"history": history, "paras": paras, "contexts": contexts, **kwargs}, f)
57
+
58
+
59
+ def remove_data(current_chat: str):
60
+ os.remove(f"./{history_chats_filename}/{current_chat}.json")
61
+
62
+
63
+ def load_data(current_chat: str) -> dict:
64
+ try:
65
+ with open(f"./{history_chats_filename}/{current_chat}.json", 'r', encoding='utf-8') as f:
66
+ data = json.load(f)
67
+ return data
68
+ except FileNotFoundError:
69
+ with open(f"./{history_chats_filename}/{current_chat}.json", 'w', encoding='utf-8') as f:
70
+ f.write(json.dumps(initial_content_all))
71
+ return initial_content_all
72
+
73
+
74
+ def show_each_message(message, role, area=None):
75
+ if area is None:
76
+ area = [st.markdown] * 2
77
+ if role == 'user':
78
+ icon = user_svg
79
+ name = user_name
80
+ background_color = '#ffffff'
81
+ else:
82
+ icon = gpt_svg
83
+ name = gpt_name
84
+ background_color = '#f0f2f6'
85
+ area[0](f"\n<div class='avatar'>{icon}<h2>{name}:</h2></div>", unsafe_allow_html=True)
86
+ area[1](f"""<div class='content-div' style='background-color: {background_color};'>\n\n{message}""",
87
+ unsafe_allow_html=True)
88
+
89
+
90
+ def show_messages(messages: list):
91
+ for each in messages:
92
+ if (each["role"] == "user") or (each["role"] == "assistant"):
93
+ show_each_message(each["content"], each["role"])
94
+ if each["role"] == "assistant":
95
+ st.write("---")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ openai==0.27.0
2
+ streamlit==1.19.0
3
+ pandas==1.5.3
4
+ requests==2.28.2
set_context.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set_context = {
2
+ "英语学术润色":
3
+ "Below is a paragraph from an academic paper. Polish the writing to meet the academic style, improve the "
4
+ "spelling, grammar, clarity, concision and overall readability."
5
+ "When necessary, rewrite the whole sentence. Furthermore, list all modification and explain the reasons to do "
6
+ "so in markdown table.",
7
+
8
+ '中文学术润色':
9
+ "在这次会话中,你将作为一名中文学术论文写作改进助理。你的任务是改进所提供文本的拼写、语法、清晰、简洁和整体可读性。"
10
+ "同时分解长句,减少重复,并提供改进建议。请只提供文本的更正版本,避免包括解释。",
11
+
12
+ '查找语法错误':
13
+ r"Can you help me ensure that the grammar and the spelling is correct? " +
14
+ r"Do not try to polish the text, if no mistake is found, tell me that this paragraph is good." +
15
+ r"If you find grammar or spelling mistakes, please list mistakes you find in a two-column markdown table, " +
16
+ r"put the original text the first column, " +
17
+ r"put the corrected text in the second column and highlight the key words you fixed.""\n"
18
+ r"Example:""\n"
19
+ r"Paragraph: How is you? Do you knows what is it?""\n"
20
+ r"| Original sentence | Corrected sentence |""\n"
21
+ r"| :--- | :--- |""\n"
22
+ r"| How **is** you? | How **are** you? |""\n"
23
+ r"| Do you **knows** what **is** **it**? | Do you **know** what **it** **is** ? |""\n"
24
+ r"Below is a paragraph from an academic paper. "
25
+ r"You need to report all grammar and spelling mistakes as the example before.",
26
+
27
+ '学术中英互译':
28
+ "I want you to act as a scientific English-Chinese translator, I will provide you with some paragraphs in one "
29
+ "language and your task is to accurately and academically translate the paragraphs only into the other "
30
+ "language."
31
+ "Do not repeat the original provided paragraphs after translation. You should use artificial intelligence "
32
+ "tools, such as natural language processing, and rhetorical knowledge and experience about effective writing "
33
+ "techniques to reply."
34
+ "I'll give you my paragraphs as follows, tell me what language it is written in, and then translate.",
35
+
36
+ '英语口语老师':
37
+ "I want you to act as a spoken English teacher and improver. I will speak to you in English and you will "
38
+ "reply to me in English to practice my spoken English. I want you to keep your reply neat, limiting the reply "
39
+ "to 100 words. I want you to strictly correct my grammar mistakes, typos, and factual errors. I want you to "
40
+ "ask me a question in your reply.Remember, I want you to strictly correct my grammar mistakes, typos, "
41
+ "and factual errors. Now let's start practicing.",
42
+
43
+ '英文翻译与改进':
44
+ "在这次会话中,我想让你充当英语翻译员、拼写纠正员和改进员。我会用任何语言与你交谈,你会检测语言,并在更正和改进我的句子后用英语回答。"
45
+ "我希望你用更优美优雅的高级英语单词和句子来替换我使用的简单单词和句子。保持相同的意思,但使它们更文艺。我要你只回复更正、改进,不要写任何解释。",
46
+
47
+ '寻找网络图片':
48
+ '我需要你找一张网络图片。使用Unsplash API(https://source.unsplash.com/960x640/?<英语关键词>)获取图片URL,'
49
+ '然后请使用Markdown格式封装,并且不要有反斜线,不要用代码块。'
50
+ '现在,请按以下描述给我发送图片:',
51
+
52
+ '数据检索助理':
53
+ "在此次聊天中,你将担任数据检索助理。接下来我会发送数据名称,你告诉我在哪里可以获取到相关数据,并说明如何获取,数据来源要尽量丰富。",
54
+
55
+ '充当Python解释器':
56
+ 'I want you to act like a Python interpreter. I will give you Python code, and you will execute it. Do not '
57
+ 'provide any explanations. Do not respond with anything except the output of the code.',
58
+
59
+ '正则表达式生成器':
60
+ "I want you to act as a regex generator. Your role is to generate regular expressions that match specific "
61
+ "patterns in text. You should provide the regular expressions in a format that can be easily copied and "
62
+ "pasted into a regex-enabled text editor or programming language. Do not write explanations or examples of "
63
+ "how the regular expressions work; simply provide only the regular expressions themselves.",
64
+ }