IAMTFRMZA's picture
Update app.py
ad10eed verified
import gradio as gr
import openai
import os
import time
# Load secrets from HF Space secrets
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
ASSISTANT_ID = os.getenv("OPENAI_ASSISTANT_ID")
openai.api_key = OPENAI_API_KEY
def chat_with_assistant(message):
try:
if not OPENAI_API_KEY or not ASSISTANT_ID:
return "🚫 Missing OpenAI credentials or Assistant ID"
# Create thread + add user message
thread = openai.beta.threads.create()
openai.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=message
)
# Run the assistant
run = openai.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=ASSISTANT_ID
)
# Wait until complete
while True:
run_status = openai.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
if run_status.status == "completed":
break
elif run_status.status == "failed":
return "❌ Assistant failed to generate a response."
time.sleep(1)
# Fetch reply
messages = openai.beta.threads.messages.list(thread_id=thread.id)
for msg in reversed(messages.data):
if msg.role == "assistant":
return msg.content[0].text.value
return "⚠️ No assistant reply found."
except Exception as e:
return f"❌ Error: {str(e)}"
demo = gr.Interface(fn=chat_with_assistant, inputs="text", outputs="text", title="LOR Chat Assistant")
demo.launch()