aazankhanYousafzai commited on
Commit
cf21c6e
·
verified ·
1 Parent(s): 9d7c744

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -172
app.py CHANGED
@@ -2,213 +2,139 @@ import os
2
  import gradio as gr
3
  from groq import Groq
4
 
5
- # =====================================================
6
- # Groq Client Initialization (GLOBAL)
7
- # =====================================================
8
- def get_groq_client():
9
- api_key = os.getenv("GROQ_API_KEY")
10
- if not api_key:
11
- raise RuntimeError("GROQ_API_KEY not set")
12
- return Groq(api_key=api_key)
13
-
14
- client = get_groq_client()
15
-
16
- # =====================================================
17
- # Chat Logic (Gradio 6 compatible)
18
- # =====================================================
19
- def chat_with_groq(user_message, history):
20
- if not user_message or not user_message.strip():
21
- return history, ""
22
-
23
- history.append({"role": "user", "content": user_message})
24
- history.append({"role": "assistant", "content": "⚡ Groq is thinking..."})
25
-
26
- messages = [
27
- {"role": msg["role"], "content": msg["content"]}
28
- for msg in history[:-1]
29
- ]
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  try:
32
- completion = client.chat.completions.create(
33
  model="llama-3.3-70b-versatile",
34
  messages=messages,
35
  )
36
- history[-1] = {
37
- "role": "assistant",
38
- "content": completion.choices[0].message.content
39
- }
40
- except Exception as e:
41
- history[-1] = {
42
- "role": "assistant",
43
- "content": f"⚠️ Error: {str(e)}"
44
- }
45
-
46
- return history, ""
47
-
48
- # =====================================================
49
- # Clear Chat
50
- # =====================================================
51
- def clear_chat():
52
- return [], ""
53
-
54
- # =====================================================
55
- # CSS (Light/Dark + Gradio 6 UI FIX)
56
- # =====================================================
57
- custom_css = """
58
- /* ---------- Color System ---------- */
59
- :root {
60
- --bg: #f9fafb;
61
- --surface: #ffffff;
62
- --user: #2563eb;
63
- --assistant: #e5e7eb;
64
- --text: #111827;
65
- --muted: #6b7280;
66
- --border: #d1d5db;
67
- }
68
 
69
- @media (prefers-color-scheme: dark) {
70
- :root {
71
- --bg: #0b0f19;
72
- --surface: #111827;
73
- --assistant: #1f2937;
74
- --text: #f9fafb;
75
- --muted: #9ca3af;
76
- --border: #1f2937;
77
- }
78
- }
79
 
80
- /* ---------- Base Layout ---------- */
81
- body {
82
- background-color: var(--bg);
83
- }
84
 
85
- .gradio-container {
86
- max-width: 1100px !important;
87
- margin: auto;
88
- padding: 24px;
89
- overflow-x: hidden !important;
90
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
91
- }
92
 
93
- /* ---------- Typography ---------- */
94
- h1 {
95
- color: var(--text);
96
- text-align: center;
97
- font-size: 2rem;
98
- margin-bottom: 6px;
99
  }
100
 
101
- .subtitle {
102
- color: var(--muted);
103
- text-align: center;
104
- margin-bottom: 20px;
105
  }
106
 
107
- /* ---------- Chatbot ---------- */
108
- .chatbot {
109
- background: var(--surface);
110
- border-radius: 16px;
111
- padding: 16px;
112
- height: 70vh;
113
- width: 100% !important;
114
- border: 1px solid var(--border);
115
- overflow-y: auto;
116
  }
117
 
118
- /* ---------- Messages ---------- */
119
- .message {
120
- max-width: 72%;
121
- padding: 12px 14px;
122
- border-radius: 14px;
123
- margin-bottom: 10px;
124
- line-height: 1.6;
125
- font-size: 15px;
126
- box-sizing: border-box;
127
  }
128
 
129
  .message.user {
130
- background: var(--user);
131
- color: white;
132
- margin-left: auto;
133
- border-bottom-right-radius: 4px;
134
  }
135
 
136
  .message.bot {
137
- background: var(--assistant);
138
- color: var(--text);
139
- margin-right: auto;
140
- border-bottom-left-radius: 4px;
141
  }
142
 
143
- /* ---------- Input ---------- */
144
  textarea {
145
- background: var(--surface) !important;
146
- color: var(--text) !important;
147
- border: 1px solid var(--border) !important;
148
- border-radius: 12px !important;
149
- padding: 12px !important;
150
- font-size: 15px;
151
- }
152
-
153
- textarea::placeholder {
154
- color: var(--muted);
155
  }
156
 
157
- /* ---------- Buttons ---------- */
158
  button {
159
- background: var(--user) !important;
160
- color: white !important;
161
- border-radius: 12px !important;
162
- padding: 10px 16px !important;
163
- font-weight: 600 !important;
164
  }
165
-
166
- button:hover {
167
- opacity: 0.9;
168
- }
169
-
170
- /* ---------- GRADIO 6 FIXES ---------- */
171
- .chatbot-toolbar,
172
- .chatbot-actions,
173
- button[aria-label="Copy"],
174
- button[aria-label="Share"],
175
- button[aria-label="Clear"] {
176
- display: none !important;
177
- }
178
-
179
- .chatbot .scroll-to-bottom {
180
- right: 16px !important;
181
- bottom: 80px !important;
182
  }
183
  """
184
 
185
- # =====================================================
186
- # Gradio UI
187
- # =====================================================
188
- with gr.Blocks(title="GROQ AI CHATBOT") as demo:
189
- gr.Markdown("# 🤖 GROQ AI CHATBOT")
190
- gr.Markdown(
191
- "<div class='subtitle'>Fast, reliable AI powered by Groq & LLaMA-3.3</div>"
192
- )
193
-
194
- chatbot = gr.Chatbot(elem_classes="chatbot")
195
- state = gr.State([])
196
 
197
  with gr.Row():
198
- txt = gr.Textbox(
199
- placeholder="Type your message",
200
  show_label=False,
201
- scale=5,
202
  )
203
  send = gr.Button("Send", scale=1)
204
- clear = gr.Button("Clear", scale=1)
205
 
206
- send.click(chat_with_groq, [txt, state], [chatbot, txt])
207
- txt.submit(chat_with_groq, [txt, state], [chatbot, txt])
208
- clear.click(clear_chat, outputs=[chatbot, txt], show_progress=False)
 
 
209
 
210
- # =====================================================
211
- # Launch (Gradio 6)
212
- # =====================================================
213
- if __name__ == "__main__":
214
- demo.launch(css=custom_css)
 
2
  import gradio as gr
3
  from groq import Groq
4
 
5
+ # Initialize Groq client
6
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
7
+
8
+ def normalize_chat_history(chat_history):
9
+ """
10
+ Converts chat_history into list of tuples (user, assistant)
11
+ Works with both tuple and dict formats returned by Gradio.
12
+ """
13
+ normalized = []
14
+ for item in chat_history:
15
+ if isinstance(item, dict):
16
+ # If it's a dict, convert accordingly
17
+ if item.get("role") == "user":
18
+ normalized.append((item.get("content"), ""))
19
+ elif item.get("role") == "assistant":
20
+ # merge assistant into last user entry
21
+ if normalized:
22
+ last_user, _ = normalized[-1]
23
+ normalized[-1] = (last_user, item.get("content"))
24
+ elif isinstance(item, (list, tuple)) and len(item) == 2:
25
+ normalized.append((item[0], item[1]))
26
+ return normalized
27
+
28
+ def chat_with_groq(user_input, chat_history):
29
+ if not user_input.strip():
30
+ return chat_history, ""
31
+
32
+ chat_history = normalize_chat_history(chat_history)
33
+
34
+ messages = []
35
+ for u, a in chat_history:
36
+ if u:
37
+ messages.append({"role": "user", "content": u})
38
+ if a:
39
+ messages.append({"role": "assistant", "content": a})
40
+
41
+ messages.append({"role": "user", "content": user_input})
42
 
43
  try:
44
+ chat_completion = client.chat.completions.create(
45
  model="llama-3.3-70b-versatile",
46
  messages=messages,
47
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ assistant_response = chat_completion.choices[0].message.content
50
+ chat_history.append((user_input, assistant_response))
 
 
 
 
 
 
 
 
51
 
52
+ except Exception as e:
53
+ chat_history.append((user_input, f"❌ Error: {e}"))
 
 
54
 
55
+ return chat_history, ""
 
 
 
 
 
 
56
 
57
+ # UI Styling
58
+ custom_css = """
59
+ .gradio-container {
60
+ max-width: 1000px;
61
+ margin: auto;
62
+ padding: 16px;
63
  }
64
 
65
+ body {
66
+ background: #f8f9fa;
67
+ color: #1f2937;
68
+ font-family: 'Inter', sans-serif;
69
  }
70
 
71
+ h1 {
72
+ color: #0b4f99;
73
+ font-weight: bold;
74
+ font-size: 2rem;
75
+ text-align: center;
76
+ margin-bottom: 12px;
 
 
 
77
  }
78
 
79
+ #chatbot {
80
+ background: #ffffff;
81
+ border: 1px solid #d1d5db;
82
+ border-radius: 12px;
83
+ padding: 12px;
84
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
 
 
 
85
  }
86
 
87
  .message.user {
88
+ background: #0b4f99;
89
+ color: #ffffff;
90
+ border-radius: 16px;
91
+ padding: 8px;
92
  }
93
 
94
  .message.bot {
95
+ background: #e5e7eb;
96
+ color: #1f2937;
97
+ border-radius: 16px;
98
+ padding: 8px;
99
  }
100
 
 
101
  textarea {
102
+ width: 100%;
103
+ border: 2px solid #6b7280;
104
+ border-radius: 8px;
105
+ padding: 8px;
106
+ font-size: 1rem;
107
+ color: #1f2937;
 
 
 
 
108
  }
109
 
 
110
  button {
111
+ background: #0b4f99;
112
+ color: #ffffff;
113
+ font-weight: bold;
114
+ border-radius: 8px;
115
+ padding: 12px 20px;
116
  }
117
+ button:hover, button:focus {
118
+ background: #093c77;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  }
120
  """
121
 
122
+ with gr.Blocks(css=custom_css) as demo:
123
+ gr.Markdown("<h1>🌐 Groq ChatBot</h1>")
124
+ chatbot = gr.Chatbot(elem_id="chatbot", height=450)
 
 
 
 
 
 
 
 
125
 
126
  with gr.Row():
127
+ msg = gr.Textbox(
128
+ placeholder="💬 Type your message here...",
129
  show_label=False,
130
+ scale=4,
131
  )
132
  send = gr.Button("Send", scale=1)
 
133
 
134
+ clear = gr.Button("Clear Chat")
135
+
136
+ send.click(chat_with_groq, [msg, chatbot], [chatbot, msg])
137
+ msg.submit(chat_with_groq, [msg, chatbot], [chatbot, msg])
138
+ clear.click(lambda: [], None, chatbot)
139
 
140
+ demo.launch()