Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import openai
|
3 |
+
|
4 |
+
|
5 |
+
def get_answer_chatgpt(chat_history, message, system_message=None):
|
6 |
+
messages = []
|
7 |
+
if system_message:
|
8 |
+
TEMPLATE_SYSTEM = {"role": "system", "content": system_message}
|
9 |
+
message.append(TEMPLATE_SYSTEM)
|
10 |
+
|
11 |
+
TEMPLATE_USER = {"role": "user"}
|
12 |
+
TEMPLATE_BOT = {"role": "assistant"}
|
13 |
+
|
14 |
+
# add historical conversation
|
15 |
+
for pair in chat_history:
|
16 |
+
TEMPLATE_USER["content"] = pair[0]
|
17 |
+
TEMPLATE_BOT["content"] = pair[1]
|
18 |
+
messages.append(TEMPLATE_USER)
|
19 |
+
messages.append(TEMPLATE_BOT)
|
20 |
+
|
21 |
+
# add latest input
|
22 |
+
TEMPLATE_USER["content"] = message
|
23 |
+
messages.append(TEMPLATE_USER)
|
24 |
+
|
25 |
+
response = openai.ChatCompletion.create(
|
26 |
+
model="gpt-3.5-turbo",
|
27 |
+
messages=messages
|
28 |
+
)
|
29 |
+
|
30 |
+
return {
|
31 |
+
"completion": response["choices"][0]["message"]["content"],
|
32 |
+
"usage_prompt_token": response["usage"]["prompt_tokens"],
|
33 |
+
"usage_completion_token": response["usage"]["completion_tokens"]
|
34 |
+
}
|
35 |
+
|
36 |
+
|
37 |
+
|
38 |
+
with gr.Blocks() as demo:
|
39 |
+
system_prompt = gr.Textbox(placeholder="You are helpful assistence", lines=5, label="System")
|
40 |
+
message = gr.Textbox(placeholder="Please press enter to submit")
|
41 |
+
chatbot = gr.Chatbot()
|
42 |
+
clear = gr.Button("Clear")
|
43 |
+
|
44 |
+
def respond(chat_history, message):
|
45 |
+
response = get_answer_chatgpt(chat_history, message)
|
46 |
+
response = response["completion"]
|
47 |
+
|
48 |
+
return chat_history + [[message, response]]
|
49 |
+
|
50 |
+
message.submit(respond, [chatbot, message], chatbot)
|
51 |
+
|
52 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
53 |
+
|
54 |
+
demo.launch(share=True)
|