Files changed (1) hide show
  1. app.py +73 -25
app.py CHANGED
@@ -3,32 +3,45 @@ import gradio as gr
3
  import openai
4
  import os
5
  import sys
 
6
  # import markdown
7
 
8
- my_api_key = "" # 在这里输入你的 API 密钥
9
  initial_prompt = "You are a helpful assistant."
10
 
11
- if my_api_key == "":
12
- my_api_key = os.environ.get('my_api_key')
13
-
14
  if my_api_key == "empty":
15
  print("Please give a api key!")
16
  sys.exit(1)
17
 
 
 
 
 
 
 
 
 
18
  def parse_text(text):
19
  lines = text.split("\n")
 
20
  for i,line in enumerate(lines):
21
  if "```" in line:
 
22
  items = line.split('`')
23
- if items[-1]:
24
  lines[i] = f'<pre><code class="{items[-1]}">'
25
  else:
26
  lines[i] = f'</code></pre>'
27
  else:
28
- if i>0:
29
- line = line.replace("<", "&lt;")
30
- line = line.replace(">", "&gt;")
31
- lines[i] = '<br/>'+line.replace(" ", "&nbsp;")
 
 
 
 
 
32
  return "".join(lines)
33
 
34
  def get_response(system, context, myKey, raw = False):
@@ -56,9 +69,21 @@ def predict(chatbot, input_sentence, system, context, myKey):
56
 
57
  try:
58
  message, message_with_stats = get_response(system, context, myKey)
59
- except:
60
  chatbot.append((input_sentence, "请求失败,请检查API-key是否正确。"))
61
  return chatbot, context
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  context.append({"role": "assistant", "content": message})
64
 
@@ -69,11 +94,25 @@ def predict(chatbot, input_sentence, system, context, myKey):
69
  def retry(chatbot, system, context, myKey):
70
  if len(context) == 0:
71
  return [], []
 
72
  try:
73
  message, message_with_stats = get_response(system, context[:-1], myKey)
74
- except:
75
  chatbot.append(("重试请求", "请求失败,请检查API-key是否正确。"))
76
  return chatbot, context
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  context[-1] = {"role": "assistant", "content": message}
78
 
79
  chatbot[-1] = (context[-2]["content"], message_with_stats)
@@ -130,16 +169,24 @@ def update_system(new_system_prompt):
130
 
131
  def set_apikey(new_api_key, myKey):
132
  old_api_key = myKey
 
133
  try:
134
  get_response(update_system(initial_prompt), [{"role": "user", "content": "test"}], new_api_key)
135
- except:
136
  return "无效的api-key", myKey
 
 
 
 
 
 
 
137
  encryption_str = "验证成功,api-key已做遮挡处理:" + new_api_key[:4] + "..." + new_api_key[-4:]
138
  return encryption_str, new_api_key
139
 
140
 
141
  with gr.Blocks() as demo:
142
- keyTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入你的API-key...", value=my_api_key, label="API Key").style(container=True)
143
  chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
144
  context = gr.State([])
145
  systemPrompt = gr.State(update_system(initial_prompt))
@@ -158,14 +205,14 @@ with gr.Blocks() as demo:
158
  reduceTokenBtn = gr.Button("♻️ 优化Tokens")
159
  newSystemPrompt = gr.Textbox(show_label=True, placeholder=f"在这里输入新的System Prompt...", label="更改 System prompt").style(container=True)
160
  systemPromptDisplay = gr.Textbox(show_label=True, value=initial_prompt, interactive=False, label="目前的 System prompt").style(container=True)
161
- # with gr.Accordion(label="保存/加载对话历史记录(在文本框中输入文件名,点击“保存对话”按钮,历史记录文件会被存储到本地)", open=False):
162
- # with gr.Column():
163
- # with gr.Row():
164
- # with gr.Column(scale=6):
165
- # saveFileName = gr.Textbox(show_label=True, placeholder=f"在这里输入保存的文件名...", label="保存对话", value="对话历史记录").style(container=True)
166
- # with gr.Column(scale=1):
167
- # saveBtn = gr.Button("💾 保存对话")
168
- # uploadBtn = gr.UploadButton("📂 读取对话", file_count="single", file_types=["json"])
169
 
170
  txt.submit(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
171
  txt.submit(lambda :"", None, txt)
@@ -178,9 +225,10 @@ with gr.Blocks() as demo:
178
  retryBtn.click(retry, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
179
  delLastBtn.click(delete_last_conversation, [chatbot, context], [chatbot, context], show_progress=True)
180
  reduceTokenBtn.click(reduce_token, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
181
- keyTxt.submit(set_apikey, [keyTxt, myKey], [keyTxt, myKey], show_progress=True)
182
- # uploadBtn.upload(load_chat_history, uploadBtn, [chatbot, systemPrompt, context, systemPromptDisplay], show_progress=True)
183
- # saveBtn.click(save_chat_history, [saveFileName, systemPrompt, context], None, show_progress=True)
184
 
185
 
186
- demo.launch()
 
 
3
  import openai
4
  import os
5
  import sys
6
+ import traceback
7
  # import markdown
8
 
9
+ my_api_key = "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" # 在这里输入你的 API 密钥
10
  initial_prompt = "You are a helpful assistant."
11
 
 
 
 
12
  if my_api_key == "empty":
13
  print("Please give a api key!")
14
  sys.exit(1)
15
 
16
+ if my_api_key == "":
17
+ initial_keytxt = None
18
+ elif len(str(my_api_key)) == 51:
19
+ # initial_keytxt = "默认api-key(未验证):" + str(my_api_key[:4] + "..." + my_api_key[-4:])
20
+ initial_keytxt = "Zhou Yang Assistant !"
21
+ else:
22
+ initial_keytxt = "默认api-key无效,请重新输入"
23
+
24
  def parse_text(text):
25
  lines = text.split("\n")
26
+ count = 0
27
  for i,line in enumerate(lines):
28
  if "```" in line:
29
+ count += 1
30
  items = line.split('`')
31
+ if count % 2 == 1:
32
  lines[i] = f'<pre><code class="{items[-1]}">'
33
  else:
34
  lines[i] = f'</code></pre>'
35
  else:
36
+ if i > 0:
37
+ if count % 2 == 1:
38
+ line = line.replace("&", "&amp;")
39
+ line = line.replace("\"", "&quot;")
40
+ line = line.replace("\'", "&apos;")
41
+ line = line.replace("<", "&lt;")
42
+ line = line.replace(">", "&gt;")
43
+ line = line.replace(" ", "&nbsp;")
44
+ lines[i] = '<br/>'+line
45
  return "".join(lines)
46
 
47
  def get_response(system, context, myKey, raw = False):
 
69
 
70
  try:
71
  message, message_with_stats = get_response(system, context, myKey)
72
+ except openai.error.AuthenticationError:
73
  chatbot.append((input_sentence, "请求失败,请检查API-key是否正确。"))
74
  return chatbot, context
75
+ except openai.error.Timeout:
76
+ chatbot.append((input_sentence, "请求超时,请检查网络连接。"))
77
+ return chatbot, context
78
+ except openai.error.APIConnectionError:
79
+ chatbot.append((input_sentence, "连接失败,请检查网络连接。"))
80
+ return chatbot, context
81
+ except openai.error.RateLimitError:
82
+ chatbot.append((input_sentence, "请求过于频繁,请5s后再试。"))
83
+ return chatbot, context
84
+ except:
85
+ chatbot.append((input_sentence, "发生了未知错误Orz"))
86
+ return chatbot, context
87
 
88
  context.append({"role": "assistant", "content": message})
89
 
 
94
  def retry(chatbot, system, context, myKey):
95
  if len(context) == 0:
96
  return [], []
97
+
98
  try:
99
  message, message_with_stats = get_response(system, context[:-1], myKey)
100
+ except openai.error.AuthenticationError:
101
  chatbot.append(("重试请求", "请求失败,请检查API-key是否正确。"))
102
  return chatbot, context
103
+ except openai.error.Timeout:
104
+ chatbot.append(("重试请求", "请求超时,请检查网络连接。"))
105
+ return chatbot, context
106
+ except openai.error.APIConnectionError:
107
+ chatbot.append(("重试请求", "连接失败,请检查网络连接。"))
108
+ return chatbot, context
109
+ except openai.error.RateLimitError:
110
+ chatbot.append(("重试请求", "请求过于频繁,请5s后再试。"))
111
+ return chatbot, context
112
+ except:
113
+ chatbot.append(("重试请求", "发生了未知错误Orz"))
114
+ return chatbot, context
115
+
116
  context[-1] = {"role": "assistant", "content": message}
117
 
118
  chatbot[-1] = (context[-2]["content"], message_with_stats)
 
169
 
170
  def set_apikey(new_api_key, myKey):
171
  old_api_key = myKey
172
+
173
  try:
174
  get_response(update_system(initial_prompt), [{"role": "user", "content": "test"}], new_api_key)
175
+ except openai.error.AuthenticationError:
176
  return "无效的api-key", myKey
177
+ except openai.error.Timeout:
178
+ return "请求超时,请检查网络设置", myKey
179
+ except openai.error.APIConnectionError:
180
+ return "网络错误", myKey
181
+ except:
182
+ return "发生了未知错误Orz", myKey
183
+
184
  encryption_str = "验证成功,api-key已做遮挡处理:" + new_api_key[:4] + "..." + new_api_key[-4:]
185
  return encryption_str, new_api_key
186
 
187
 
188
  with gr.Blocks() as demo:
189
+ keyTxt = gr.Button(initial_keytxt)
190
  chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
191
  context = gr.State([])
192
  systemPrompt = gr.State(update_system(initial_prompt))
 
205
  reduceTokenBtn = gr.Button("♻️ 优化Tokens")
206
  newSystemPrompt = gr.Textbox(show_label=True, placeholder=f"在这里输入新的System Prompt...", label="更改 System prompt").style(container=True)
207
  systemPromptDisplay = gr.Textbox(show_label=True, value=initial_prompt, interactive=False, label="目前的 System prompt").style(container=True)
208
+ with gr.Accordion(label="保存/加载对话历史记录(在文本框中输入文件名,点击“保存对话”按钮,历史记录文件会被存储到本地)", open=False):
209
+ with gr.Column():
210
+ with gr.Row():
211
+ with gr.Column(scale=6):
212
+ saveFileName = gr.Textbox(show_label=True, placeholder=f"在这里输入保存的文件名...", label="保存对话", value="对话历史记录").style(container=True)
213
+ with gr.Column(scale=1):
214
+ saveBtn = gr.Button("💾 保存对话")
215
+ uploadBtn = gr.UploadButton("📂 读取对话", file_count="single", file_types=["json"])
216
 
217
  txt.submit(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
218
  txt.submit(lambda :"", None, txt)
 
225
  retryBtn.click(retry, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
226
  delLastBtn.click(delete_last_conversation, [chatbot, context], [chatbot, context], show_progress=True)
227
  reduceTokenBtn.click(reduce_token, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
228
+ # keyTxt.submit(set_apikey, [keyTxt, myKey], [keyTxt, myKey], show_progress=False)
229
+ uploadBtn.upload(load_chat_history, uploadBtn, [chatbot, systemPrompt, context, systemPromptDisplay], show_progress=True)
230
+ saveBtn.click(save_chat_history, [saveFileName, systemPrompt, context], None, show_progress=True)
231
 
232
 
233
+ # demo.launch(server_name="0.0.0.0", server_port=9000)
234
+ demo.launch()