Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,43 +1,48 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 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 |
-
return
|
| 33 |
-
|
| 34 |
-
# Gradio
|
| 35 |
-
|
| 36 |
-
fn=
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
)
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import openai
|
| 3 |
import gradio as gr
|
| 4 |
+
|
| 5 |
+
# Retrieve OpenAI API key from Hugging Face Secrets
|
| 6 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 7 |
+
|
| 8 |
+
# Initialize OpenAI client
|
| 9 |
+
client = openai.OpenAI(api_key=openai_api_key)
|
| 10 |
+
|
| 11 |
+
# Chatbot function
|
| 12 |
+
def chatbot(user_input, history=[]):
|
| 13 |
+
if not openai_api_key:
|
| 14 |
+
return "⚠️ API key is missing. Please configure it in Hugging Face Secrets.", history
|
| 15 |
+
|
| 16 |
+
history.append({"role": "user", "content": user_input})
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
response = client.chat.completions.create(
|
| 20 |
+
model="gpt-4o",
|
| 21 |
+
messages=history,
|
| 22 |
+
temperature=0.7,
|
| 23 |
+
max_tokens=200,
|
| 24 |
+
top_p=1
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
bot_reply = response.choices[0].message.content
|
| 28 |
+
history.append({"role": "assistant", "content": bot_reply})
|
| 29 |
+
|
| 30 |
+
except Exception as e:
|
| 31 |
+
bot_reply = f"❌ Error: {str(e)}"
|
|
|
|
| 32 |
|
| 33 |
+
return bot_reply, history
|
| 34 |
+
|
| 35 |
+
# Gradio Interface
|
| 36 |
+
chatbot_ui = gr.ChatInterface(
|
| 37 |
+
fn=chatbot,
|
| 38 |
+
title="AI Chatbot",
|
| 39 |
+
description="A simple chatbot powered by GPT-4o.",
|
| 40 |
+
theme="soft",
|
| 41 |
+
retry_btn="🔄 Retry",
|
| 42 |
+
undo_btn="↩️ Undo",
|
| 43 |
+
clear_btn="🗑️ Clear"
|
| 44 |
)
|
| 45 |
|
| 46 |
+
# Launch the app
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
chatbot_ui.launch()
|