aazankhanYousafzai commited on
Commit
fa370b9
·
verified ·
1 Parent(s): 59ff455

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -100
app.py CHANGED
@@ -2,139 +2,183 @@ import os
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()
 
 
 
 
 
2
  import gradio as gr
3
  from groq import Groq
4
 
5
+ # =====================================================
6
+ # Groq Client Initialization
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
+ # SAFE CSS (Fixes Vertical Text Bug)
56
+ # =====================================================
57
+ custom_css = """
58
+ /* RESET ONLY INSIDE CHATBOT */
59
+ .chatbot * {
60
+ all: unset;
61
+ }
62
 
63
+ /* RESTORE MESSAGE STRUCTURE */
64
+ .chatbot .message,
65
+ .chatbot .message * {
66
+ all: revert;
67
+ }
68
 
69
+ /* COLOR SYSTEM */
70
+ :root {
71
+ --bg: #0b0f19;
72
+ --surface: #111827;
73
+ --user: #2563eb;
74
+ --assistant: #1f2937;
75
+ --text: #f9fafb;
76
+ --muted: #9ca3af;
77
+ --border: #1f2937;
78
  }
79
 
80
  body {
81
+ background-color: var(--bg);
 
 
82
  }
83
 
84
+ .gradio-container {
85
+ max-width: 1100px !important;
86
+ margin: auto;
87
+ padding: 24px;
88
+ overflow-x: hidden !important;
89
+ font-family: system-ui, sans-serif;
90
+ }
91
+
92
+ /* CHAT WINDOW */
93
+ .chatbot {
94
+ background: var(--surface);
95
+ border-radius: 16px;
96
+ padding: 16px;
97
+ height: 70vh;
98
+ width: 100% !important;
99
+ border: 1px solid var(--border);
100
+ overflow-y: auto;
101
  }
102
 
103
+ /* MESSAGES */
104
+ .chatbot .message {
105
+ display: block !important;
106
+ max-width: 72%;
107
+ padding: 12px 14px;
108
+ border-radius: 14px;
109
+ margin-bottom: 10px;
110
+ line-height: 1.6;
111
+ font-size: 15px;
112
+ white-space: pre-wrap !important;
113
+ word-break: normal !important;
114
  }
115
 
116
+ .chatbot .message.user {
117
+ background: var(--user);
118
+ color: white;
119
+ margin-left: auto;
 
120
  }
121
 
122
+ .chatbot .message.bot {
123
+ background: var(--assistant);
124
+ color: var(--text);
125
+ margin-right: auto;
 
126
  }
127
 
128
+ /* INPUT */
129
  textarea {
130
+ background: var(--surface) !important;
131
+ color: var(--text) !important;
132
+ border: 1px solid var(--border) !important;
133
+ border-radius: 12px !important;
134
+ padding: 12px !important;
135
+ font-size: 15px;
136
  }
137
 
138
+ /* BUTTONS */
139
  button {
140
+ background: var(--user) !important;
141
+ color: white !important;
142
+ border-radius: 12px !important;
143
+ padding: 10px 16px !important;
144
+ font-weight: 600 !important;
145
  }
146
+
147
+ /* REMOVE FLOATING ICONS */
148
+ .chatbot-toolbar,
149
+ .chatbot-actions,
150
+ button[aria-label="Copy"],
151
+ button[aria-label="Share"],
152
+ button[aria-label="Clear"] {
153
+ display: none !important;
154
  }
155
  """
156
 
157
+ # =====================================================
158
+ # Gradio UI
159
+ # =====================================================
160
+ with gr.Blocks(title="GROQ AI CHATBOT") as demo:
161
+ gr.Markdown("# 🤖 GROQ AI CHATBOT")
162
+ gr.Markdown("<div class='subtitle'>Fast, reliable AI powered by Groq</div>")
163
+
164
+ chatbot = gr.Chatbot(elem_classes="chatbot")
165
+ state = gr.State([])
166
 
167
  with gr.Row():
168
+ txt = gr.Textbox(
169
+ placeholder="Type your message",
170
  show_label=False,
171
+ scale=5,
172
  )
173
  send = gr.Button("Send", scale=1)
174
+ clear = gr.Button("Clear", scale=1)
175
 
176
+ send.click(chat_with_groq, [txt, state], [chatbot, txt])
177
+ txt.submit(chat_with_groq, [txt, state], [chatbot, txt])
178
+ clear.click(clear_chat, outputs=[chatbot, txt], show_progress=False)
 
 
179
 
180
+ # =====================================================
181
+ # Launch
182
+ # =====================================================
183
+ if __name__ == "__main__":
184
+ demo.launch(css=custom_css)