File size: 2,385 Bytes
cfdc4be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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()