adikwok commited on
Commit
f213ab0
Β·
verified Β·
1 Parent(s): 013d3ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -85
app.py CHANGED
@@ -74,26 +74,10 @@ def groq_with_memory(message: str, topic: str = "general", summarize: bool = Fal
74
  except Exception as e:
75
  return f"❌ Error: {str(e)}"
76
 
77
- def chat_with_groq(message: str, history: List[List[str]], topic: str = "general", summarize: bool = False) -> tuple:
78
- """
79
- Function for Gradio Chatbot
80
- Returns: (updated_history, empty_string_for_textbox)
81
- """
82
- if not message.strip():
83
- return history, ""
84
-
85
- # Get response from Groq
86
- response = groq_with_memory(message, topic, summarize)
87
-
88
- # Add to gradio chat history format
89
- history.append([message, response])
90
-
91
- return history, ""
92
-
93
- def clear_chat():
94
- """Clear both chat histories"""
95
  chat_history.clear()
96
- return [], "βœ… Chat history cleared"
97
 
98
  def view_history(topic: str = None):
99
  """View chat history with optional topic filter"""
@@ -102,7 +86,7 @@ def view_history(topic: str = None):
102
 
103
  filtered = [msg for msg in chat_history if topic is None or msg.get("topic") == topic]
104
  return "\n".join(
105
- f"[{msg.get('timestamp', 'N/A')}] {msg['role'].capitalize()}: {msg['content']}"
106
  for msg in filtered
107
  )
108
 
@@ -116,120 +100,157 @@ def manual_curl_example():
116
  -d '{{"model": "llama-3.3-70b-versatile", "messages": [{{"role": "user", "content": "Hello"}}], "max_tokens": 1000}}'
117
  """
118
 
 
 
 
 
 
 
 
 
119
  # Gradio Interface
120
- with gr.Blocks(title="Groq Chat Debugger", theme=gr.themes.Soft()) as demo:
121
  gr.Markdown("## πŸ’¬ Groq API Chat Interface")
122
 
123
  with gr.Tab("πŸ’¬ Chat"):
 
 
 
 
 
 
 
 
 
 
 
 
124
  with gr.Row():
125
  with gr.Column(scale=3):
126
- # Main chatbot interface
127
- chatbot = gr.Chatbot(
128
- label="Chat with Groq",
129
- height=500,
130
- show_copy_button=True
131
  )
132
-
133
- with gr.Row():
134
- msg_input = gr.Textbox(
135
- label="Your Message",
136
- placeholder="Ketik pesan Anda di sini...",
137
- scale=4
138
- )
139
- send_btn = gr.Button("Send πŸ“€", variant="primary", scale=1)
140
-
141
  with gr.Column(scale=1):
142
- # Settings panel
143
- gr.Markdown("### βš™οΈ Settings")
144
  topic_input = gr.Textbox(
145
- label="Topic",
146
  value="general",
147
- placeholder="general"
148
  )
149
  summarize_cb = gr.Checkbox(
150
  label="πŸ“‹ Summarize conversation",
151
  value=False
152
  )
153
- clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="stop")
154
-
155
- # Stats
156
- gr.Markdown("### πŸ“Š Stats")
157
- stats_output = gr.Textbox(
158
- label="Chat Stats",
159
- value=f"API Status: {'βœ… Ready' if API_KEY else '❌ No Key'}",
160
- interactive=False,
161
- lines=3
162
- )
163
 
164
  # Event handlers
165
  send_btn.click(
166
- chat_with_groq,
167
- inputs=[msg_input, chatbot, topic_input, summarize_cb],
168
- outputs=[chatbot, msg_input]
169
  )
170
 
171
- msg_input.submit( # Enter key support
172
- chat_with_groq,
173
- inputs=[msg_input, chatbot, topic_input, summarize_cb],
174
- outputs=[chatbot, msg_input]
 
175
  )
176
 
177
  clear_btn.click(
178
- clear_chat,
179
- outputs=[chatbot, stats_output]
180
  )
181
 
182
  with gr.Tab("πŸ“œ History"):
183
- gr.Markdown("### View and manage your chat history")
 
184
  with gr.Row():
185
  history_topic = gr.Textbox(
186
- label="Filter by Topic",
187
- placeholder="Leave empty to see all"
188
  )
189
  view_btn = gr.Button("πŸ‘€ View History", variant="primary")
 
190
 
191
  history_output = gr.Textbox(
192
- label="Chat History",
193
- lines=15,
194
- interactive=False
 
195
  )
196
 
197
- view_btn.click(
198
- view_history,
199
- inputs=[history_topic],
200
- outputs=[history_output]
201
- )
202
 
203
  with gr.Tab("πŸ”§ API Tools"):
204
- gr.Markdown(f"""
205
- ### API Configuration
206
- **Status:** {'βœ… Connected' if API_KEY else '❌ No API Key Set'}
207
- **Endpoint:** `{API_URL}`
208
- **Available Models:**
209
- - `llama-3.3-70b-versatile` (Default)
210
- - `llama3-8b-8192`
211
- - `mixtral-8x7b-32768`
 
 
 
212
  """)
213
 
214
- curl_btn = gr.Button("πŸ“‹ Generate cURL Example")
 
 
215
  curl_output = gr.Code(
216
  label="cURL Command",
217
- language="shell",
218
- lines=8
 
219
  )
220
  curl_btn.click(manual_curl_example, outputs=[curl_output])
221
 
 
222
  if not API_KEY:
223
  gr.Markdown("""
224
- ### ⚠️ Setup Instructions
225
- 1. Get your API key from [Groq Console](https://console.groq.com/)
226
- 2. Set environment variable: `export GROQ_API_KEY="your-key-here"`
227
- 3. Restart the application
 
 
 
 
 
 
 
228
  """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
  if __name__ == "__main__":
231
  demo.launch(
232
  server_name="0.0.0.0",
233
  server_port=7860,
234
- share=False # Set True if you want public link
235
  )
 
74
  except Exception as e:
75
  return f"❌ Error: {str(e)}"
76
 
77
+ def clear_history():
78
+ """Clear the chat history"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  chat_history.clear()
80
+ return "βœ… Chat history cleared", ""
81
 
82
  def view_history(topic: str = None):
83
  """View chat history with optional topic filter"""
 
86
 
87
  filtered = [msg for msg in chat_history if topic is None or msg.get("topic") == topic]
88
  return "\n".join(
89
+ f"[{msg['timestamp']}] {msg['role'].capitalize()}: {msg['content']}"
90
  for msg in filtered
91
  )
92
 
 
100
  -d '{{"model": "llama-3.3-70b-versatile", "messages": [{{"role": "user", "content": "Hello"}}], "max_tokens": 1000}}'
101
  """
102
 
103
+ def process_message(message: str, topic: str, summarize: bool):
104
+ """Process message and clear input"""
105
+ if not message.strip():
106
+ return "❌ Please enter a message", ""
107
+
108
+ response = groq_with_memory(message, topic, summarize)
109
+ return response, ""
110
+
111
  # Gradio Interface
112
+ with gr.Blocks(title="Groq Chat Interface", theme=gr.themes.Soft()) as demo:
113
  gr.Markdown("## πŸ’¬ Groq API Chat Interface")
114
 
115
  with gr.Tab("πŸ’¬ Chat"):
116
+ # Response area at top
117
+ response_output = gr.Textbox(
118
+ label="πŸ€– AI Response",
119
+ lines=15,
120
+ interactive=False,
121
+ placeholder="AI responses will appear here...",
122
+ show_copy_button=True
123
+ )
124
+
125
+ gr.Markdown("---")
126
+
127
+ # Input area at bottom
128
  with gr.Row():
129
  with gr.Column(scale=3):
130
+ msg_input = gr.Textbox(
131
+ label="✍️ Your Message",
132
+ placeholder="Type your message here...",
133
+ lines=3,
134
+ max_lines=10
135
  )
136
+
 
 
 
 
 
 
 
 
137
  with gr.Column(scale=1):
 
 
138
  topic_input = gr.Textbox(
139
+ label="🏷️ Topic",
140
  value="general",
141
+ placeholder="conversation topic"
142
  )
143
  summarize_cb = gr.Checkbox(
144
  label="πŸ“‹ Summarize conversation",
145
  value=False
146
  )
147
+
148
+ with gr.Row():
149
+ send_btn = gr.Button("πŸ“€ Send Message", variant="primary", scale=2)
150
+ clear_btn = gr.Button("πŸ—‘οΈ Clear Response", variant="secondary", scale=1)
 
 
 
 
 
 
151
 
152
  # Event handlers
153
  send_btn.click(
154
+ process_message,
155
+ inputs=[msg_input, topic_input, summarize_cb],
156
+ outputs=[response_output, msg_input]
157
  )
158
 
159
+ # Enter key support (Shift+Enter for new line, Enter to send)
160
+ msg_input.submit(
161
+ process_message,
162
+ inputs=[msg_input, topic_input, summarize_cb],
163
+ outputs=[response_output, msg_input]
164
  )
165
 
166
  clear_btn.click(
167
+ lambda: ("", ""),
168
+ outputs=[response_output, msg_input]
169
  )
170
 
171
  with gr.Tab("πŸ“œ History"):
172
+ gr.Markdown("### Chat History Management")
173
+
174
  with gr.Row():
175
  history_topic = gr.Textbox(
176
+ label="πŸ” Filter by Topic",
177
+ placeholder="Leave empty to see all conversations"
178
  )
179
  view_btn = gr.Button("πŸ‘€ View History", variant="primary")
180
+ clear_history_btn = gr.Button("πŸ—‘οΈ Clear All History", variant="stop")
181
 
182
  history_output = gr.Textbox(
183
+ label="πŸ“š Chat History",
184
+ lines=20,
185
+ interactive=False,
186
+ show_copy_button=True
187
  )
188
 
189
+ view_btn.click(view_history, inputs=[history_topic], outputs=[history_output])
190
+ clear_history_btn.click(clear_history, outputs=[history_output, response_output])
 
 
 
191
 
192
  with gr.Tab("πŸ”§ API Tools"):
193
+ gr.Markdown("### API Configuration & Testing")
194
+
195
+ # API Status
196
+ api_status = gr.Markdown(f"""
197
+ **πŸ”Œ API Status:** {'βœ… Ready' if API_KEY else '❌ No API Key Set'}
198
+ **🌐 Endpoint:** `{API_URL}`
199
+ **πŸ€– Available Models:**
200
+ - `llama-3.3-70b-versatile` (Default - Most Capable)
201
+ - `llama3-8b-8192` (Fast)
202
+ - `llama3-70b-8192` (Balanced)
203
+ - `mixtral-8x7b-32768` (Long Context)
204
  """)
205
 
206
+ # cURL Generator
207
+ gr.Markdown("### πŸ“‹ Generate cURL Command")
208
+ curl_btn = gr.Button("πŸ“‹ Generate cURL Example", variant="primary")
209
  curl_output = gr.Code(
210
  label="cURL Command",
211
+ language="bash",
212
+ lines=8,
213
+ show_copy_button=True
214
  )
215
  curl_btn.click(manual_curl_example, outputs=[curl_output])
216
 
217
+ # Setup Instructions
218
  if not API_KEY:
219
  gr.Markdown("""
220
+ ### ⚠️ Setup Required
221
+
222
+ **To use this interface:**
223
+ 1. πŸ”‘ Get your API key from [Groq Console](https://console.groq.com/)
224
+ 2. πŸ’» Set environment variable:
225
+ ```bash
226
+ export GROQ_API_KEY="your-groq-api-key-here"
227
+ ```
228
+ 3. πŸ”„ Restart the application
229
+
230
+ **Alternative:** Set in your system environment or `.env` file
231
  """)
232
+ else:
233
+ gr.Markdown("""
234
+ ### βœ… Ready to Chat!
235
+
236
+ **Tips for better conversations:**
237
+ - 🎯 Use specific topics to organize conversations
238
+ - πŸ“‹ Enable summarization for long conversations
239
+ - πŸ”„ Check history to review past interactions
240
+ - πŸ’‘ Try different models in the API for various needs
241
+ """)
242
+
243
+ # Launch message
244
+ print("πŸš€ Starting Groq Chat Interface...")
245
+ print(f"🌐 Access at: http://localhost:7860")
246
+ if API_KEY:
247
+ print("βœ… API Key detected - Ready to chat!")
248
+ else:
249
+ print("⚠️ No API Key found - Please set GROQ_API_KEY environment variable")
250
 
251
  if __name__ == "__main__":
252
  demo.launch(
253
  server_name="0.0.0.0",
254
  server_port=7860,
255
+ show_error=True
256
  )