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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import openai
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import traceback
|
| 7 |
+
# import markdown
|
| 8 |
+
|
| 9 |
+
my_api_key = "" # 在这里输入你的 API 密钥
|
| 10 |
+
initial_prompt = "You are a helpful assistant."
|
| 11 |
+
|
| 12 |
+
if my_api_key == "":
|
| 13 |
+
my_api_key = os.environ.get('my_api_key')
|
| 14 |
+
|
| 15 |
+
if my_api_key == "empty":
|
| 16 |
+
print("Please give a api key!")
|
| 17 |
+
sys.exit(1)
|
| 18 |
+
|
| 19 |
+
if my_api_key == "":
|
| 20 |
+
initial_keytxt = None
|
| 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 |
+
def parse_text(text):
|
| 27 |
+
lines = text.split("\n")
|
| 28 |
+
for i,line in enumerate(lines):
|
| 29 |
+
if "```" in line:
|
| 30 |
+
items = line.split('`')
|
| 31 |
+
if items[-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 |
+
line = line.replace("<", "<")
|
| 38 |
+
line = line.replace(">", ">")
|
| 39 |
+
lines[i] = '<br/>'+line.replace(" ", " ")
|
| 40 |
+
return "".join(lines)
|
| 41 |
+
|
| 42 |
+
def get_response(system, context, myKey, raw = False):
|
| 43 |
+
openai.api_key = myKey
|
| 44 |
+
response = openai.ChatCompletion.create(
|
| 45 |
+
model="gpt-3.5-turbo",
|
| 46 |
+
messages=[system, *context],
|
| 47 |
+
temperature=0.75,
|
| 48 |
+
top_p=1,
|
| 49 |
+
frequency_penalty=0,
|
| 50 |
+
presence_penalty=0
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
openai.api_key = ""
|
| 54 |
+
if raw:
|
| 55 |
+
return response
|
| 56 |
+
else:
|
| 57 |
+
statistics = f'本次对话Tokens用量【{response["usage"]["total_tokens"]} / 4096】 ( 提问+上文 {response["usage"]["prompt_tokens"]},回答 {response["usage"]["completion_tokens"]} )'
|
| 58 |
+
# message = response["choices"][0]["message"]["content"]
|
| 59 |
+
message = response["choices"][0]["message"]["content"]
|
| 60 |
+
message_with_stats = f'{message}\n\n================\n\n{statistics}'
|
| 61 |
+
# message_with_stats = markdown.markdown(message_with_stats)
|
| 62 |
+
|
| 63 |
+
return message, parse_text(message_with_stats)
|
| 64 |
+
|
| 65 |
+
def predict(chatbot, input_sentence, system, context, myKey):
|
| 66 |
+
if len(input_sentence) == 0:
|
| 67 |
+
return []
|
| 68 |
+
context.append({"role": "user", "content": f"{input_sentence}"})
|
| 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 |
+
|
| 90 |
+
chatbot.append((input_sentence, message_with_stats))
|
| 91 |
+
|
| 92 |
+
return chatbot, context
|
| 93 |
+
|
| 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)
|
| 119 |
+
return chatbot, context
|
| 120 |
+
|
| 121 |
+
def delete_last_conversation(chatbot, context):
|
| 122 |
+
if len(context) == 0:
|
| 123 |
+
return [], []
|
| 124 |
+
chatbot = chatbot[:-1]
|
| 125 |
+
context = context[:-2]
|
| 126 |
+
return chatbot, context
|
| 127 |
+
|
| 128 |
+
def reduce_token(chatbot, system, context, myKey):
|
| 129 |
+
context.append({"role": "user", "content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。"})
|
| 130 |
+
|
| 131 |
+
response = get_response(system, context, myKey, raw=True)
|
| 132 |
+
|
| 133 |
+
statistics = f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
|
| 134 |
+
optmz_str = parse_text( f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}' )
|
| 135 |
+
chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
|
| 136 |
+
|
| 137 |
+
context = []
|
| 138 |
+
context.append({"role": "user", "content": "我们之前聊了什么?"})
|
| 139 |
+
context.append({"role": "assistant", "content": f'我们之前聊了:{response["choices"][0]["message"]["content"]}'})
|
| 140 |
+
return chatbot, context
|
| 141 |
+
|
| 142 |
+
def save_chat_history(filepath, system, context):
|
| 143 |
+
if filepath == "":
|
| 144 |
+
return
|
| 145 |
+
history = {"system": system, "context": context}
|
| 146 |
+
with open(f"{filepath}.json", "w") as f:
|
| 147 |
+
json.dump(history, f)
|
| 148 |
+
|
| 149 |
+
def load_chat_history(fileobj):
|
| 150 |
+
with open(fileobj.name, "r") as f:
|
| 151 |
+
history = json.load(f)
|
| 152 |
+
context = history["context"]
|
| 153 |
+
chathistory = []
|
| 154 |
+
for i in range(0, len(context), 2):
|
| 155 |
+
chathistory.append((parse_text(context[i]["content"]), parse_text(context[i+1]["content"])))
|
| 156 |
+
return chathistory , history["system"], context, history["system"]["content"]
|
| 157 |
+
|
| 158 |
+
def get_history_names():
|
| 159 |
+
with open("history.json", "r") as f:
|
| 160 |
+
history = json.load(f)
|
| 161 |
+
return list(history.keys())
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def reset_state():
|
| 165 |
+
return [], []
|
| 166 |
+
|
| 167 |
+
def update_system(new_system_prompt):
|
| 168 |
+
return {"role": "system", "content": new_system_prompt}
|
| 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.Textbox(show_label=True, placeholder=f"在这里输入你的OpenAI API-key...", value=initial_keytxt, label="API Key").style(container=True)
|
| 190 |
+
chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
|
| 191 |
+
context = gr.State([])
|
| 192 |
+
systemPrompt = gr.State(update_system(initial_prompt))
|
| 193 |
+
myKey = gr.State(my_api_key)
|
| 194 |
+
topic = gr.State("未命名对话历史记录")
|
| 195 |
+
|
| 196 |
+
with gr.Row():
|
| 197 |
+
with gr.Column(scale=12):
|
| 198 |
+
txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(container=False)
|
| 199 |
+
with gr.Column(min_width=50, scale=1):
|
| 200 |
+
submitBtn = gr.Button("🚀", variant="primary")
|
| 201 |
+
with gr.Row():
|
| 202 |
+
emptyBtn = gr.Button("🧹 新的对话")
|
| 203 |
+
retryBtn = gr.Button("🔄 重新生成")
|
| 204 |
+
delLastBtn = gr.Button("🗑️ 删除上条对话")
|
| 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)
|
| 219 |
+
submitBtn.click(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
|
| 220 |
+
submitBtn.click(lambda :"", None, txt)
|
| 221 |
+
emptyBtn.click(reset_state, outputs=[chatbot, context])
|
| 222 |
+
newSystemPrompt.submit(update_system, newSystemPrompt, systemPrompt)
|
| 223 |
+
newSystemPrompt.submit(lambda x: x, newSystemPrompt, systemPromptDisplay)
|
| 224 |
+
newSystemPrompt.submit(lambda :"", None, newSystemPrompt)
|
| 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=True)
|
| 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()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
mdtex2html
|
| 3 |
+
pypinyin
|
| 4 |
+
tiktoken
|
| 5 |
+
socksio
|
| 6 |
+
tqdm
|
| 7 |
+
colorama
|