import os import gradio as gr from groq import Groq # --------------------------- # Load API Key from Hugging Face Secrets # --------------------------- GROQ_API_KEY = os.environ.get("GROQ_API_KEY") if not GROQ_API_KEY: raise ValueError("GROQ_API_KEY not found. Add it in Space Settings → Secrets.") client = Groq(api_key=GROQ_API_KEY) print("Groq Client Ready 🚀") # --------------------------- # Helper to convert Gradio's message dict to simple format for Groq # --------------------------- def convert_to_groq_messages(gradio_history): groq_messages = [] for msg in gradio_history: role = msg.get("role") content = msg.get("content") # Gradio 6 may send content as a list of parts (for multimodal) if isinstance(content, list): # Extract text from parts with type "text" text_parts = [part.get("text", "") for part in content if part.get("type") == "text"] content = " ".join(text_parts) elif content is None: continue # Ensure content is a string groq_messages.append({"role": role, "content": str(content)}) return groq_messages # --------------------------- # Core chat function – accepts a list of message dicts (Gradio format) # --------------------------- def chat_with_groq(history): try: groq_messages = convert_to_groq_messages(history) print("Sending messages to Groq:", groq_messages) chat_completion = client.chat.completions.create( messages=groq_messages, model="openai/gpt-oss-120b", # or your preferred model ) reply = chat_completion.choices[0].message.content return reply except Exception as e: import traceback traceback.print_exc() return f"❌ Error: {str(e)}" # --------------------------- # Gradio UI (unchanged) # --------------------------- custom_css = """ body { background: linear-gradient(135deg, #667eea, #764ba2, #ff6ec4); font-family: 'Poppins', sans-serif; } .gradio-container { background: transparent !important; } #chatbox { backdrop-filter: blur(20px); background: rgba(255, 255, 255, 0.1); border-radius: 20px; padding: 15px; box-shadow: 0px 8px 32px rgba(0, 0, 0, 0.3); } textarea { border-radius: 15px !important; } button { background: linear-gradient(90deg, #ff6ec4, #7873f5) !important; color: white !important; border-radius: 12px !important; font-weight: bold !important; border: none !important; } button:hover { opacity: 0.85 !important; } """ with gr.Blocks() as demo: gr.Markdown( """

🤖 Groq Gen-Z Chatbot

Fast. Smart. Stylish. ⚡

""" ) chatbot = gr.Chatbot(elem_id="chatbox", height=450) msg = gr.Textbox(placeholder="Type something cool...", scale=8) clear = gr.Button("✨ Clear Chat") def user_message(message, history): history.append({"role": "user", "content": message}) return "", history def bot_response(history): reply = chat_with_groq(history) history.append({"role": "assistant", "content": reply}) return history msg.submit(user_message, [msg, chatbot], [msg, chatbot]).then( bot_response, chatbot, chatbot ) clear.click(lambda: [], None, chatbot, queue=False) demo.launch(theme=gr.themes.Soft(), css=custom_css)