Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| from groq import Groq | |
| # ----------------------------- | |
| # Groq Client (HF Secrets) | |
| # ----------------------------- | |
| api_key = os.environ.get("GROQ_API_KEY") | |
| if not api_key: | |
| raise RuntimeError( | |
| "GROQ_API_KEY is not set. Add it in Hugging Face Spaces → Settings → Secrets." | |
| ) | |
| client = Groq(api_key=api_key) | |
| # ----------------------------- | |
| # Chat Function | |
| # ----------------------------- | |
| def chat(user_input, history): | |
| if not user_input or not user_input.strip(): | |
| return history, "" | |
| # Keep only valid messages for Groq | |
| messages = [{"role": m["role"], "content": m["content"]} | |
| for m in history if "role" in m and "content" in m] | |
| # Add latest user message | |
| messages.append({"role": "user", "content": user_input}) | |
| try: | |
| completion = client.chat.completions.create( | |
| model="llama-3.3-70b-versatile", | |
| messages=messages | |
| ) | |
| assistant_reply = completion.choices[0].message.content | |
| except Exception as e: | |
| assistant_reply = f"⚠️ Error: {str(e)}" | |
| # Add assistant reply to messages | |
| messages.append({"role": "assistant", "content": assistant_reply}) | |
| return messages, "" | |
| # ----------------------------- | |
| # Theme & CSS | |
| # ----------------------------- | |
| theme = gr.themes.Soft( | |
| primary_hue="blue", | |
| secondary_hue="gray", | |
| neutral_hue="gray", | |
| font=["Inter", "sans-serif"] | |
| ) | |
| custom_css = """ | |
| #container { | |
| max-width: 900px; | |
| margin: auto; | |
| } | |
| footer {display: none;} | |
| """ | |
| # ----------------------------- | |
| # UI | |
| # ----------------------------- | |
| with gr.Blocks() as demo: | |
| with gr.Column(elem_id="container"): | |
| gr.Markdown( | |
| """ | |
| # 🤖 Groq AI Chatbot | |
| **Fast • Responsive • HCI-Friendly Interface** | |
| """ | |
| ) | |
| # ✅ Just remove type="messages" | |
| chatbot = gr.Chatbot( | |
| height=420, | |
| show_label=False | |
| ) | |
| with gr.Row(): | |
| user_input = gr.Textbox( | |
| placeholder="Type your message here…", | |
| show_label=False | |
| ) | |
| send_btn = gr.Button("Send", variant="primary") | |
| with gr.Row(): | |
| clear_btn = gr.Button("Clear Chat", variant="secondary") | |
| send_btn.click(chat, [user_input, chatbot], [chatbot, user_input]) | |
| user_input.submit(chat, [user_input, chatbot], [chatbot, user_input]) | |
| clear_btn.click(lambda: [], None, chatbot) | |
| # ----------------------------- | |
| # Launch | |
| # ----------------------------- | |
| demo.launch(theme=theme, css=custom_css) |