Spaces:
Build error
Build error
File size: 2,425 Bytes
0c0cda3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | from openai import OpenAI, AssistantEventHandler
from dotenv import load_dotenv
import os
import gradio as gr
# Load environment variables from .env file
load_dotenv()
# Load env variables
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
ASSISTANT_ID = os.getenv("ASSISTANT_ID")
client = OpenAI(api_key=OPENAI_API_KEY)
def create_thread():
return client.beta.threads.create()
def predict(user_message, history, thread):
# Append the new user message to the history
# history.append({"role": "user", "content": user_message})
# Send the user message to the OpenAI API
client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=user_message
)
response = []
# Stream the assistant's response
with client.beta.threads.runs.stream(
thread_id=thread.id,
assistant_id=ASSISTANT_ID
) as stream:
for event in stream:
if event.event == "thread.message.delta" and event.data.delta.content:
assistant_message = event.data.delta.content[0].text
response.append(assistant_message.value)
yield [{"role": "assistant", "content": ''.join(response)}], thread
# # Append the assistant's response to the history
history.append({"role": "assistant", "content": ''.join(response)})
yield history, thread
# Launch the Gradio chat interface
with gr.Blocks(title="Hair Library Shopping Assistant Demo") as demo:
chatbot = gr.Chatbot(type='messages', label="Hair Library Shopping Assistant Demo")
msg = gr.Textbox(placeholder="Type your message here...")
user_content = gr.State("")
thread = gr.State(create_thread)
history = gr.State([])
submit = gr.Button("Submit")
def user_input(user_message, history):
user_content = user_message
return "", history + [{"role": "user", "content": user_message}], user_content
msg.submit(user_input, [msg, chatbot], [msg, chatbot, user_content], queue=False).then(
predict, [user_content, chatbot, thread], [chatbot, thread]
)
submit.click(user_input, [msg, chatbot], [msg, chatbot, user_content], queue=False).then(
predict, [user_content, chatbot, thread], [chatbot, thread]
)
# msg.submit(predict, [msg, chatbot, thread], [chatbot, thread], queue=False)
# clear.click(lambda: None, None, chatbot, queue=False)
demo.launch(share=False) |