File size: 3,561 Bytes
38514fb
 
 
 
6834052
 
 
38514fb
 
8c878ce
38514fb
 
3a92392
38514fb
6834052
fbbadd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6834052
e55e1b0
8c878ce
fbbadd1
 
8c878ce
fbbadd1
83ed55d
38514fb
8c878ce
 
38514fb
c9f4ade
fbbadd1
c9f4ade
38514fb
6834052
fbbadd1
6834052
38514fb
 
 
8c878ce
 
 
 
38514fb
 
 
8c878ce
38514fb
 
6f0bf21
38514fb
8c878ce
 
 
38514fb
8c878ce
 
 
 
 
6f0bf21
 
8c878ce
38514fb
 
 
e55e1b0
6834052
8c878ce
 
 
 
 
 
 
 
6834052
 
b62c735
8c878ce
38514fb
 
8c878ce
e55e1b0
 
8c878ce
 
e55e1b0
 
8c878ce
 
 
 
 
 
 
38514fb
3a92392
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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(
        """
        <h1 style='text-align: center; color: white;'>
        🤖 Groq Gen-Z Chatbot
        </h1>
        <p style='text-align: center; color: white; font-size: 18px;'>
        Fast. Smart. Stylish. ⚡
        </p>
        """
    )

    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)