TKM03 commited on
Commit
cc4536c
·
verified ·
1 Parent(s): 49d71b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -167
app.py CHANGED
@@ -19,7 +19,7 @@ logging.basicConfig(
19
  logger = logging.getLogger("CompanyChatbot")
20
 
21
  # Environment variables
22
- HF_MODEL = os.environ.get("HF_MODEL", "MaziyarPanahi/calme-3.2-instruct-78b")
23
  HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
24
  COMPANY_NAME = os.environ.get("COMPANY_NAME", "AI")
25
  DEFAULT_SYSTEM_PROMPT = os.environ.get("DEFAULT_SYSTEM_PROMPT",
@@ -27,7 +27,7 @@ DEFAULT_SYSTEM_PROMPT = os.environ.get("DEFAULT_SYSTEM_PROMPT",
27
 
28
  # Validate API token
29
  if not HF_API_TOKEN:
30
- raise RuntimeError("HF_API_TOKEN environment variable is not set. Please configure it in Spaces settings.")
31
 
32
  # Initialize the client
33
  try:
@@ -35,7 +35,7 @@ try:
35
  logger.info(f"Successfully initialized InferenceClient with model: {HF_MODEL}")
36
  except Exception as e:
37
  logger.error(f"Failed to initialize InferenceClient: {str(e)}")
38
- raise RuntimeError(f"Failed to initialize the model. Please check your configuration: {str(e)}")
39
 
40
  # Configuration state management
41
  class ConfigState:
@@ -58,11 +58,12 @@ def save_conversation(user_id, conversation):
58
  # Main chat function
59
  def respond(message, chat_history, user_id):
60
  if not message.strip():
61
- return chat_history + [[message, "I'm sorry, I didn't receive any input. How can I help you today?"]]
62
 
63
  logger.info(f"User {user_id} sent message - Length: {len(message)}")
64
 
65
  try:
 
66
  messages = [{"role": "system", "content": config_state.system_message}]
67
 
68
  for user_msg, assistant_msg in chat_history:
@@ -110,7 +111,7 @@ def respond(message, chat_history, user_id):
110
  except Exception as e:
111
  error_msg = f"An error occurred: {str(e)}"
112
  logger.error(f"Error generating response for user {user_id}: {str(e)}")
113
- return chat_history + [[message, error_msg]]
114
 
115
  # Configuration update functions
116
  def update_config(system_msg, max_tok, temp, tp, role):
@@ -165,86 +166,23 @@ def login(username, password):
165
  gr.update(visible=True, value="Invalid username or password")
166
  )
167
 
168
- # CSS styling
169
  css = """
170
- body {
171
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
172
- background-color: #f9f9f9;
173
- }
174
- .container {
175
- max-width: 1400px !important;
176
- margin: auto;
177
- }
178
- .setting-panel {
179
- background-color: #f0f4f8;
180
- border-radius: 10px;
181
- padding: 15px;
182
- box-shadow: 0 2px 6px rgba(0,0,0,0.1);
183
- }
184
- .chat-container {
185
- border-radius: 10px;
186
- box-shadow: 0 2px 6px rgba(0,0,0,0.1);
187
- background-color: white;
188
- }
189
- .company-header {
190
- background-color: #2c3e50;
191
- color: white;
192
- padding: 15px;
193
- border-radius: 10px 10px 0 0;
194
- margin-bottom: 15px;
195
- }
196
- .footer {
197
- text-align: center;
198
- margin-top: 20px;
199
- color: #666;
200
- font-size: 0.8em;
201
- }
202
- .message-user {
203
- background-color: #e6f7ff !important;
204
- border-radius: 15px 15px 0 15px !important;
205
- }
206
- .message-bot {
207
- background-color: #f0f0f0 !important;
208
- border-radius: 15px 15px 15px 0 !important;
209
- }
210
- .login-container {
211
- max-width: 500px;
212
- margin: 50px auto;
213
- padding: 30px;
214
- background-color: white;
215
- border-radius: 10px;
216
- box-shadow: 0 4px 10px rgba(0,0,0,0.1);
217
- }
218
- .login-header {
219
- text-align: center;
220
- margin-bottom: 30px;
221
- }
222
- .error-message {
223
- color: #e74c3c;
224
- background-color: #fdedeb;
225
- padding: 10px;
226
- border-radius: 5px;
227
- margin-bottom: 15px;
228
- font-size: 14px;
229
- }
230
- .role-badge {
231
- font-size: 12px;
232
- padding: 3px 8px;
233
- border-radius: 10px;
234
- margin-left: 10px;
235
- }
236
- .admin-badge {
237
- background-color: #e74c3c;
238
- color: white;
239
- }
240
- .user-badge {
241
- background-color: #3498db;
242
- color: white;
243
- }
244
- .setting-disabled {
245
- opacity: 0.5;
246
- pointer-events: none;
247
- }
248
  """
249
 
250
  # Main application
@@ -267,58 +205,24 @@ with gr.Blocks(css=css, title=f"{COMPANY_NAME} AI Assistant") as demo:
267
  with gr.Row():
268
  with gr.Column(scale=1, elem_classes=["setting-panel"]):
269
  role_indicator = gr.Markdown("", elem_id="role-indicator")
270
-
271
  gr.Markdown("### Configuration")
272
  with gr.Group() as config_group:
273
- system_message = gr.Textbox(
274
- value=DEFAULT_SYSTEM_PROMPT,
275
- label="System Instructions",
276
- lines=4,
277
- interactive=False
278
- )
279
- max_tokens = gr.Slider(
280
- minimum=1,
281
- maximum=2048,
282
- value=512,
283
- step=1,
284
- label="Max Response Length",
285
- interactive=False
286
- )
287
- temperature = gr.Slider(
288
- minimum=0.1,
289
- maximum=1.0,
290
- value=0.7,
291
- step=0.1,
292
- label="Temperature",
293
- interactive=False
294
- )
295
- top_p = gr.Slider(
296
- minimum=0.1,
297
- maximum=1.0,
298
- value=0.95,
299
- step=0.05,
300
- label="Top-p",
301
- interactive=False
302
- )
303
-
304
  update_config_btn = gr.Button("Update Configuration", visible=False)
305
  config_status = gr.Markdown("")
306
-
307
  gr.Markdown("### Chat Actions")
308
  with gr.Row():
309
  clear_btn = gr.Button("Clear Chat", variant="secondary")
310
  export_btn = gr.Button("Export Conversation", variant="secondary")
311
-
312
  logout_btn = gr.Button("Logout", variant="stop")
313
 
314
  with gr.Column(scale=2, elem_classes=["chat-container"]):
315
  chatbot = gr.Chatbot(elem_classes=["chatbox"])
316
  with gr.Row():
317
- msg = gr.Textbox(
318
- show_label=False,
319
- placeholder="Type your message here...",
320
- container=False
321
- )
322
  submit_btn = gr.Button("Send", variant="primary")
323
 
324
  def update_role_display(role):
@@ -336,37 +240,15 @@ with gr.Blocks(css=css, title=f"{COMPANY_NAME} AI Assistant") as demo:
336
  gr.update(visible=is_admin),
337
  ]
338
 
339
- login_button.click(
340
- login,
341
- inputs=[username, password],
342
- outputs=[login_group, chat_group, user_id, user_role, error_message]
343
- ).then(
344
- update_role_display,
345
- inputs=[user_role],
346
- outputs=[role_indicator]
347
- ).then(
348
- handle_role_permissions,
349
- inputs=[user_role],
350
- outputs=[system_message, max_tokens, temperature, top_p, update_config_btn]
351
- )
352
 
353
- update_config_btn.click(
354
- update_config,
355
- inputs=[system_message, max_tokens, temperature, top_p, user_role],
356
- outputs=[config_status]
357
- )
358
 
359
- msg.submit(
360
- respond,
361
- inputs=[msg, chatbot, user_id],
362
- outputs=[chatbot]
363
- ).then(lambda: "", None, [msg])
364
 
365
- submit_btn.click(
366
- respond,
367
- inputs=[msg, chatbot, user_id],
368
- outputs=[chatbot]
369
- ).then(lambda: "", None, [msg])
370
 
371
  clear_btn.click(lambda: [], None, chatbot, queue=False)
372
 
@@ -379,25 +261,12 @@ with gr.Blocks(css=css, title=f"{COMPANY_NAME} AI Assistant") as demo:
379
  logger.info(f"Exported conversation for user {uid}")
380
  return gr.update(value=f"Conversation exported to {filename}", visible=True)
381
 
382
- export_btn.click(
383
- export_conversation,
384
- inputs=[chatbot, user_id],
385
- outputs=[error_message]
386
- )
387
 
388
  def logout():
389
  return gr.update(visible=True), gr.update(visible=False), None, None
390
 
391
- logout_btn.click(
392
- logout,
393
- outputs=[login_group, chat_group, user_id, user_role]
394
- )
395
 
396
  if __name__ == "__main__":
397
- # Launch the app for Hugging Face Spaces
398
- demo.launch(
399
- server_name="0.0.0.0",
400
- server_port=7860,
401
- share=True,
402
- show_error=True
403
- )
 
19
  logger = logging.getLogger("CompanyChatbot")
20
 
21
  # Environment variables
22
+ HF_MODEL = os.environ.get("HF_MODEL", "mistralai/Mixtral-8x7B-Instruct-v0.1") # Smaller model
23
  HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
24
  COMPANY_NAME = os.environ.get("COMPANY_NAME", "AI")
25
  DEFAULT_SYSTEM_PROMPT = os.environ.get("DEFAULT_SYSTEM_PROMPT",
 
27
 
28
  # Validate API token
29
  if not HF_API_TOKEN:
30
+ raise RuntimeError("HF_API_TOKEN environment variable is not set.")
31
 
32
  # Initialize the client
33
  try:
 
35
  logger.info(f"Successfully initialized InferenceClient with model: {HF_MODEL}")
36
  except Exception as e:
37
  logger.error(f"Failed to initialize InferenceClient: {str(e)}")
38
+ raise RuntimeError(f"Failed to initialize the model: {str(e)}")
39
 
40
  # Configuration state management
41
  class ConfigState:
 
58
  # Main chat function
59
  def respond(message, chat_history, user_id):
60
  if not message.strip():
61
+ return chat_history or [] + [[message, "I'm sorry, I didn't receive any input. How can I help you today?"]]
62
 
63
  logger.info(f"User {user_id} sent message - Length: {len(message)}")
64
 
65
  try:
66
+ chat_history = chat_history or []
67
  messages = [{"role": "system", "content": config_state.system_message}]
68
 
69
  for user_msg, assistant_msg in chat_history:
 
111
  except Exception as e:
112
  error_msg = f"An error occurred: {str(e)}"
113
  logger.error(f"Error generating response for user {user_id}: {str(e)}")
114
+ yield chat_history + [[message, error_msg]]
115
 
116
  # Configuration update functions
117
  def update_config(system_msg, max_tok, temp, tp, role):
 
166
  gr.update(visible=True, value="Invalid username or password")
167
  )
168
 
169
+ # CSS styling (unchanged, omitted for brevity)
170
  css = """
171
+ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f9f9f9; }
172
+ .container { max-width: 1400px !important; margin: auto; }
173
+ .setting-panel { background-color: #f0f4f8; border-radius: 10px; padding: 15px; box-shadow: 0 2px 6px rgba(0,0,0,0.1); }
174
+ .chat-container { border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1); background-color: white; }
175
+ .company-header { background-color: #2c3e50; color: white; padding: 15px; border-radius: 10px 10px 0 0; margin-bottom: 15px; }
176
+ .footer { text-align: center; margin-top: 20px; color: #666; font-size: 0.8em; }
177
+ .message-user { background-color: #e6f7ff !important; border-radius: 15px 15px 0 15px !important; }
178
+ .message-bot { background-color: #f0f0f0 !important; border-radius: 15px 15px 15px 0 !important; }
179
+ .login-container { max-width: 500px; margin: 50px auto; padding: 30px; background-color: white; border-radius: 10px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
180
+ .login-header { text-align: center; margin-bottom: 30px; }
181
+ .error-message { color: #e74c3c; background-color: #fdedeb; padding: 10px; border-radius: 5px; margin-bottom: 15px; font-size: 14px; }
182
+ .role-badge { font-size: 12px; padding: 3px 8px; border-radius: 10px; margin-left: 10px; }
183
+ .admin-badge { background-color: #e74c3c; color: white; }
184
+ .user-badge { background-color: #3498db; color: white; }
185
+ .setting-disabled { opacity: 0.5; pointer-events: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  """
187
 
188
  # Main application
 
205
  with gr.Row():
206
  with gr.Column(scale=1, elem_classes=["setting-panel"]):
207
  role_indicator = gr.Markdown("", elem_id="role-indicator")
 
208
  gr.Markdown("### Configuration")
209
  with gr.Group() as config_group:
210
+ system_message = gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="System Instructions", lines=4, interactive=False)
211
+ max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max Response Length", interactive=False)
212
+ temperature = gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature", interactive=False)
213
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  update_config_btn = gr.Button("Update Configuration", visible=False)
215
  config_status = gr.Markdown("")
 
216
  gr.Markdown("### Chat Actions")
217
  with gr.Row():
218
  clear_btn = gr.Button("Clear Chat", variant="secondary")
219
  export_btn = gr.Button("Export Conversation", variant="secondary")
 
220
  logout_btn = gr.Button("Logout", variant="stop")
221
 
222
  with gr.Column(scale=2, elem_classes=["chat-container"]):
223
  chatbot = gr.Chatbot(elem_classes=["chatbox"])
224
  with gr.Row():
225
+ msg = gr.Textbox(show_label=False, placeholder="Type your message here...", container=False)
 
 
 
 
226
  submit_btn = gr.Button("Send", variant="primary")
227
 
228
  def update_role_display(role):
 
240
  gr.update(visible=is_admin),
241
  ]
242
 
243
+ login_button.click(login, inputs=[username, password], outputs=[login_group, chat_group, user_id, user_role, error_message]) \
244
+ .then(update_role_display, inputs=[user_role], outputs=[role_indicator]) \
245
+ .then(handle_role_permissions, inputs=[user_role], outputs=[system_message, max_tokens, temperature, top_p, update_config_btn])
 
 
 
 
 
 
 
 
 
 
246
 
247
+ update_config_btn.click(update_config, inputs=[system_message, max_tokens, temperature, top_p, user_role], outputs=[config_status])
 
 
 
 
248
 
249
+ msg.submit(respond, inputs=[msg, chatbot, user_id], outputs=[chatbot]).then(lambda: "", None, [msg])
 
 
 
 
250
 
251
+ submit_btn.click(respond, inputs=[msg, chatbot, user_id], outputs=[chatbot]).then(lambda: "", None, [msg])
 
 
 
 
252
 
253
  clear_btn.click(lambda: [], None, chatbot, queue=False)
254
 
 
261
  logger.info(f"Exported conversation for user {uid}")
262
  return gr.update(value=f"Conversation exported to {filename}", visible=True)
263
 
264
+ export_btn.click(export_conversation, inputs=[chatbot, user_id], outputs=[error_message])
 
 
 
 
265
 
266
  def logout():
267
  return gr.update(visible=True), gr.update(visible=False), None, None
268
 
269
+ logout_btn.click(logout, outputs=[login_group, chat_group, user_id, user_role])
 
 
 
270
 
271
  if __name__ == "__main__":
272
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=True, show_error=True)