Sathvika-Alla commited on
Commit
02b86d2
·
verified ·
1 Parent(s): 9a5e694

Updated UI

Browse files
Files changed (1) hide show
  1. chatbot-gradio.py +150 -167
chatbot-gradio.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import logging
2
  import uuid
3
  from semantic_kernel import Kernel
@@ -161,24 +162,22 @@ kernel.add_plugin(ConverterPlugin(logger=logger), "CosmosDBPlugin")
161
  kernel.add_plugin(ChatMemoryPlugin(logger=logger), "ChatMemoryPlugin")
162
  kernel.add_plugin(NL2SQLPlugin(), "NL2SQLPlugin")
163
 
164
- def initialize_session():
165
- return str(uuid.uuid4())
166
-
167
  # Updated query handler using function calling
168
- async def handle_query(user_input: str, session_state):
169
- session_id = session_state
170
 
171
  settings = AzureChatPromptExecutionSettings(
172
  function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=True)
173
  )
174
 
175
- ARTNR_PATTERN = r'\b\d{6}\b'
176
 
177
  prompt = f"""
178
  You are a product catalog customer service chatbot for TAL BV. Answer questions about converters, their specifications and lamps. Process this user query:
179
  {user_input}
180
 
181
  artnr Pattern: {ARTNR_PATTERN}
 
182
 
183
  Available functions:
184
  - generate_sql: Creates SQL queries (use only for complex queries or schema keywords)
@@ -248,10 +247,11 @@ async def handle_query(user_input: str, session_state):
248
  )
249
 
250
  func_name = result.model_dump()["metadata"]["messages"]["messages"][2]["items"][0]["name"]
 
251
  log_func = kernel.get_function("ChatMemoryPlugin", "log_interaction")
252
  await log_func.invoke(
253
  kernel=kernel,
254
- session_id=session_id,
255
  question=user_input,
256
  function_used=func_name,
257
  answer=str(result)
@@ -264,218 +264,201 @@ async def handle_query(user_input: str, session_state):
264
  error_func = kernel.get_function("ChatMemoryPlugin", "log_interaction")
265
  await error_func.invoke(
266
  kernel=kernel,
267
- session_id=session_id,
268
  question=user_input,
269
  function_used="error",
270
  answer=str(e)
271
  )
272
  raise
273
 
274
- # # Example usage
275
- # async def main():
276
- # # cm = ChatMemoryPlugin(logger)
277
- # # await cm.get_semantic_faqs()
278
-
279
- # while True:
280
- # try:
281
- # query = input("User: ")
282
- # if query.lower() in ["exit", "quit"]:
283
- # break
284
-
285
- # response = await handle_query(query)
286
- # print(response)
287
-
288
- # except KeyboardInterrupt:
289
- # break
290
-
291
-
292
- # if __name__ == "__main__":
293
- # import asyncio
294
- # asyncio.run(main())
295
 
296
- # --- Gradio UI ---
 
 
 
 
 
 
297
 
298
- custom_css = """
 
299
  #chatbot-toggle-btn {
300
  position: fixed;
301
  bottom: 30px;
302
  right: 30px;
303
  z-index: 10001;
304
- background-color: #ED1C24;
305
- color: white;
306
- border: none;
307
- border-radius: 50%;
308
- width: 56px;
309
- height: 56px;
310
- font-size: 28px;
311
- font-weight: bold;
312
- cursor: pointer;
313
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
314
- display: flex;
315
- align-items: center;
316
- justify-content: center;
317
- transition: all 0.3s ease;
318
  }
319
 
320
  #chatbot-panel {
321
  position: fixed;
322
- bottom: 10vw;
323
  right: 2vw;
324
  z-index: 10000;
325
  width: 95vw;
326
  max-width: 600px;
327
  height: 90vh;
328
  max-height: 700px;
329
- background-color: #ffffff;
330
- border-radius: 20px;
331
- box-shadow: 0 4px 24px rgba(0, 0, 0, 0.25);
332
- display: flex;
333
- flex-direction: column;
334
- overflow: hidden;
335
- font-family: 'Arial', sans-serif;
336
- }
337
-
338
- @media (max-width: 600px) {
339
- #chatbot-panel {
340
- width: 100vw;
341
- height: 100vh;
342
- right: 0;
343
- bottom: 0;
344
- border-radius: 0;
345
- }
346
- #chatbot-toggle-btn {
347
- right: 10px;
348
- bottom: 10px;
349
- width: 48px;
350
- height: 48px;
351
- font-size: 24px;
352
- }
353
- }
354
-
355
- #chatbot-panel.hide {
356
- display: none !important;
357
  }
358
 
359
  #chat-header {
360
- background-color: #ED1C24;
361
- color: white;
362
- padding: 20px;
363
- font-weight: bold;
364
- font-size: 22px;
365
- display: flex;
366
- align-items: center;
367
- gap: 12px;
368
- width: 100%;
369
  box-sizing: border-box;
370
- }
371
-
372
- #chat-header img {
373
- border-radius: 50%;
374
- width: 40px;
375
- height: 40px;
376
  }
377
 
378
  .gr-chatbot {
379
- flex: 1;
380
- overflow-y: auto;
381
- padding: 20px;
382
- background-color: #f9f9f9;
383
- border-top: 1px solid #eee;
384
- border-bottom: 1px solid #eee;
385
- display: flex;
386
- flex-direction: column;
387
- gap: 12px;
388
- box-sizing: border-box;
389
- }
390
-
391
- .gr-textbox {
392
- padding: 16px 20px;
393
- background-color: #fff;
394
- display: flex;
395
- align-items: center;
396
- gap: 12px;
397
- border-top: 1px solid #eee;
398
- box-sizing: border-box;
399
- }
400
-
401
- .gr-textbox textarea {
402
- flex: 1;
403
- resize: none;
404
- padding: 12px;
405
- background-color: white;
406
- border: 1px solid #ccc;
407
- border-radius: 8px;
408
- font-family: inherit;
409
- font-size: 16px;
410
  box-sizing: border-box;
411
- height: 48px;
412
- line-height: 1.5;
413
  }
414
 
415
- .gr-textbox button {
416
- background-color: #ED1C24;
417
- border: none;
418
- color: white;
419
- border-radius: 8px;
420
- padding: 12px 20px;
421
- cursor: pointer;
422
- font-weight: bold;
423
- transition: background-color 0.3s ease;
424
- font-size: 16px;
425
  }
426
 
427
- .gr-textbox button:hover {
428
- background-color: #c4161c;
429
- }
 
 
 
 
430
 
431
- footer {
432
- display: none !important;
433
- }
 
 
 
 
434
 
435
  """
436
-
437
  panel_visible = False
438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
  def toggle_panel():
440
  global panel_visible
441
  panel_visible = not panel_visible
442
  return gr.Column(visible=panel_visible)
443
 
444
- with gr.Blocks(css=custom_css) as demo:
445
- session_state = gr.State(value=initialize_session())
 
446
 
447
- # Toggle button (floating action button)
448
- toggle_btn = gr.Button("💬", elem_id="chatbot-toggle-btn")
449
 
450
- # Chat panel (initially hidden)
 
 
 
 
 
 
 
 
451
  chat_panel = gr.Column(visible=panel_visible, elem_id="chatbot-panel")
 
452
  with chat_panel:
453
- # Chat header
454
- with gr.Row(elem_id="chat-header"):
455
- gr.HTML("""
456
- <div id='chat-header'>
457
- <img src="https://www.svgrepo.com/download/490283/pixar-lamp.svg" />
458
- Lofty the TAL Bot
459
- </div>
460
- """)
461
- # Chatbot and input
462
- chatbot = gr.Chatbot(elem_id="gr-chatbot", type="messages")
463
- msg = gr.Textbox(placeholder="Type your question here...", elem_id="gr-textbox")
464
- send = gr.Button("Send")
465
- # clear = gr.ClearButton([msg, chatbot])
466
-
467
-
468
- # Function to handle messages
469
- async def respond(message, chat_history, session_state):
470
- response = await handle_query(message, session_state)
471
 
472
- # Add new messages
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473
  chat_history.append({"role": "user", "content": message})
474
  chat_history.append({"role": "assistant", "content": response})
475
  return "", chat_history
476
-
477
- send.click(respond, [msg, chatbot, session_state], [msg,chatbot])
478
- msg.submit(respond, [msg, chatbot, session_state], [msg, chatbot])
479
  toggle_btn.click(toggle_panel, outputs=chat_panel)
480
 
481
- demo.launch()
 
1
+ import asyncio
2
  import logging
3
  import uuid
4
  from semantic_kernel import Kernel
 
162
  kernel.add_plugin(ChatMemoryPlugin(logger=logger), "ChatMemoryPlugin")
163
  kernel.add_plugin(NL2SQLPlugin(), "NL2SQLPlugin")
164
 
 
 
 
165
  # Updated query handler using function calling
166
+ async def handle_query(user_input: str, session_state:str):
167
+
168
 
169
  settings = AzureChatPromptExecutionSettings(
170
  function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=True)
171
  )
172
 
173
+ ARTNR_PATTERN = r'\b(?:\d{5}|\d{6})\b'
174
 
175
  prompt = f"""
176
  You are a product catalog customer service chatbot for TAL BV. Answer questions about converters, their specifications and lamps. Process this user query:
177
  {user_input}
178
 
179
  artnr Pattern: {ARTNR_PATTERN}
180
+ artnrs are usually numbers like 40057 or 930565
181
 
182
  Available functions:
183
  - generate_sql: Creates SQL queries (use only for complex queries or schema keywords)
 
247
  )
248
 
249
  func_name = result.model_dump()["metadata"]["messages"]["messages"][2]["items"][0]["name"]
250
+ print(func_name)
251
  log_func = kernel.get_function("ChatMemoryPlugin", "log_interaction")
252
  await log_func.invoke(
253
  kernel=kernel,
254
+ session_id=session_state,
255
  question=user_input,
256
  function_used=func_name,
257
  answer=str(result)
 
264
  error_func = kernel.get_function("ChatMemoryPlugin", "log_interaction")
265
  await error_func.invoke(
266
  kernel=kernel,
267
+ session_id=session_state,
268
  question=user_input,
269
  function_used="error",
270
  answer=str(e)
271
  )
272
  raise
273
 
274
+ import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
 
276
+ # Create a custom theme based on your brand colors
277
+ custom_theme = gr.themes.Base(
278
+ primary_hue="red",
279
+ secondary_hue="amber",
280
+ font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui', 'sans-serif'],
281
+ font_mono=[gr.themes.GoogleFont('Roboto Mono'), 'ui-monospace', 'Consolas', 'monospace'],
282
+ )
283
 
284
+ # Minimal CSS for positioning only (avoiding styling)
285
+ minimal_css = """
286
  #chatbot-toggle-btn {
287
  position: fixed;
288
  bottom: 30px;
289
  right: 30px;
290
  z-index: 10001;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  }
292
 
293
  #chatbot-panel {
294
  position: fixed;
295
+ bottom: 5vh;
296
  right: 2vw;
297
  z-index: 10000;
298
  width: 95vw;
299
  max-width: 600px;
300
  height: 90vh;
301
  max-height: 700px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  }
303
 
304
  #chat-header {
305
+ width: calc(100% + 20px);
 
 
 
 
 
 
 
 
306
  box-sizing: border-box;
307
+ margin: 0 -10px;
308
+ margin-bottom: -7px !important;
 
 
 
 
309
  }
310
 
311
  .gr-chatbot {
312
+ margin-top: -7px;
313
+ width: 100%;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  box-sizing: border-box;
 
 
315
  }
316
 
317
+ #chat-header img {
318
+ border-radius: 50%;
319
+ width: 50px;
320
+ height: 50px;
321
+ filter: brightness(0) invert(1);
 
 
 
 
 
322
  }
323
 
324
+ #chatbot-toggle-btn {
325
+ right: 30px;
326
+ bottom: 30px;
327
+ width: 48px;
328
+ height: 48px;
329
+ font-size: 24px;
330
+ }
331
 
332
+ @media (max-width: 600px) {
333
+ #chatbot-panel {
334
+ width: 100vw;
335
+ height: 100vh;
336
+ right: 0;
337
+ bottom: 0;
338
+ }
339
 
340
  """
 
341
  panel_visible = False
342
 
343
+ async def get_chatbot_examples():
344
+ """Fetch FAQs and format them as Gradio chatbot examples"""
345
+ try:
346
+ # Get your chat memory plugin instance
347
+ get_faqs_func = kernel.get_function("ChatMemoryPlugin", "get_semantic_faqs")
348
+
349
+ # Call the function to get FAQs
350
+ result = await get_faqs_func.invoke(kernel=kernel, limit=6, threshold=0.1)
351
+ faqs = result.value if hasattr(result, 'value') else result
352
+
353
+ # Format as Gradio examples
354
+ examples = []
355
+ for faq in faqs:
356
+ examples.append({
357
+ "text": faq,
358
+ "display_text": faq
359
+ })
360
+
361
+ return examples
362
+ except Exception as e:
363
+ logger.error(f"Failed to load FAQ examples: {str(e)}")
364
+ return []
365
+
366
+ def get_examples_sync():
367
+ try:
368
+ loop = asyncio.get_event_loop()
369
+ return loop.run_until_complete(get_chatbot_examples())
370
+ except:
371
+ # If no event loop, create one
372
+ return asyncio.run(get_chatbot_examples())
373
+
374
  def toggle_panel():
375
  global panel_visible
376
  panel_visible = not panel_visible
377
  return gr.Column(visible=panel_visible)
378
 
379
+ # Apply the custom theme to your Blocks
380
+ with gr.Blocks(theme=custom_theme, css=minimal_css) as demo:
381
+ faqs = gr.State(get_examples_sync())
382
 
383
+ session_id = gr.State(str(uuid.uuid4()))
 
384
 
385
+ # Toggle button
386
+ toggle_btn = gr.Button(
387
+ "💬",
388
+ elem_id="chatbot-toggle-btn",
389
+ variant="primary",
390
+ size="sm"
391
+ )
392
+
393
+ # Chat panel
394
  chat_panel = gr.Column(visible=panel_visible, elem_id="chatbot-panel")
395
+
396
  with chat_panel:
397
+ # Header - Remove the gr.Row wrapper and place directly in the column
398
+ gr.HTML("""
399
+ <div id='chat-header' style='
400
+ background-color: var(--button-primary-background-fill);
401
+ color: var(--button-primary-text-color);
402
+ padding: 30px;
403
+ font-weight: bold;
404
+ font-size: 30px;
405
+ display: flex;
406
+ align-items: center;
407
+ box-sizing: border-box;
408
+ border-radius: var(--radius-md);'>
409
+ <img src="https://www.svgrepo.com/download/490283/pixar-lamp.svg"
410
+ style="width: 50px; height: 50px; border-radius: 50%; margin-right: 15px; filter: brightness(0) invert(1);" />
411
+ Lofty the TAL Bot
412
+ </div>
413
+ """)
 
414
 
415
+ # Chatbot with theme styling
416
+ chatbot = gr.Chatbot(
417
+ type="messages",
418
+ height=400,
419
+ show_copy_button=True,
420
+ container=False,
421
+ resizable=True,
422
+ examples=faqs.value
423
+ )
424
+
425
+ # Input with theme styling
426
+ with gr.Row():
427
+ msg = gr.Textbox(
428
+ placeholder="Type your question here...",
429
+ container=False,
430
+ scale=4
431
+ )
432
+
433
+ send = gr.Button(
434
+ "Send",
435
+ variant="primary",
436
+ scale=1
437
+ )
438
+
439
+ def handle_example_select(evt: gr.SelectData):
440
+ """Handle when user clicks on an example"""
441
+ examples = faqs.value
442
+ if evt.index < len(examples):
443
+ selected_example = examples[evt.index]
444
+ return selected_example.get("text", "")
445
+ return ""
446
+
447
+ # Connect the example_select event to populate the textbox
448
+ chatbot.example_select(
449
+ fn=handle_example_select,
450
+ outputs=msg
451
+ )
452
+
453
+ # Your existing event handlers
454
+ async def respond(message, chat_history):
455
+ response = await handle_query(message, session_id.value)
456
  chat_history.append({"role": "user", "content": message})
457
  chat_history.append({"role": "assistant", "content": response})
458
  return "", chat_history
459
+
460
+ send.click(respond, [msg, chatbot], [msg, chatbot])
461
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
462
  toggle_btn.click(toggle_panel, outputs=chat_panel)
463
 
464
+ demo.launch()