MZhaovo commited on
Commit
bc41d77
1 Parent(s): e8d851b

新增输入key,取消api全局设置

Browse files
Files changed (1) hide show
  1. ChuanhuChatbot.py +35 -15
ChuanhuChatbot.py CHANGED
@@ -14,8 +14,6 @@ if my_api_key == "empty":
14
  print("Please give a api key!")
15
  sys.exit(1)
16
 
17
- openai.api_key = my_api_key
18
-
19
  def parse_text(text):
20
  lines = text.split("\n")
21
  for i,line in enumerate(lines):
@@ -32,11 +30,13 @@ def parse_text(text):
32
  lines[i] = '<br/>'+line.replace(" ", "&nbsp;")
33
  return "".join(lines)
34
 
35
- def get_response(system, context, raw = False):
 
36
  response = openai.ChatCompletion.create(
37
  model="gpt-3.5-turbo",
38
  messages=[system, *context],
39
  )
 
40
  if raw:
41
  return response
42
  else:
@@ -44,16 +44,20 @@ def get_response(system, context, raw = False):
44
  message = response["choices"][0]["message"]["content"]
45
 
46
  message_with_stats = f'{message}\n\n================\n\n{statistics}'
47
- # message_with_stats = markdown.markdown(message_with_stats)
48
 
49
  return message, parse_text(message_with_stats)
50
 
51
- def predict(chatbot, input_sentence, system, context):
52
  if len(input_sentence) == 0:
53
  return []
54
  context.append({"role": "user", "content": f"{input_sentence}"})
55
 
56
- message, message_with_stats = get_response(system, context)
 
 
 
 
57
 
58
  context.append({"role": "assistant", "content": message})
59
 
@@ -61,10 +65,14 @@ def predict(chatbot, input_sentence, system, context):
61
 
62
  return chatbot, context
63
 
64
- def retry(chatbot, system, context):
65
  if len(context) == 0:
66
  return [], []
67
- message, message_with_stats = get_response(system, context[:-1])
 
 
 
 
68
  context[-1] = {"role": "assistant", "content": message}
69
 
70
  chatbot[-1] = (context[-2]["content"], message_with_stats)
@@ -77,13 +85,13 @@ def delete_last_conversation(chatbot, context):
77
  context = context[:-2]
78
  return chatbot, context
79
 
80
- def reduce_token(chatbot, system, context):
81
  context.append({"role": "user", "content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。"})
82
 
83
- response = get_response(system, context, raw=True)
84
 
85
  statistics = f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
86
- optmz_str = markdown.markdown( f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}' )
87
  chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
88
 
89
  context = []
@@ -98,11 +106,22 @@ def reset_state():
98
  def update_system(new_system_prompt):
99
  return {"role": "system", "content": new_system_prompt}
100
 
 
 
 
 
 
 
 
 
 
101
 
102
  with gr.Blocks() as demo:
 
103
  chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
104
  context = gr.State([])
105
  systemPrompt = gr.State(update_system(initial_prompt))
 
106
 
107
  with gr.Row():
108
  with gr.Column(scale=12):
@@ -118,17 +137,18 @@ with gr.Blocks() as demo:
118
  newSystemPrompt = gr.Textbox(show_label=True, placeholder=f"在这里输入新的System Prompt...", label="更改 System prompt").style(container=True)
119
  systemPromptDisplay = gr.Textbox(show_label=True, value=initial_prompt, interactive=False, label="目前的 System prompt").style(container=True)
120
 
121
- txt.submit(predict, [chatbot, txt, systemPrompt, context], [chatbot, context], show_progress=True)
122
  txt.submit(lambda :"", None, txt)
123
- submitBtn.click(predict, [chatbot, txt, systemPrompt, context], [chatbot, context], show_progress=True)
124
  submitBtn.click(lambda :"", None, txt)
125
  emptyBtn.click(reset_state, outputs=[chatbot, context])
126
  newSystemPrompt.submit(update_system, newSystemPrompt, systemPrompt)
127
  newSystemPrompt.submit(lambda x: x, newSystemPrompt, systemPromptDisplay)
128
  newSystemPrompt.submit(lambda :"", None, newSystemPrompt)
129
- retryBtn.click(retry, [chatbot, systemPrompt, context], [chatbot, context], show_progress=True)
130
  delLastBtn.click(delete_last_conversation, [chatbot, context], [chatbot, context], show_progress=True)
131
- reduceTokenBtn.click(reduce_token, [chatbot, systemPrompt, context], [chatbot, context], show_progress=True)
 
132
 
133
 
134
  demo.launch()
 
14
  print("Please give a api key!")
15
  sys.exit(1)
16
 
 
 
17
  def parse_text(text):
18
  lines = text.split("\n")
19
  for i,line in enumerate(lines):
 
30
  lines[i] = '<br/>'+line.replace(" ", "&nbsp;")
31
  return "".join(lines)
32
 
33
+ def get_response(system, context, myKey, raw = False):
34
+ openai.api_key = myKey
35
  response = openai.ChatCompletion.create(
36
  model="gpt-3.5-turbo",
37
  messages=[system, *context],
38
  )
39
+ openai.api_key = ""
40
  if raw:
41
  return response
42
  else:
 
44
  message = response["choices"][0]["message"]["content"]
45
 
46
  message_with_stats = f'{message}\n\n================\n\n{statistics}'
47
+ # message_with_stats = markdown.markdown(message_with_stats)
48
 
49
  return message, parse_text(message_with_stats)
50
 
51
+ def predict(chatbot, input_sentence, system, context, myKey):
52
  if len(input_sentence) == 0:
53
  return []
54
  context.append({"role": "user", "content": f"{input_sentence}"})
55
 
56
+ try:
57
+ message, message_with_stats = get_response(system, context, myKey)
58
+ except:
59
+ chatbot.append((input_sentence, "请求失败,请检查API-key是否正确。"))
60
+ return chatbot, context
61
 
62
  context.append({"role": "assistant", "content": message})
63
 
 
65
 
66
  return chatbot, context
67
 
68
+ def retry(chatbot, system, context, myKey):
69
  if len(context) == 0:
70
  return [], []
71
+ try:
72
+ message, message_with_stats = get_response(system, context[:-1], myKey)
73
+ except:
74
+ chatbot.append(("重试请求", "请求失败,请检查API-key是否正确。"))
75
+ return chatbot, context
76
  context[-1] = {"role": "assistant", "content": message}
77
 
78
  chatbot[-1] = (context[-2]["content"], message_with_stats)
 
85
  context = context[:-2]
86
  return chatbot, context
87
 
88
+ def reduce_token(chatbot, system, context, myKey):
89
  context.append({"role": "user", "content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。"})
90
 
91
+ response = get_response(system, context, myKey, raw=True)
92
 
93
  statistics = f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
94
+ optmz_str = parse_text( f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}' )
95
  chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
96
 
97
  context = []
 
106
  def update_system(new_system_prompt):
107
  return {"role": "system", "content": new_system_prompt}
108
 
109
+ def set_apikey(new_api_key, myKey):
110
+ old_api_key = myKey
111
+ try:
112
+ get_response(update_system(initial_prompt), [{"role": "user", "content": "test"}], new_api_key)
113
+ except:
114
+ return "无效的api-key", myKey
115
+ encryption_str = "验证成功,api-key已做遮挡处理:" + new_api_key[:4] + "..." + new_api_key[-4:]
116
+ return encryption_str, new_api_key
117
+
118
 
119
  with gr.Blocks() as demo:
120
+ keyTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入你的API-key...", value=my_api_key, label="API Key").style(container=True)
121
  chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
122
  context = gr.State([])
123
  systemPrompt = gr.State(update_system(initial_prompt))
124
+ myKey = gr.State("sk-xxxxxxxxxxxxxxxxxxxxx")
125
 
126
  with gr.Row():
127
  with gr.Column(scale=12):
 
137
  newSystemPrompt = gr.Textbox(show_label=True, placeholder=f"在这里输入新的System Prompt...", label="更改 System prompt").style(container=True)
138
  systemPromptDisplay = gr.Textbox(show_label=True, value=initial_prompt, interactive=False, label="目前的 System prompt").style(container=True)
139
 
140
+ txt.submit(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
141
  txt.submit(lambda :"", None, txt)
142
+ submitBtn.click(predict, [chatbot, txt, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
143
  submitBtn.click(lambda :"", None, txt)
144
  emptyBtn.click(reset_state, outputs=[chatbot, context])
145
  newSystemPrompt.submit(update_system, newSystemPrompt, systemPrompt)
146
  newSystemPrompt.submit(lambda x: x, newSystemPrompt, systemPromptDisplay)
147
  newSystemPrompt.submit(lambda :"", None, newSystemPrompt)
148
+ retryBtn.click(retry, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
149
  delLastBtn.click(delete_last_conversation, [chatbot, context], [chatbot, context], show_progress=True)
150
+ reduceTokenBtn.click(reduce_token, [chatbot, systemPrompt, context, myKey], [chatbot, context], show_progress=True)
151
+ keyTxt.submit(set_apikey, [keyTxt, myKey], [keyTxt, myKey], show_progress=True)
152
 
153
 
154
  demo.launch()