Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,262 +1,331 @@
|
|
| 1 |
import json
|
| 2 |
import gradio as gr
|
| 3 |
-
|
| 4 |
import os
|
| 5 |
import sys
|
| 6 |
import traceback
|
| 7 |
-
|
| 8 |
# import markdown
|
| 9 |
|
| 10 |
-
my_api_key = "sk-
|
| 11 |
initial_prompt = "You are a helpful assistant."
|
| 12 |
|
| 13 |
-
API_URL = "https://api.openai.com/v1/chat/completions"
|
| 14 |
-
|
| 15 |
if my_api_key == "":
|
| 16 |
-
|
|
|
|
| 17 |
|
| 18 |
if my_api_key == "empty":
|
| 19 |
print("Please give a api key!")
|
| 20 |
sys.exit(1)
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def parse_text(text):
|
|
|
|
| 24 |
lines = text.split("\n")
|
| 25 |
-
count = 0
|
| 26 |
for i, line in enumerate(lines):
|
| 27 |
if "```" in line:
|
| 28 |
-
|
| 29 |
-
items = line.split(
|
| 30 |
-
|
|
|
|
| 31 |
lines[i] = f'<pre><code class="{items[-1]}">'
|
| 32 |
else:
|
| 33 |
-
lines[i] = f
|
| 34 |
else:
|
| 35 |
if i > 0:
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
line = line.replace("
|
| 41 |
-
line = line.replace("
|
| 42 |
-
line = line.replace("
|
| 43 |
-
|
| 44 |
return "".join(lines)
|
| 45 |
|
| 46 |
-
def predict(inputs, top_p, temperature, openai_api_key, chatbot=[], history=[], system_prompt=initial_prompt, retry=False, summary=False): # repetition_penalty, top_k
|
| 47 |
-
|
| 48 |
-
headers = {
|
| 49 |
-
"Content-Type": "application/json",
|
| 50 |
-
"Authorization": f"Bearer {openai_api_key}"
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
chat_counter = len(history) // 2
|
| 54 |
-
|
| 55 |
-
print(f"chat_counter - {chat_counter}")
|
| 56 |
-
|
| 57 |
-
messages = [compose_system(system_prompt)]
|
| 58 |
-
if chat_counter:
|
| 59 |
-
for data in chatbot:
|
| 60 |
-
temp1 = {}
|
| 61 |
-
temp1["role"] = "user"
|
| 62 |
-
temp1["content"] = data[0]
|
| 63 |
-
temp2 = {}
|
| 64 |
-
temp2["role"] = "assistant"
|
| 65 |
-
temp2["content"] = data[1]
|
| 66 |
-
if temp1["content"] != "":
|
| 67 |
-
messages.append(temp1)
|
| 68 |
-
messages.append(temp2)
|
| 69 |
-
else:
|
| 70 |
-
messages[-1]['content'] = temp2['content']
|
| 71 |
-
if retry and chat_counter:
|
| 72 |
-
messages.pop()
|
| 73 |
-
elif summary and chat_counter:
|
| 74 |
-
messages.append(compose_user(
|
| 75 |
-
"请帮我总结一下上述对话的内容,实现减少字数的同时,保证对话的质量。在总结中不要加入这一句话。"))
|
| 76 |
-
history = ["我们刚刚聊了什么?"]
|
| 77 |
-
else:
|
| 78 |
-
temp3 = {}
|
| 79 |
-
temp3["role"] = "user"
|
| 80 |
-
temp3["content"] = inputs
|
| 81 |
-
messages.append(temp3)
|
| 82 |
-
chat_counter += 1
|
| 83 |
-
# messages
|
| 84 |
-
payload = {
|
| 85 |
-
"model": "gpt-3.5-turbo",
|
| 86 |
-
"messages": messages, # [{"role": "user", "content": f"{inputs}"}],
|
| 87 |
-
"temperature": temperature, # 1.0,
|
| 88 |
-
"top_p": top_p, # 1.0,
|
| 89 |
-
"n": 1,
|
| 90 |
-
"stream": True,
|
| 91 |
-
"presence_penalty": 0,
|
| 92 |
-
"frequency_penalty": 0,
|
| 93 |
-
}
|
| 94 |
-
|
| 95 |
-
if not summary:
|
| 96 |
-
history.append(inputs)
|
| 97 |
-
print(f"payload is - {payload}")
|
| 98 |
-
# make a POST request to the API endpoint using the requests.post method, passing in stream=True
|
| 99 |
-
response = requests.post(API_URL, headers=headers,
|
| 100 |
-
json=payload, stream=True)
|
| 101 |
-
#response = requests.post(API_URL, headers=headers, json=payload, stream=True)
|
| 102 |
-
|
| 103 |
-
token_counter = 0
|
| 104 |
-
partial_words = ""
|
| 105 |
-
|
| 106 |
-
counter = 0
|
| 107 |
-
chatbot.append((history[-1], ""))
|
| 108 |
-
for chunk in response.iter_lines():
|
| 109 |
-
if counter == 0:
|
| 110 |
-
counter += 1
|
| 111 |
-
continue
|
| 112 |
-
counter += 1
|
| 113 |
-
# check whether each line is non-empty
|
| 114 |
-
if chunk:
|
| 115 |
-
# decode each line as response data is in bytes
|
| 116 |
-
try:
|
| 117 |
-
if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
|
| 118 |
-
break
|
| 119 |
-
except Exception as e:
|
| 120 |
-
chatbot.pop()
|
| 121 |
-
chatbot.append((history[-1], f"☹️发生了错误\n返回��:{response.text}\n异常:{e}"))
|
| 122 |
-
history.pop()
|
| 123 |
-
yield chatbot, history
|
| 124 |
-
break
|
| 125 |
-
#print(json.loads(chunk.decode()[6:])['choices'][0]["delta"] ["content"])
|
| 126 |
-
partial_words = partial_words + \
|
| 127 |
-
json.loads(chunk.decode()[6:])[
|
| 128 |
-
'choices'][0]["delta"]["content"]
|
| 129 |
-
if token_counter == 0:
|
| 130 |
-
history.append(" " + partial_words)
|
| 131 |
-
else:
|
| 132 |
-
history[-1] = parse_text(partial_words)
|
| 133 |
-
chatbot[-1] = (history[-2], history[-1])
|
| 134 |
-
# chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
|
| 135 |
-
token_counter += 1
|
| 136 |
-
# resembles {chatbot: chat, state: history}
|
| 137 |
-
yield chatbot, history
|
| 138 |
-
|
| 139 |
-
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
if filepath == "":
|
| 151 |
return
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
with open(filepath, "w") as f:
|
| 156 |
-
json.dump(json_s, f)
|
| 157 |
|
| 158 |
|
| 159 |
-
def load_chat_history(
|
| 160 |
-
with open(
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
-
def get_history_names(
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
return files
|
| 170 |
-
else:
|
| 171 |
-
return gr.Dropdown.update(choices=files)
|
| 172 |
|
| 173 |
|
| 174 |
def reset_state():
|
| 175 |
return [], []
|
| 176 |
|
| 177 |
|
| 178 |
-
def
|
| 179 |
-
return {"role": "system", "content":
|
|
|
|
| 180 |
|
|
|
|
|
|
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
def reset_textbox():
|
| 187 |
-
return gr.update(value='')
|
| 188 |
|
| 189 |
-
title = """<h1 align="center">ChatGPT 🚀</h1>"""
|
| 190 |
-
description = """<div align=center>
|
| 191 |
-
此App使用 `gpt-3.5-turbo` 大语言模型
|
| 192 |
-
</div>
|
| 193 |
-
"""
|
| 194 |
with gr.Blocks() as demo:
|
| 195 |
-
gr.
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
topic = gr.State("未命名对话历史记录")
|
| 203 |
|
| 204 |
with gr.Row():
|
| 205 |
with gr.Column(scale=12):
|
| 206 |
txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(
|
| 207 |
-
container=False
|
|
|
|
| 208 |
with gr.Column(min_width=50, scale=1):
|
| 209 |
submitBtn = gr.Button("🚀", variant="primary")
|
| 210 |
with gr.Row():
|
| 211 |
emptyBtn = gr.Button("🧹 新的对话")
|
| 212 |
retryBtn = gr.Button("🔄 重新生成")
|
| 213 |
delLastBtn = gr.Button("🗑️ 删除上条对话")
|
| 214 |
-
reduceTokenBtn = gr.Button("♻️
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
with gr.Column():
|
| 219 |
with gr.Row():
|
| 220 |
with gr.Column(scale=6):
|
| 221 |
saveFileName = gr.Textbox(
|
| 222 |
-
show_label=True,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
with gr.Column(scale=1):
|
| 224 |
saveBtn = gr.Button("💾 保存对话")
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
|
| 262 |
demo.title = "ChatGPT 🚀"
|
|
|
|
| 1 |
import json
|
| 2 |
import gradio as gr
|
| 3 |
+
import openai
|
| 4 |
import os
|
| 5 |
import sys
|
| 6 |
import traceback
|
| 7 |
+
|
| 8 |
# import markdown
|
| 9 |
|
| 10 |
+
my_api_key = "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" # 在这里输入你的 API 密钥
|
| 11 |
initial_prompt = "You are a helpful assistant."
|
| 12 |
|
|
|
|
|
|
|
| 13 |
if my_api_key == "":
|
| 14 |
+
initial_keytxt = None
|
| 15 |
+
my_api_key = os.environ.get("my_api_key")
|
| 16 |
|
| 17 |
if my_api_key == "empty":
|
| 18 |
print("Please give a api key!")
|
| 19 |
sys.exit(1)
|
| 20 |
|
| 21 |
+
elif len(str(my_api_key)) == 51:
|
| 22 |
+
initial_keytxt = "默认api-key(未验证):" + str(my_api_key[:4] + "..." + my_api_key[-4:])
|
| 23 |
+
else:
|
| 24 |
+
initial_keytxt = "默认api-key无效,请重新输入"
|
| 25 |
+
|
| 26 |
|
| 27 |
def parse_text(text):
|
| 28 |
+
in_code = False
|
| 29 |
lines = text.split("\n")
|
|
|
|
| 30 |
for i, line in enumerate(lines):
|
| 31 |
if "```" in line:
|
| 32 |
+
in_code = 1 - in_code
|
| 33 |
+
items = line.split("`")
|
| 34 |
+
print(items)
|
| 35 |
+
if in_code == True:
|
| 36 |
lines[i] = f'<pre><code class="{items[-1]}">'
|
| 37 |
else:
|
| 38 |
+
lines[i] = f"</code></pre>"
|
| 39 |
else:
|
| 40 |
if i > 0:
|
| 41 |
+
line = line.replace("<", "<")
|
| 42 |
+
line = line.replace(">", ">")
|
| 43 |
+
lines[i] = "<br/>" + line.replace(" ", " ")
|
| 44 |
+
if in_code:
|
| 45 |
+
line = line.replace(",", ",")
|
| 46 |
+
line = line.replace("。", ".")
|
| 47 |
+
line = line.replace("‘", "'")
|
| 48 |
+
line = line.replace("“", ' " ')
|
| 49 |
return "".join(lines)
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
# Note 对话需求大则令 raw = False
|
| 53 |
+
def get_response(system, context, myKey, raw=False):
|
| 54 |
+
openai.api_key = myKey
|
| 55 |
+
response = openai.ChatCompletion.create(
|
| 56 |
+
model="gpt-3.5-turbo",
|
| 57 |
+
messages=[system, *context],
|
| 58 |
+
)
|
| 59 |
+
openai.api_key = ""
|
| 60 |
+
if raw:
|
| 61 |
+
return response
|
| 62 |
+
else:
|
| 63 |
+
statistics = f'本次对话Tokens用量【{response["usage"]["total_tokens"]} / 4096】 ( 提问+上文 {response["usage"]["prompt_tokens"]},回答 {response["usage"]["completion_tokens"]} )'
|
| 64 |
+
message = response["choices"][0]["message"]["content"]
|
| 65 |
+
|
| 66 |
+
message_with_stats = f"{message}\n\n================\n\n{statistics}"
|
| 67 |
+
# message_with_stats = markdown.markdown(message_with_stats)
|
| 68 |
+
|
| 69 |
+
return message, parse_text(message_with_stats)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def predict(chatbot, input_sentence, system, context, myKey):
|
| 73 |
+
if len(input_sentence) == 0:
|
| 74 |
+
return []
|
| 75 |
+
context.append({"role": "user", "content": f"{input_sentence}"})
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
message, message_with_stats = get_response(system, context, myKey)
|
| 79 |
+
except openai.error.AuthenticationError:
|
| 80 |
+
chatbot.append((input_sentence, "请求失败,请检查API-key是否正确。"))
|
| 81 |
+
return chatbot, context
|
| 82 |
+
except openai.error.Timeout:
|
| 83 |
+
chatbot.append((input_sentence, "请求超时,请检查网络连接。"))
|
| 84 |
+
return chatbot, context
|
| 85 |
+
except openai.error.APIConnectionError:
|
| 86 |
+
chatbot.append((input_sentence, "连接失败,请检查网络连接。"))
|
| 87 |
+
return chatbot, context
|
| 88 |
+
except openai.error.RateLimitError:
|
| 89 |
+
chatbot.append((input_sentence, "请求过于频繁,请5s后再试。"))
|
| 90 |
+
return chatbot, context
|
| 91 |
+
except:
|
| 92 |
+
chatbot.append((input_sentence, "发生了未知错误Orz"))
|
| 93 |
+
return chatbot, context
|
| 94 |
+
|
| 95 |
+
context.append({"role": "assistant", "content": message})
|
| 96 |
+
chatbot.append((input_sentence, message_with_stats))
|
| 97 |
+
return chatbot, context
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def retry(chatbot, system, context, myKey):
|
| 101 |
+
if len(context) == 0:
|
| 102 |
+
return [], []
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
message, message_with_stats = get_response(system, context[:-1], myKey)
|
| 106 |
+
except openai.error.AuthenticationError:
|
| 107 |
+
chatbot.append(("重试请求", "请求失败,请检查API-key是否正确。"))
|
| 108 |
+
return chatbot, context
|
| 109 |
+
except openai.error.Timeout:
|
| 110 |
+
chatbot.append(("重试请求", "请求超时,请检查网络连接。"))
|
| 111 |
+
return chatbot, context
|
| 112 |
+
except openai.error.APIConnectionError:
|
| 113 |
+
chatbot.append(("重试请求", "连接失败,请检查网络连接。"))
|
| 114 |
+
return chatbot, context
|
| 115 |
+
except openai.error.RateLimitError:
|
| 116 |
+
chatbot.append(("重试请求", "请求过于频繁,请5s后再试。"))
|
| 117 |
+
return chatbot, context
|
| 118 |
+
except:
|
| 119 |
+
chatbot.append(("重试请求", "发生了未知错误Orz"))
|
| 120 |
+
return chatbot, context
|
| 121 |
+
|
| 122 |
+
context[-1] = {"role": "assistant", "content": message}
|
| 123 |
+
|
| 124 |
+
chatbot[-1] = (context[-2]["content"], message_with_stats)
|
| 125 |
+
return chatbot, context
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def delete_last_conversation(chatbot, context):
|
| 129 |
+
if len(context) == 0:
|
| 130 |
+
return [], []
|
| 131 |
+
chatbot = chatbot[:-1]
|
| 132 |
+
context = context[:-2]
|
| 133 |
+
return chatbot, context
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def reduce_token(chatbot, system, context, myKey):
|
| 137 |
+
context.append(
|
| 138 |
+
{
|
| 139 |
+
"role": "user",
|
| 140 |
+
"content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。",
|
| 141 |
+
}
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
response = get_response(system, context, myKey, raw=True)
|
| 145 |
+
|
| 146 |
+
statistics = (
|
| 147 |
+
f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
|
| 148 |
+
)
|
| 149 |
+
optmz_str = parse_text(
|
| 150 |
+
f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}'
|
| 151 |
+
)
|
| 152 |
+
chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
|
| 153 |
+
|
| 154 |
+
context = []
|
| 155 |
+
context.append({"role": "user", "content": "我们之前聊了什么?"})
|
| 156 |
+
context.append(
|
| 157 |
+
{
|
| 158 |
+
"role": "assistant",
|
| 159 |
+
"content": f'我们之前聊了:{response["choices"][0]["message"]["content"]}',
|
| 160 |
+
}
|
| 161 |
+
)
|
| 162 |
+
return chatbot, context
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def save_chat_history(filepath, system, context):
|
| 166 |
if filepath == "":
|
| 167 |
return
|
| 168 |
+
history = {"system": system, "context": context}
|
| 169 |
+
with open(f"{filepath}.json", "w") as f:
|
| 170 |
+
json.dump(history, f)
|
|
|
|
|
|
|
| 171 |
|
| 172 |
|
| 173 |
+
def load_chat_history(fileobj):
|
| 174 |
+
with open(fileobj.name, "r") as f:
|
| 175 |
+
history = json.load(f)
|
| 176 |
+
context = history["context"]
|
| 177 |
+
chathistory = []
|
| 178 |
+
for i in range(0, len(context), 2):
|
| 179 |
+
chathistory.append(
|
| 180 |
+
(parse_text(context[i]["content"]), parse_text(context[i + 1]["content"]))
|
| 181 |
+
)
|
| 182 |
+
return chathistory, history["system"], context, history["system"]["content"]
|
| 183 |
|
| 184 |
|
| 185 |
+
def get_history_names():
|
| 186 |
+
with open("history.json", "r") as f:
|
| 187 |
+
history = json.load(f)
|
| 188 |
+
return list(history.keys())
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
|
| 191 |
def reset_state():
|
| 192 |
return [], []
|
| 193 |
|
| 194 |
|
| 195 |
+
def update_system(new_system_prompt):
|
| 196 |
+
return {"role": "system", "content": new_system_prompt}
|
| 197 |
+
|
| 198 |
|
| 199 |
+
def set_apikey(new_api_key, myKey):
|
| 200 |
+
old_api_key = myKey
|
| 201 |
|
| 202 |
+
try:
|
| 203 |
+
get_response(
|
| 204 |
+
update_system(initial_prompt),
|
| 205 |
+
[{"role": "user", "content": "test"}],
|
| 206 |
+
new_api_key,
|
| 207 |
+
)
|
| 208 |
+
except openai.error.AuthenticationError:
|
| 209 |
+
return "无效的api-key", myKey
|
| 210 |
+
except openai.error.Timeout:
|
| 211 |
+
return "请求超时,请检查网络设置", myKey
|
| 212 |
+
except openai.error.APIConnectionError:
|
| 213 |
+
return "网络错误", myKey
|
| 214 |
+
except:
|
| 215 |
+
return "发生了未知错误Orz", myKey
|
| 216 |
|
| 217 |
+
encryption_str = "验证成功,api-key已做遮挡处理:" + new_api_key[:4] + "..." + new_api_key[-4:]
|
| 218 |
+
return encryption_str, new_api_key
|
| 219 |
|
|
|
|
|
|
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
with gr.Blocks() as demo:
|
| 222 |
+
keyTxt = gr.Textbox(
|
| 223 |
+
show_label=True,
|
| 224 |
+
placeholder=f"在这里输入你的OpenAI API-key...",
|
| 225 |
+
value=initial_keytxt,
|
| 226 |
+
label="API Key",
|
| 227 |
+
).style(container=True)
|
| 228 |
+
|
| 229 |
+
chatbot = gr.Chatbot()
|
| 230 |
+
|
| 231 |
+
# The 'color_map' parameter has been deprecated.
|
| 232 |
+
# chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
|
| 233 |
+
context = gr.State([])
|
| 234 |
+
systemPrompt = gr.State(update_system(initial_prompt))
|
| 235 |
+
myKey = gr.State(my_api_key)
|
| 236 |
topic = gr.State("未命名对话历史记录")
|
| 237 |
|
| 238 |
with gr.Row():
|
| 239 |
with gr.Column(scale=12):
|
| 240 |
txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(
|
| 241 |
+
container=False
|
| 242 |
+
)
|
| 243 |
with gr.Column(min_width=50, scale=1):
|
| 244 |
submitBtn = gr.Button("🚀", variant="primary")
|
| 245 |
with gr.Row():
|
| 246 |
emptyBtn = gr.Button("🧹 新的对话")
|
| 247 |
retryBtn = gr.Button("🔄 重新生成")
|
| 248 |
delLastBtn = gr.Button("🗑️ 删除上条对话")
|
| 249 |
+
reduceTokenBtn = gr.Button("♻️ 优化Tokens")
|
| 250 |
+
newSystemPrompt = gr.Textbox(
|
| 251 |
+
show_label=True,
|
| 252 |
+
placeholder=f"在这里输入新的System Prompt...",
|
| 253 |
+
label="更改 System prompt",
|
| 254 |
+
).style(container=True)
|
| 255 |
+
systemPromptDisplay = gr.Textbox(
|
| 256 |
+
show_label=True,
|
| 257 |
+
value=initial_prompt,
|
| 258 |
+
interactive=False,
|
| 259 |
+
label="目前的 System prompt",
|
| 260 |
+
).style(container=True)
|
| 261 |
+
with gr.Accordion(
|
| 262 |
+
label="保存/加载对话历史记录(在文本框中输入文件名,点击“保存对话”按钮,历史记录文件会被存储到本地)", open=False
|
| 263 |
+
):
|
| 264 |
with gr.Column():
|
| 265 |
with gr.Row():
|
| 266 |
with gr.Column(scale=6):
|
| 267 |
saveFileName = gr.Textbox(
|
| 268 |
+
show_label=True,
|
| 269 |
+
placeholder=f"在这里输入保存的文件名...",
|
| 270 |
+
label="保存对话",
|
| 271 |
+
value="对话历史记录",
|
| 272 |
+
).style(container=True)
|
| 273 |
with gr.Column(scale=1):
|
| 274 |
saveBtn = gr.Button("💾 保存对话")
|
| 275 |
+
uploadBtn = gr.UploadButton(
|
| 276 |
+
"📂 读取对话", file_count="single", file_types=["json"]
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
txt.submit(
|
| 280 |
+
predict,
|
| 281 |
+
[chatbot, txt, systemPrompt, context, myKey],
|
| 282 |
+
[chatbot, context],
|
| 283 |
+
show_progress=True,
|
| 284 |
+
)
|
| 285 |
+
txt.submit(lambda: "", None, txt)
|
| 286 |
+
submitBtn.click(
|
| 287 |
+
predict,
|
| 288 |
+
[chatbot, txt, systemPrompt, context, myKey],
|
| 289 |
+
[chatbot, context],
|
| 290 |
+
show_progress=True,
|
| 291 |
+
)
|
| 292 |
+
submitBtn.click(lambda: "", None, txt)
|
| 293 |
+
emptyBtn.click(reset_state, outputs=[chatbot, context])
|
| 294 |
+
newSystemPrompt.submit(update_system, newSystemPrompt, systemPrompt)
|
| 295 |
+
newSystemPrompt.submit(lambda x: x, newSystemPrompt, systemPromptDisplay)
|
| 296 |
+
newSystemPrompt.submit(lambda: "", None, newSystemPrompt)
|
| 297 |
+
retryBtn.click(
|
| 298 |
+
retry,
|
| 299 |
+
[chatbot, systemPrompt, context, myKey],
|
| 300 |
+
[chatbot, context],
|
| 301 |
+
show_progress=True,
|
| 302 |
+
)
|
| 303 |
+
delLastBtn.click(
|
| 304 |
+
delete_last_conversation,
|
| 305 |
+
[chatbot, context],
|
| 306 |
+
[chatbot, context],
|
| 307 |
+
show_progress=True,
|
| 308 |
+
)
|
| 309 |
+
reduceTokenBtn.click(
|
| 310 |
+
reduce_token,
|
| 311 |
+
[chatbot, systemPrompt, context, myKey],
|
| 312 |
+
[chatbot, context],
|
| 313 |
+
show_progress=True,
|
| 314 |
+
)
|
| 315 |
+
keyTxt.submit(set_apikey, [keyTxt, myKey], [keyTxt, myKey], show_progress=True)
|
| 316 |
+
uploadBtn.upload(
|
| 317 |
+
load_chat_history,
|
| 318 |
+
uploadBtn,
|
| 319 |
+
[chatbot, systemPrompt, context, systemPromptDisplay],
|
| 320 |
+
show_progress=True,
|
| 321 |
+
)
|
| 322 |
+
saveBtn.click(
|
| 323 |
+
save_chat_history,
|
| 324 |
+
[saveFileName, systemPrompt, context],
|
| 325 |
+
None,
|
| 326 |
+
show_progress=True,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
|
| 330 |
|
| 331 |
demo.title = "ChatGPT 🚀"
|