JohnSmith9982 commited on
Commit
84509dd
1 Parent(s): 545cceb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -0
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ 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):
35
+ openai.api_key = myKey
36
+ response = openai.ChatCompletion.create(
37
+ model="gpt-3.5-turbo",
38
+ messages=[system, *context],
39
+ )
40
+ openai.api_key = ""
41
+ if raw:
42
+ return response
43
+ else:
44
+ statistics = f'本次对话Tokens用量【{response["usage"]["total_tokens"]} / 4096】 ( 提问+上文 {response["usage"]["prompt_tokens"]},回答 {response["usage"]["completion_tokens"]} )'
45
+ message = response["choices"][0]["message"]["content"]
46
+
47
+ message_with_stats = f'{message}\n\n================\n\n{statistics}'
48
+ # message_with_stats = markdown.markdown(message_with_stats)
49
+
50
+ return message, parse_text(message_with_stats)
51
+
52
+ def predict(chatbot, input_sentence, system, context, myKey):
53
+ if len(input_sentence) == 0:
54
+ return []
55
+ context.append({"role": "user", "content": f"{input_sentence}"})
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
+
65
+ chatbot.append((input_sentence, message_with_stats))
66
+
67
+ return chatbot, context
68
+
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)
80
+ return chatbot, context
81
+
82
+ def delete_last_conversation(chatbot, context):
83
+ if len(context) == 0:
84
+ return [], []
85
+ chatbot = chatbot[:-1]
86
+ context = context[:-2]
87
+ return chatbot, context
88
+
89
+ def reduce_token(chatbot, system, context, myKey):
90
+ context.append({"role": "user", "content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。"})
91
+
92
+ response = get_response(system, context, myKey, raw=True)
93
+
94
+ statistics = f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
95
+ optmz_str = parse_text( f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}' )
96
+ chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
97
+
98
+ context = []
99
+ context.append({"role": "user", "content": "我们之前聊了什么?"})
100
+ context.append({"role": "assistant", "content": f'我们之前聊了:{response["choices"][0]["message"]["content"]}'})
101
+ return chatbot, context
102
+
103
+ def save_chat_history(filepath, system, context):
104
+ if filepath == "":
105
+ return
106
+ history = {"system": system, "context": context}
107
+ with open(f"{filepath}.json", "w") as f:
108
+ json.dump(history, f)
109
+
110
+ def load_chat_history(fileobj):
111
+ with open(fileobj.name, "r") as f:
112
+ history = json.load(f)
113
+ context = history["context"]
114
+ chathistory = []
115
+ for i in range(0, len(context), 2):
116
+ chathistory.append((parse_text(context[i]["content"]), parse_text(context[i+1]["content"])))
117
+ return chathistory , history["system"], context, history["system"]["content"]
118
+
119
+ def get_history_names():
120
+ with open("history.json", "r") as f:
121
+ history = json.load(f)
122
+ return list(history.keys())
123
+
124
+
125
+ def reset_state():
126
+ return [], []
127
+
128
+ def update_system(new_system_prompt):
129
+ return {"role": "system", "content": 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))
146
+ myKey = gr.State(my_api_key)
147
+ topic = gr.State("未命名对话历史记录")
148
+
149
+ with gr.Row():
150
+ with gr.Column(scale=12):
151
+ txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(container=False)
152
+ with gr.Column(min_width=50, scale=1):
153
+ submitBtn = gr.Button("🚀", variant="primary")
154
+ with gr.Row():
155
+ emptyBtn = gr.Button("🧹 新的对话")
156
+ retryBtn = gr.Button("🔄 重新生成")
157
+ delLastBtn = gr.Button("🗑️ 删除上条对话")
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)
172
+ submitBtn.click(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
173
+ submitBtn.click(lambda :"", None, txt)
174
+ emptyBtn.click(reset_state, outputs=[chatbot, context])
175
+ newSystemPrompt.submit(update_system, newSystemPrompt, systemPrompt)
176
+ newSystemPrompt.submit(lambda x: x, newSystemPrompt, systemPromptDisplay)
177
+ newSystemPrompt.submit(lambda :"", None, newSystemPrompt)
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()