Spaces:
Runtime error
Runtime error
Commit
·
da67f32
1
Parent(s):
83167a5
Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,48 @@
|
|
1 |
import gradio as gr
|
2 |
import openai
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
)
|
|
|
|
|
|
|
15 |
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
def
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
fn=app,
|
30 |
)
|
31 |
-
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import openai
|
3 |
+
import random
|
4 |
+
import time
|
5 |
|
6 |
+
# Set up OpenAI API key
|
7 |
+
openai.api_key = "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"
|
8 |
|
9 |
+
system_message = {"role": "system", "content": "You are a helpful assistant."}
|
10 |
+
|
11 |
+
with gr.Blocks() as demo:
|
12 |
+
chatbot = gr.Chatbot()
|
13 |
+
msg = gr.Textbox()
|
14 |
+
clear = gr.Button("Clear")
|
15 |
+
|
16 |
+
state = gr.State([])
|
17 |
+
|
18 |
+
def user(user_message, history):
|
19 |
+
return "", history + [[user_message, None]]
|
20 |
|
21 |
+
def bot(history, messages_history):
|
22 |
+
user_message = history[-1][0]
|
23 |
+
bot_message, messages_history = ask_gpt(user_message, messages_history)
|
24 |
+
messages_history += [{"role": "assistant", "content": bot_message}]
|
25 |
+
history[-1][1] = bot_message
|
26 |
+
time.sleep(1)
|
27 |
+
return history, messages_history
|
28 |
|
29 |
+
def ask_gpt(message, messages_history):
|
30 |
+
messages_history += [{"role": "user", "content": message}]
|
31 |
+
response = openai.ChatCompletion.create(
|
32 |
+
model="gpt-3.5-turbo",
|
33 |
+
messages=messages_history
|
34 |
+
)
|
35 |
+
return response['choices'][0]['message']['content'], messages_history
|
36 |
|
37 |
+
def init_history(messages_history):
|
38 |
+
messages_history = []
|
39 |
+
messages_history += [system_message]
|
40 |
+
return messages_history
|
41 |
+
|
42 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
43 |
+
bot, [chatbot, state], [chatbot, state]
|
|
|
44 |
)
|
45 |
+
|
46 |
+
clear.click(lambda: None, None, chatbot, queue=False).success(init_history, [state], [state])
|
47 |
+
|
48 |
+
demo.launch()
|