longtianye2010 commited on
Commit
65538e0
·
1 Parent(s): 1cc77d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -4
app.py CHANGED
@@ -1,7 +1,189 @@
 
1
  import gradio as gr
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def parse_text(text):
20
+ lines = text.split("\n")
21
+ for i,line in enumerate(lines):
22
+ if "```" in line:
23
+ items = line.split('`')
24
+ if items[-1]:
25
+ lines[i] = f'<pre><code class="{items[-1]}">'
26
+ else:
27
+ lines[i] = f'</code></pre>'
28
+ else:
29
+ if i>0:
30
+ line = line.replace("<", "&lt;")
31
+ line = line.replace(">", "&gt;")
32
+ lines[i] = '<br/>'+line.replace(" ", "&nbsp;")
33
+ return "".join(lines)
34
+
35
+ def get_response(system, context, myKey, raw = False):
36
+ openai.api_key = myKey
37
+ response = openai.ChatCompletion.create(
38
+ model="gpt-3.5-turbo",
39
+ messages=[system, *context],
40
+ )
41
+ openai.api_key = ""
42
+ if raw:
43
+ return response
44
+ else:
45
+ statistics = f'本次对话Tokens用量【{response["usage"]["total_tokens"]} / 4096】 ( 提问+上文 {response["usage"]["prompt_tokens"]},回答 {response["usage"]["completion_tokens"]} )'
46
+ message = response["choices"][0]["message"]["content"]
47
+
48
+ message_with_stats = f'{message}\n\n================\n\n{statistics}'
49
+ # message_with_stats = markdown.markdown(message_with_stats)
50
+
51
+ return message, parse_text(message_with_stats)
52
+
53
+ def predict(chatbot, input_sentence, system, context, myKey):
54
+ if len(input_sentence) == 0:
55
+ return []
56
+ context.append({"role": "user", "content": f"{input_sentence}"})
57
+
58
+ try:
59
+ message, message_with_stats = get_response(system, context, myKey)
60
+ except:
61
+ chatbot.append((input_sentence, "请求失败,请检查API-key是否正确。"))
62
+ return chatbot, context
63
+
64
+ context.append({"role": "assistant", "content": message})
65
+
66
+ chatbot.append((input_sentence, message_with_stats))
67
+
68
+ return chatbot, context
69
+
70
+ def retry(chatbot, system, context, myKey):
71
+ if len(context) == 0:
72
+ return [], []
73
+ try:
74
+ message, message_with_stats = get_response(system, context[:-1], myKey)
75
+ except:
76
+ chatbot.append(("重试请求", "请求失败,请检查API-key是否正确。"))
77
+ return chatbot, context
78
+ context[-1] = {"role": "assistant", "content": message}
79
+
80
+ chatbot[-1] = (context[-2]["content"], message_with_stats)
81
+ return chatbot, context
82
+
83
+ def delete_last_conversation(chatbot, context):
84
+ if len(context) == 0:
85
+ return [], []
86
+ chatbot = chatbot[:-1]
87
+ context = context[:-2]
88
+ return chatbot, context
89
+
90
+ def reduce_token(chatbot, system, context, myKey):
91
+ context.append({"role": "user", "content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。"})
92
+
93
+ response = get_response(system, context, myKey, raw=True)
94
+
95
+ statistics = f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
96
+ optmz_str = parse_text( f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}' )
97
+ chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
98
+
99
+ context = []
100
+ context.append({"role": "user", "content": "我们之前聊了什么?"})
101
+ context.append({"role": "assistant", "content": f'我们之前聊了:{response["choices"][0]["message"]["content"]}'})
102
+ return chatbot, context
103
+
104
+ def save_chat_history(filepath, system, context):
105
+ if filepath == "":
106
+ return
107
+ history = {"system": system, "context": context}
108
+ with open(f"{filepath}.json", "w") as f:
109
+ json.dump(history, f)
110
+
111
+ def load_chat_history(fileobj):
112
+ with open(fileobj.name, "r") as f:
113
+ history = json.load(f)
114
+ context = history["context"]
115
+ chathistory = []
116
+ for i in range(0, len(context), 2):
117
+ chathistory.append((parse_text(context[i]["content"]), parse_text(context[i+1]["content"])))
118
+ return chathistory , history["system"], context, history["system"]["content"]
119
+
120
+ def get_history_names():
121
+ with open("history.json", "r") as f:
122
+ history = json.load(f)
123
+ return list(history.keys())
124
+
125
+
126
+ def reset_state():
127
+ return [], []
128
+
129
+ def update_system(new_system_prompt):
130
+ return {"role": "system", "content": new_system_prompt}
131
+
132
+ def set_apikey(new_api_key, myKey):
133
+ old_api_key = myKey
134
+ try:
135
+ get_response(update_system(initial_prompt), [{"role": "user", "content": "test"}], new_api_key)
136
+ except:
137
+ traceback.print_exc()
138
+ print("API key校验失败,请检查API key是否正确,或者检查网络是否畅通。")
139
+ return "无效的api-key", myKey
140
+ encryption_str = "验证成功,api-key已做遮挡处理:" + new_api_key[:4] + "..." + new_api_key[-4:]
141
+ return encryption_str, new_api_key
142
+
143
+
144
+ with gr.Blocks() as demo:
145
+ keyTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入你的API-key...", value=my_api_key, label="API Key").style(container=True)
146
+ chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
147
+ context = gr.State([])
148
+ systemPrompt = gr.State(update_system(initial_prompt))
149
+ myKey = gr.State(my_api_key)
150
+ topic = gr.State("未命名对话历史记录")
151
+
152
+ with gr.Row():
153
+ with gr.Column(scale=12):
154
+ txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(container=False)
155
+ with gr.Column(min_width=50, scale=1):
156
+ submitBtn = gr.Button("🚀", variant="primary")
157
+ with gr.Row():
158
+ emptyBtn = gr.Button("🧹 新的对话")
159
+ retryBtn = gr.Button("🔄 重新生成")
160
+ delLastBtn = gr.Button("🗑️ 删除上条对话")
161
+ reduceTokenBtn = gr.Button("♻️ 优化Tokens")
162
+ newSystemPrompt = gr.Textbox(show_label=True, placeholder=f"在这里输入新的System Prompt...", label="更改 System prompt").style(container=True)
163
+ systemPromptDisplay = gr.Textbox(show_label=True, value=initial_prompt, interactive=False, label="目前的 System prompt").style(container=True)
164
+ with gr.Accordion(label="保存/加载对话历史记录(在文本框中输入文件名,点击“保存对话”按钮,历史记录文件会被存储到本地)", open=False):
165
+ with gr.Column():
166
+ with gr.Row():
167
+ with gr.Column(scale=6):
168
+ saveFileName = gr.Textbox(show_label=True, placeholder=f"在这里输入保存的文件名...", label="保存对话", value="对话历史记录").style(container=True)
169
+ with gr.Column(scale=1):
170
+ saveBtn = gr.Button("💾 保存对话")
171
+ uploadBtn = gr.UploadButton("📂 读取对话", file_count="single", file_types=["json"])
172
+
173
+ txt.submit(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
174
+ txt.submit(lambda :"", None, txt)
175
+ submitBtn.click(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
176
+ submitBtn.click(lambda :"", None, txt)
177
+ emptyBtn.click(reset_state, outputs=[chatbot, context])
178
+ newSystemPrompt.submit(update_system, newSystemPrompt, systemPrompt)
179
+ newSystemPrompt.submit(lambda x: x, newSystemPrompt, systemPromptDisplay)
180
+ newSystemPrompt.submit(lambda :"", None, newSystemPrompt)
181
+ retryBtn.click(retry, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
182
+ delLastBtn.click(delete_last_conversation, [chatbot, context], [chatbot, context], show_progress=True)
183
+ reduceTokenBtn.click(reduce_token, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
184
+ keyTxt.submit(set_apikey, [keyTxt, myKey], [keyTxt, myKey], show_progress=True)
185
+ uploadBtn.upload(load_chat_history, uploadBtn, [chatbot, systemPrompt, context, systemPromptDisplay], show_progress=True)
186
+ saveBtn.click(save_chat_history, [saveFileName, systemPrompt, context], None, show_progress=True)
187
+
188
+
189
+ demo.launch()