Talha812's picture
Create app.py
cfdc4be verified
import os
import gradio as gr
from groq import Groq
from datetime import datetime
# ============ Load API Key ============
# In Hugging Face β†’ Settings β†’ Repository secrets β†’ Add "GROQ_API_KEY"
api_key = os.getenv("GROQ_API_KEY")
if not api_key:
raise ValueError("❌ GROQ_API_KEY not found. Please add it in Hugging Face Space β†’ Settings β†’ Repository secrets.")
# Initialize Groq client
client = Groq(api_key=api_key)
# Function to send prompt to Groq API
def ask_groq(user_message, model="openai/gpt-oss-120b"):
try:
response = client.chat.completions.create(
messages=[{"role": "user", "content": user_message}],
model=model,
)
return response.choices[0].message.content
except Exception as e:
return f"⚠️ Error: {str(e)}"
# Function to handle chat responses
def respond(message, chat_history):
bot_reply = ask_groq(message)
chat_history.append((message, bot_reply))
return chat_history, ""
# ============ Build Gradio UI ============
with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple", secondary_hue="cyan")) as demo:
gr.Markdown(
"""
<div style="text-align:center; font-size:2em; font-weight:700; color:#9333ea;">
⚑ Groq ChatBot ⚑
</div>
<p style="text-align:center; color:#64748b;">
A Gen-Z styled AI chat app powered by Groq LLMs.
</p>
"""
)
chatbot = gr.Chatbot(
height=500,
bubble_full_width=False,
avatar_images=(
"https://cdn-icons-png.flaticon.com/512/1077/1077012.png", # user avatar
"https://cdn-icons-png.flaticon.com/512/4712/4712109.png", # bot avatar
),
)
with gr.Row():
msg = gr.Textbox(
placeholder="Type your message...",
show_label=False,
scale=8,
container=False,
)
send = gr.Button("Send πŸš€", variant="primary", scale=1)
send.click(respond, inputs=[msg, chatbot], outputs=[chatbot, msg])
msg.submit(respond, inputs=[msg, chatbot], outputs=[chatbot, msg])
gr.Markdown(
f"""
<div style="text-align:center; color:#a3a3a3; margin-top:10px;">
<small>Powered by Groq β€’ {datetime.now().year}</small>
</div>
"""
)
# Run app
if __name__ == "__main__":
demo.launch()