chatbot / app.py
mishalmazhar's picture
Update app.py
6e524c6 verified
import os
import gradio as gr
from groq import Groq
# Load Groq API key
api_key = os.environ.get("GROQ_API_KEY")
if not api_key:
raise ValueError("Missing GROQ_API_KEY. Add it in Hugging Face β†’ Settings β†’ Secrets.")
client = Groq(api_key=api_key)
# Chat function
def chat_with_ai(message, history):
if history is None:
history = []
try:
# Filter history to only role & content
clean_history = [{"role": h["role"], "content": h["content"]} for h in history]
# Build Groq message list
messages = [
{"role": "system", "content": "You are a helpful, friendly AI assistant."}
] + clean_history + [
{"role": "user", "content": message}
]
# Call Groq
response = client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=messages,
temperature=0.5,
)
reply = response.choices[0].message.content.strip()
# Append in Gradio 6 dictionary format
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": reply})
return "", history
except Exception as e:
history.append({"role": "assistant", "content": f"Error: {str(e)}"})
return "", history
# 🎨 UI CSS
custom_css = """
body {
background: linear-gradient(135deg, #4facfe, #00f2fe);
}
.gradio-container {
max-width: 900px !important;
margin: auto;
}
h1 { color: white; text-align: center; }
button {
background: linear-gradient(90deg, #ff9a9e, #fad0c4) !important;
color: black !important;
border-radius: 12px !important;
}
"""
# 🌈 UI
with gr.Blocks() as demo:
gr.Markdown("# πŸ€– Groq AI Chatbot")
chatbot = gr.Chatbot(height=400)
msg = gr.Textbox(placeholder="Type your message...", show_label=False)
clear = gr.Button("Clear Chat 🧹")
msg.submit(chat_with_ai, [msg, chatbot], [msg, chatbot])
clear.click(lambda: [], None, chatbot)
# Launch (Gradio 6 requires css here)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860, css=custom_css)