Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,57 @@
|
|
| 1 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
#
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
weights = [0.5, 0.3, 0.2]
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
print("\
|
| 29 |
-
|
| 30 |
-
print("
|
| 31 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import openai
|
| 3 |
+
import random
|
| 4 |
+
import time
|
| 5 |
+
import os
|
| 6 |
|
| 7 |
+
# Set up OpenAI API key
|
| 8 |
+
openai.api_key = os.getenv('APICode2')
|
| 9 |
+
system_message = {"role": "system", "content": "You are a helpful assistant."}
|
|
|
|
| 10 |
|
| 11 |
+
with gr.Blocks() as demo:
|
| 12 |
+
with gr.Row():
|
| 13 |
+
with gr.Column():
|
| 14 |
+
msg = gr.Textbox()
|
| 15 |
+
btn = gr.Button(value="send")
|
| 16 |
+
with gr.Row():
|
| 17 |
+
chatbot = gr.Chatbot()
|
| 18 |
+
with gr.Row():
|
| 19 |
+
prt = gr.Button("Save in memory")
|
| 20 |
+
clear = gr.Button("Clear")
|
| 21 |
+
state = gr.State([])
|
| 22 |
|
| 23 |
+
def user(user_message, history):
|
| 24 |
+
return "", history + [[user_message, None]]
|
| 25 |
|
| 26 |
+
def bot(history, messages_history):
|
| 27 |
+
user_message = history[-1][0]
|
| 28 |
+
bot_message, messages_history = ask_gpt(user_message, messages_history)
|
| 29 |
+
messages_history += [{"role": "assistant", "content": bot_message}]
|
| 30 |
+
history[-1][1] = bot_message
|
| 31 |
+
time.sleep(1)
|
| 32 |
+
return history, messages_history
|
| 33 |
|
| 34 |
+
def ask_gpt(message, messages_history):
|
| 35 |
+
messages_history += [{"role": "user", "content": message}]
|
| 36 |
+
response = openai.ChatCompletion.create(
|
| 37 |
+
model="gpt-4",
|
| 38 |
+
messages=messages_history
|
| 39 |
+
)
|
| 40 |
+
return response['choices'][0]['message']['content'], messages_history
|
| 41 |
|
| 42 |
+
def init_history(messages_history):
|
| 43 |
+
messages_history = []
|
| 44 |
+
messages_history += [system_message]
|
| 45 |
+
return messages_history
|
| 46 |
|
| 47 |
+
def printscr(chatbot):
|
| 48 |
+
print("\n\nYour chat hiatory:\n")
|
| 49 |
+
for i in range(len(chatbot)):
|
| 50 |
+
print(f"User input:{chatbot[i][0]}")
|
| 51 |
+
print(f"Bot output:{chatbot[i][1]}")
|
| 52 |
+
|
| 53 |
+
btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(bot, [chatbot, state], [chatbot, state])
|
| 54 |
+
prt.click(printscr, chatbot, None)
|
| 55 |
+
clear.click(lambda: None, None, chatbot, queue=False).success(init_history, [state], [state])
|
| 56 |
+
|
| 57 |
+
demo.launch()
|