Cartof commited on
Commit
0951c40
1 Parent(s): 9327ec1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -19
app.py CHANGED
@@ -1,25 +1,135 @@
1
- import openai
2
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- openai.api_key = "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"
 
 
 
 
5
 
6
- messages = [
7
- {"role": "system", "content": "You are a helpful and kind AI Assistant."},
8
- ]
 
 
 
 
 
 
 
9
 
10
- def chatbot(input):
11
- if input:
12
- messages.append({"role": "user", "content": input})
13
- chat = openai.ChatCompletion.create(
14
- model="gpt-3.5-turbo", messages=messages
15
- )
16
- reply = chat.choices[0].message.content
17
- messages.append({"role": "assistant", "content": reply})
18
- return reply
 
 
 
 
 
 
 
19
 
20
- inputs = gr.inputs.Textbox(lines=7, label="Chat with AI")
21
- outputs = gr.outputs.Textbox(label="Reply")
22
 
23
- gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="AI Chatbot",
24
- description="Ask anything you want",
25
- theme="compact").launch(share=True)
 
 
1
  import gradio as gr
2
+ import openai
3
+ import os
4
+ import sys
5
+ # import markdown
6
+
7
+ initial_prompt = "You are a helpful assistant."
8
+
9
+ def parse_text(text):
10
+ lines = text.split("\n")
11
+ for i,line in enumerate(lines):
12
+ if "```" in line:
13
+ items = line.split('`')
14
+ if items[-1]:
15
+ lines[i] = f'<pre><code class="{items[-1]}">'
16
+ else:
17
+ lines[i] = f'</code></pre>'
18
+ else:
19
+ if i>0:
20
+ line = line.replace("<", "&lt;")
21
+ line = line.replace(">", "&gt;")
22
+ lines[i] = '<br/>'+line.replace(" ", "&nbsp;")
23
+ return "".join(lines)
24
+
25
+ def get_response(system, context, raw = False):
26
+ openai.api_key = "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"
27
+ response = openai.ChatCompletion.create(
28
+ model="gpt-3.5-turbo",
29
+ messages=[system, *context],
30
+ )
31
+ if raw:
32
+ return response
33
+ else:
34
+ statistics = f'This conversation Tokens usage【{response["usage"]["total_tokens"]} / 4096】 ( Question + above {response["usage"]["prompt_tokens"]},Answer {response["usage"]["completion_tokens"]} )'
35
+ message = response["choices"][0]["message"]["content"]
36
+
37
+ message_with_stats = f'{message}\n\n================\n\n{statistics}'
38
+ # message_with_stats = markdown.markdown(message_with_stats)
39
+
40
+ return message, parse_text(message_with_stats)
41
+
42
+ def predict(chatbot, input_sentence, system, context):
43
+ if len(input_sentence) == 0:
44
+ return []
45
+ context.append({"role": "user", "content": f"{input_sentence}"})
46
+
47
+ message, message_with_stats = get_response(system, context)
48
+
49
+ context.append({"role": "assistant", "content": message})
50
+
51
+ chatbot.append((input_sentence, message_with_stats))
52
+
53
+ return chatbot, context
54
+
55
+ def retry(chatbot, system, context):
56
+ if len(context) == 0:
57
+ return [], []
58
+ message, message_with_stats = get_response(system, context[:-1])
59
+ context[-1] = {"role": "assistant", "content": message}
60
+
61
+ chatbot[-1] = (context[-2]["content"], message_with_stats)
62
+ return chatbot, context
63
+
64
+ def delete_last_conversation(chatbot, context):
65
+ if len(context) == 0:
66
+ return [], []
67
+ chatbot = chatbot[:-1]
68
+ context = context[:-2]
69
+ return chatbot, context
70
+
71
+ def reduce_token(chatbot, system, context):
72
+ context.append({"role": "user", "content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。"})
73
+
74
+ response = get_response(system, context, raw=True)
75
+
76
+ statistics = f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
77
+ optmz_str = markdown.markdown( f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}' )
78
+ chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
79
+
80
+ context = []
81
+ context.append({"role": "user", "content": "我们之前聊了什么?"})
82
+ context.append({"role": "assistant", "content": f'我们之前聊了:{response["choices"][0]["message"]["content"]}'})
83
+ return chatbot, context
84
+
85
+
86
+ def reset_state():
87
+ return [], []
88
+
89
+ def update_system(new_system_prompt):
90
+ return {"role": "system", "content": new_system_prompt}
91
+
92
+ title = """<h1 align="center">OpenAI ChatGPT</h1>"""
93
+ description = """<div align=center>
94
+
95
+ Will not describe your needs to ChatGPT?You Use [ChatGPT Shortcut](https://newzone.top/chatgpt/)
96
+
97
+ </div>
98
+ """
99
 
100
+ with gr.Blocks() as demo:
101
+ gr.HTML(title)
102
+ chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
103
+ context = gr.State([])
104
+ systemPrompt = gr.State(update_system(initial_prompt))
105
 
106
+ with gr.Row():
107
+ with gr.Column(scale=12):
108
+ txt = gr.Textbox(show_label=False, placeholder="Please enter any of your needs here").style(container=False)
109
+ with gr.Column(min_width=50, scale=1):
110
+ submitBtn = gr.Button("🚀 Submit", variant="primary")
111
+ with gr.Row():
112
+ emptyBtn = gr.Button("🧹 New conversation")
113
+ retryBtn = gr.Button("🔄 Resubmit")
114
+ delLastBtn = gr.Button("🗑️ Delete conversation")
115
+ reduceTokenBtn = gr.Button("♻️ Optimize Tokens")
116
 
117
+ newSystemPrompt = gr.Textbox(show_label=True, placeholder=f"Setting System Prompt...", label="Change System prompt").style(container=True)
118
+ systemPromptDisplay = gr.Textbox(show_label=True, value=initial_prompt, interactive=False, label="Current System prompt").style(container=True)
119
+
120
+ gr.Markdown(description)
121
+
122
+ txt.submit(predict, [chatbot, txt, systemPrompt, context], [chatbot, context], show_progress=True)
123
+ txt.submit(lambda :"", None, txt)
124
+ submitBtn.click(predict, [chatbot, txt, systemPrompt, context], [chatbot, context], show_progress=True)
125
+ submitBtn.click(lambda :"", None, txt)
126
+ emptyBtn.click(reset_state, outputs=[chatbot, context])
127
+ newSystemPrompt.submit(update_system, newSystemPrompt, systemPrompt)
128
+ newSystemPrompt.submit(lambda x: x, newSystemPrompt, systemPromptDisplay)
129
+ newSystemPrompt.submit(lambda :"", None, newSystemPrompt)
130
+ retryBtn.click(retry, [chatbot, systemPrompt, context], [chatbot, context], show_progress=True)
131
+ delLastBtn.click(delete_last_conversation, [chatbot, context], [chatbot, context], show_progress=True)
132
+ reduceTokenBtn.click(reduce_token, [chatbot, systemPrompt, context], [chatbot, context], show_progress=True)
133
 
 
 
134
 
135
+ demo.launch()