Chatbot / app.py
Laiba-Huggingface's picture
Update app.py
881f9da verified
import openai
import gradio as gr
# Hardcoded Groq API Key (⚠️ Not Secure, Recommended to Use Hugging Face Secrets)
GROQ_API_KEY = "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"
# Initialize OpenAI client for Groq
client = openai.OpenAI(
api_key=GROQ_API_KEY, # Using the hardcoded API key
base_url="https://api.groq.com/openai/v1"
)
conversation_history = [] # Store conversation history
def chat_with_groq(user_input):
"""Handles conversation with the chatbot via Groq API."""
global conversation_history
if user_input.lower() == "exit":
conversation_history.clear()
return "πŸ‘‹ Goodbye! Chat reset."
conversation_history.append({"role": "user", "content": user_input})
conversation_history = conversation_history[-5:] # Keep last 5 messages
try:
response = client.chat.completions.create(
model="llama3-8b-8192", # Change model if needed
messages=conversation_history
)
bot_reply = response.choices[0].message.content # Extract response
conversation_history.append({"role": "assistant", "content": bot_reply})
conversation_history = conversation_history[-5:]
return bot_reply
except Exception as e:
return f"⚠️ Error: {str(e)}"
# Custom CSS for Stylish UI
custom_css = """
h1 {
text-align: center;
font-size: 2em;
color: #4A90E2;
}
.gradio-container {
font-family: 'Arial', sans-serif;
background-color: #f4f4f9;
padding: 20px;
border-radius: 10px;
}
.input-container textarea {
font-size: 16px !important;
border-radius: 12px !important;
border: 2px solid #4A90E2 !important;
}
.button {
background-color: #4A90E2 !important;
color: white !important;
font-size: 16px;
border-radius: 10px !important;
padding: 10px 20px !important;
}
.output-container {
background-color: white;
padding: 15px;
border-radius: 12px;
border: 1px solid #ddd;
}
"""
# Gradio Chat UI
with gr.Blocks(css=custom_css) as app:
gr.Markdown("# ⚑ **Groq AI Chatbot**")
gr.Markdown("### πŸ€– Chat with an AI powered by Groq's API. Just type a message below!")
chatbot = gr.Chatbot(height=300) # Chat window
user_input = gr.Textbox(placeholder="Type your message here...", label="Your Message", lines=2)
send_button = gr.Button("πŸš€ Send")
def respond(message, history):
response = chat_with_groq(message)
return history + [(message, response)]
send_button.click(respond, inputs=[user_input, chatbot], outputs=[chatbot])
# Launch the Gradio App
app.launch()