jeremierostan's picture
Update app.py
e10a598 verified
raw
history blame
2.29 kB
import os
import openai
import gradio as gr
import time
# Set up password
username = os.getenv('username')
password = os.getenv('password')
# Set up OpenAI client
openai_api_key = os.getenv('openai_api_key')
openai.api_key = openai_api_key
client = openai.Client(api_key=openai.api_key)
# Set up assistant
assistant_id = os.getenv('assistant_id')
assistant = client.beta.assistants.retrieve(assistant_id)
thread = client.beta.threads.create()
# Get avatar link
avatar_link = os.getenv('avatar_link')
def chat_with_assistant(message, history):
# Add the user's message to the thread
client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=message
)
# Run the assistant with streaming
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': message}],
stream=True
)
# Handle the streaming response
response_text = ""
for chunk in response:
delta = chunk['choices'][0]['delta']
if 'content' in delta:
response_text += delta['content']
yield response_text
# Custom CSS for chat bubbles and colors
custom_css = """
.user-message { background-color: #DCF8C6; }
.assistant-message { background-color: #E2E2E2; }
"""
# Create the Gradio interface
with gr.Blocks(css=custom_css) as demo:
gr.HTML(f"""<img src = "https://i.postimg.cc/L6mbcC7F/DASH.png" width="150" height="112">""")
gr.Markdown("# **Learning Scales Assistant**🐬")
chatbot = gr.Chatbot(
[],
elem_id="chatbot",
bubble_full_width=False,
avatar_images=(None, avatar_link)
)
msg = gr.Textbox(
show_label=False,
placeholder="Enter text and press enter",
)
def user(user_message, history):
return "", history + [[user_message, None]]
def bot(history):
user_message = history[-1][0]
bot_message = ""
for response_text in chat_with_assistant(user_message, history):
history[-1][1] = response_text
chatbot.update(history)
return history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
demo.launch(auth=(username, password))