JatsTheAIGen commited on
Commit
1ca61f9
·
1 Parent(s): a3e5843

Log Process Flow as JSON for review v1

Browse files
Files changed (1) hide show
  1. app.py +65 -160
app.py CHANGED
@@ -21,19 +21,10 @@ logger = logging.getLogger(__name__)
21
  orchestrator = None
22
  orchestrator_available = False
23
 
24
- # Import Process Flow Visualization
25
- try:
26
- from process_flow_visualizer import (
27
- create_process_flow_tab,
28
- update_process_flow_visualization,
29
- clear_flow_history,
30
- export_flow_data
31
- )
32
- process_flow_available = True
33
- logger.info("✓ Process Flow Visualization available")
34
- except ImportError as e:
35
- logger.warning(f"Process Flow Visualization not available: {e}")
36
- process_flow_available = False
37
 
38
  try:
39
  logger.info("Attempting to import orchestration components...")
@@ -320,17 +311,13 @@ def create_mobile_optimized_interface():
320
  )
321
  interface_components['context_display'] = context_display
322
 
323
- # Process Flow Tab (if available)
324
- if process_flow_available:
325
- process_flow_tab = create_process_flow_tab(interface_components)
326
- interface_components['process_flow_tab'] = process_flow_tab
327
 
328
  # Mobile Bottom Navigation
329
  with gr.Row(visible=False, elem_id="mobile_nav") as mobile_navigation:
330
  chat_nav_btn = gr.Button("💬 Chat", variant="secondary", size="sm", min_width=0)
331
  details_nav_btn = gr.Button("🔍 Details", variant="secondary", size="sm", min_width=0)
332
- if process_flow_available:
333
- flow_nav_btn = gr.Button("🔄 Flow", variant="secondary", size="sm", min_width=0)
334
  settings_nav_btn = gr.Button("⚙️ Settings", variant="secondary", size="sm", min_width=0)
335
 
336
  # Settings Panel (Modal for Mobile)
@@ -384,7 +371,7 @@ def create_mobile_optimized_interface():
384
  _interface_components = interface_components
385
 
386
  # Build outputs list dynamically
387
- outputs = _build_outputs_list(interface_components, process_flow_available)
388
 
389
  # Include session_info in inputs to pass session ID
390
  inputs = [interface_components['message_input'], interface_components['chatbot']]
@@ -431,35 +418,8 @@ def create_mobile_optimized_interface():
431
  ]
432
  )
433
 
434
- # Wire up Process Flow event handlers if available
435
- if process_flow_available:
436
- # Clear flow history button
437
- if 'clear_flow_btn' in interface_components:
438
- interface_components['clear_flow_btn'].click(
439
- fn=clear_flow_history,
440
- outputs=[
441
- interface_components.get('flow_display'),
442
- interface_components.get('flow_stats'),
443
- interface_components.get('performance_metrics'),
444
- interface_components.get('intent_details'),
445
- interface_components.get('synthesis_details'),
446
- interface_components.get('safety_details')
447
- ]
448
- )
449
-
450
- # Export flow data button
451
- if 'export_flow_btn' in interface_components:
452
- interface_components['export_flow_btn'].click(
453
- fn=export_flow_data,
454
- outputs=[gr.File(label="Download Flow Data")]
455
- )
456
-
457
- # Share flow button (placeholder)
458
- if 'share_flow_btn' in interface_components:
459
- interface_components['share_flow_btn'].click(
460
- fn=lambda: gr.Info("Flow sharing feature coming soon!"),
461
- outputs=[]
462
- )
463
 
464
  return demo, interface_components
465
 
@@ -743,7 +703,7 @@ async def process_message_async(message: str, history: Optional[List], session_i
743
  # Global variable to store interface components for dynamic return values
744
  _interface_components = {}
745
 
746
- def _build_outputs_list(interface_components: dict, process_flow_available: bool) -> list:
747
  """
748
  Build outputs list dynamically based on available interface components
749
  """
@@ -761,24 +721,12 @@ def _build_outputs_list(interface_components: dict, process_flow_available: bool
761
  if 'skills_tags' in interface_components:
762
  outputs.append(interface_components['skills_tags'])
763
 
764
- # Add Process Flow outputs if available
765
- if process_flow_available:
766
- if 'flow_display' in interface_components:
767
- outputs.append(interface_components['flow_display'])
768
- if 'flow_stats' in interface_components:
769
- outputs.append(interface_components['flow_stats'])
770
- if 'performance_metrics' in interface_components:
771
- outputs.append(interface_components['performance_metrics'])
772
- if 'intent_details' in interface_components:
773
- outputs.append(interface_components['intent_details'])
774
- if 'synthesis_details' in interface_components:
775
- outputs.append(interface_components['synthesis_details'])
776
- if 'safety_details' in interface_components:
777
- outputs.append(interface_components['safety_details'])
778
 
779
  return outputs
780
 
781
- def _build_dynamic_return_values(result: tuple, skills_content: str, interface_components: dict, process_flow_available: bool = False, flow_updates: dict = None) -> tuple:
782
  """
783
  Build return values dynamically based on available interface components
784
  This ensures the return values match the outputs list exactly
@@ -803,20 +751,8 @@ def _build_dynamic_return_values(result: tuple, skills_content: str, interface_c
803
  if 'skills_tags' in interface_components:
804
  return_values.append(skills_content) # skills_content
805
 
806
- # Add Process Flow outputs if available
807
- if process_flow_available:
808
- if 'flow_display' in interface_components:
809
- return_values.append(flow_updates.get("flow_display", "") if flow_updates else "")
810
- if 'flow_stats' in interface_components:
811
- return_values.append(flow_updates.get("flow_stats", {}) if flow_updates else {})
812
- if 'performance_metrics' in interface_components:
813
- return_values.append(flow_updates.get("performance_metrics", {}) if flow_updates else {})
814
- if 'intent_details' in interface_components:
815
- return_values.append(flow_updates.get("intent_details", {}) if flow_updates else {})
816
- if 'synthesis_details' in interface_components:
817
- return_values.append(flow_updates.get("synthesis_details", {}) if flow_updates else {})
818
- if 'safety_details' in interface_components:
819
- return_values.append(flow_updates.get("safety_details", {}) if flow_updates else {})
820
 
821
  return tuple(return_values)
822
 
@@ -842,7 +778,7 @@ def process_message(message: str, history: Optional[List], session_id: Optional[
842
  skills_content, skills_visible = _update_skills_display(skills_html)
843
 
844
  # Return dynamic values based on available components
845
- return _build_dynamic_return_values(result, skills_content, _interface_components, process_flow_available)
846
  except Exception as e:
847
  logger.error(f"Error in process_message: {e}", exc_info=True)
848
  error_history = list(history) if history else []
@@ -873,7 +809,7 @@ def process_message(message: str, history: Optional[List], session_id: Optional[
873
 
874
  # Return dynamic values for error case
875
  error_result = (error_history, "", reasoning_data, {}, {}, session_id, "")
876
- return _build_dynamic_return_values(error_result, "", _interface_components, process_flow_available)
877
 
878
  # Decorate the chat handler with GPU if available
879
  if SPACES_GPU_AVAILABLE and GPU is not None:
@@ -889,7 +825,7 @@ if SPACES_GPU_AVAILABLE and GPU is not None:
889
  chat_handler_fn = gpu_chat_handler
890
  else:
891
  def chat_handler_wrapper(message, history, session_id=None):
892
- """Wrapper to handle session ID with Process Flow Visualization"""
893
  if not session_id:
894
  session_id = str(uuid.uuid4())[:8]
895
  result = process_message(message, history, session_id)
@@ -897,85 +833,54 @@ else:
897
  skills_html = result[6]
898
  skills_content, skills_visible = _update_skills_display(skills_html)
899
 
900
- # Prepare process flow updates if available
901
- flow_updates = {}
902
- if process_flow_available:
903
- try:
904
- # Extract data for process flow visualization
905
- reasoning_data = result[2]
906
- performance_data = result[3]
907
- context_data = result[4]
908
-
909
- # Create dynamic agent results for visualization
910
- step_results = {}
911
-
912
- # Intent result
913
- step_results["intent_result"] = {
914
- "primary_intent": reasoning_data.get("chain_of_thought", {}).get("step_1", {}).get("hypothesis", "unknown"),
915
- "confidence_scores": {"overall": reasoning_data.get("confidence_calibration", {}).get("overall_confidence", 0.7)},
916
- "secondary_intents": [],
917
- "reasoning_chain": list(reasoning_data.get("chain_of_thought", {}).keys()),
918
- "context_tags": ["general"],
919
- "processing_time": performance_data.get("processing_time", 0.5),
920
- "agent_id": "INTENT_REC_001"
921
- }
922
-
923
- # Skills result (if available)
924
- if "skills_result" in reasoning_data: # Check if skills data is in reasoning_data
925
- step_results["skills_result"] = reasoning_data["skills_result"]
926
- else:
927
- step_results["skills_result"] = {
928
- "identified_skills": [],
929
- "confidence_score": 0.7,
930
- "processing_time": performance_data.get("processing_time", 0.5) * 0.2,
931
- "agent_id": "SKILLS_ID_001"
932
- }
933
-
934
- # Synthesis result
935
- step_results["synthesis_result"] = {
936
- "final_response": result[0][-1]["content"] if result[0] else "",
937
- "draft_response": "",
938
- "source_references": ["INTENT_REC_001"],
939
- "coherence_score": 0.85,
940
- "synthesis_method": "llm_enhanced",
941
- "intent_alignment": {"intent_detected": step_results["intent_result"]["primary_intent"], "alignment_score": 0.8},
942
- "processing_time": performance_data.get("processing_time", 0.5) - 0.15,
943
- "agent_id": "RESP_SYNTH_001"
944
- }
945
-
946
- # Safety result
947
- step_results["safety_result"] = {
948
- "original_response": result[0][-1]["content"] if result[0] else "",
949
- "safety_checked_response": result[0][-1]["content"] if result[0] else "",
950
- "warnings": [],
951
- "safety_analysis": {
952
- "toxicity_score": 0.1,
953
- "bias_indicators": [],
954
- "privacy_concerns": [],
955
- "overall_safety_score": 0.9,
956
- "confidence_scores": {"safety": 0.9}
957
- },
958
- "blocked": False,
959
- "processing_time": 0.1,
960
- "agent_id": "SAFETY_BIAS_001"
961
- }
962
-
963
- # Final response
964
- step_results["final_response"] = result[0][-1]["content"] if result[0] else ""
965
-
966
- # Update process flow visualization dynamically
967
- flow_updates = update_process_flow_visualization(
968
- user_input=message,
969
- session_id=session_id,
970
- processing_time=performance_data.get("processing_time", 1.0),
971
- **step_results
972
- )
973
- except Exception as e:
974
- logger.error(f"Error updating process flow: {e}")
975
- flow_updates = {}
976
 
977
- # Return dynamic values including process flow
978
- return _build_dynamic_return_values(result, skills_content, _interface_components, process_flow_available, flow_updates)
979
  chat_handler_fn = chat_handler_wrapper
980
 
981
  # Initialize orchestrator on module load
 
21
  orchestrator = None
22
  orchestrator_available = False
23
 
24
+ # Process Flow Visualization - DISABLED
25
+ # Moving functionality to container logs instead of UI
26
+ process_flow_available = False
27
+ logger.info("Process Flow Visualization disabled - functionality moved to container logs")
 
 
 
 
 
 
 
 
 
28
 
29
  try:
30
  logger.info("Attempting to import orchestration components...")
 
311
  )
312
  interface_components['context_display'] = context_display
313
 
314
+ # Process Flow Tab - DISABLED
315
+ # Process flow information is now logged to container logs instead of UI
 
 
316
 
317
  # Mobile Bottom Navigation
318
  with gr.Row(visible=False, elem_id="mobile_nav") as mobile_navigation:
319
  chat_nav_btn = gr.Button("💬 Chat", variant="secondary", size="sm", min_width=0)
320
  details_nav_btn = gr.Button("🔍 Details", variant="secondary", size="sm", min_width=0)
 
 
321
  settings_nav_btn = gr.Button("⚙️ Settings", variant="secondary", size="sm", min_width=0)
322
 
323
  # Settings Panel (Modal for Mobile)
 
371
  _interface_components = interface_components
372
 
373
  # Build outputs list dynamically
374
+ outputs = _build_outputs_list(interface_components)
375
 
376
  # Include session_info in inputs to pass session ID
377
  inputs = [interface_components['message_input'], interface_components['chatbot']]
 
418
  ]
419
  )
420
 
421
+ # Process Flow event handlers - DISABLED
422
+ # Process flow information is now logged to container logs instead of UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
  return demo, interface_components
425
 
 
703
  # Global variable to store interface components for dynamic return values
704
  _interface_components = {}
705
 
706
+ def _build_outputs_list(interface_components: dict) -> list:
707
  """
708
  Build outputs list dynamically based on available interface components
709
  """
 
721
  if 'skills_tags' in interface_components:
722
  outputs.append(interface_components['skills_tags'])
723
 
724
+ # Process Flow outputs - DISABLED
725
+ # Process flow information is now logged to container logs instead of UI
 
 
 
 
 
 
 
 
 
 
 
 
726
 
727
  return outputs
728
 
729
+ def _build_dynamic_return_values(result: tuple, skills_content: str, interface_components: dict) -> tuple:
730
  """
731
  Build return values dynamically based on available interface components
732
  This ensures the return values match the outputs list exactly
 
751
  if 'skills_tags' in interface_components:
752
  return_values.append(skills_content) # skills_content
753
 
754
+ # Process Flow outputs - DISABLED
755
+ # Process flow information is now logged to container logs instead of UI
 
 
 
 
 
 
 
 
 
 
 
 
756
 
757
  return tuple(return_values)
758
 
 
778
  skills_content, skills_visible = _update_skills_display(skills_html)
779
 
780
  # Return dynamic values based on available components
781
+ return _build_dynamic_return_values(result, skills_content, _interface_components)
782
  except Exception as e:
783
  logger.error(f"Error in process_message: {e}", exc_info=True)
784
  error_history = list(history) if history else []
 
809
 
810
  # Return dynamic values for error case
811
  error_result = (error_history, "", reasoning_data, {}, {}, session_id, "")
812
+ return _build_dynamic_return_values(error_result, "", _interface_components)
813
 
814
  # Decorate the chat handler with GPU if available
815
  if SPACES_GPU_AVAILABLE and GPU is not None:
 
825
  chat_handler_fn = gpu_chat_handler
826
  else:
827
  def chat_handler_wrapper(message, history, session_id=None):
828
+ """Wrapper to handle session ID - Process Flow functionality moved to logs"""
829
  if not session_id:
830
  session_id = str(uuid.uuid4())[:8]
831
  result = process_message(message, history, session_id)
 
833
  skills_html = result[6]
834
  skills_content, skills_visible = _update_skills_display(skills_html)
835
 
836
+ # Log process flow information to container logs instead of UI
837
+ try:
838
+ # Extract data for process flow logging
839
+ reasoning_data = result[2]
840
+ performance_data = result[3]
841
+ context_data = result[4]
842
+
843
+ # Log comprehensive process flow information
844
+ logger.info("=" * 60)
845
+ logger.info("PROCESS FLOW LOGGING")
846
+ logger.info("=" * 60)
847
+ logger.info(f"Session ID: {session_id}")
848
+ logger.info(f"User Input: {message[:100]}...")
849
+ logger.info(f"Processing Time: {performance_data.get('processing_time', 0):.2f}s")
850
+
851
+ # Log intent recognition details
852
+ if reasoning_data.get("chain_of_thought"):
853
+ logger.info("Intent Recognition:")
854
+ logger.info(f" - Primary Intent: {reasoning_data.get('chain_of_thought', {}).get('step_1', {}).get('hypothesis', 'unknown')}")
855
+ logger.info(f" - Confidence: {reasoning_data.get('confidence_calibration', {}).get('overall_confidence', 0.7):.2f}")
856
+
857
+ # Log performance metrics
858
+ logger.info("Performance Metrics:")
859
+ logger.info(f" - Agent Trace: {performance_data.get('agent_trace', [])}")
860
+ logger.info(f" - Token Count: {performance_data.get('token_count', 0)}")
861
+ logger.info(f" - Confidence Score: {performance_data.get('confidence_score', 0.7):.2f}")
862
+ logger.info(f" - Agents Used: {performance_data.get('agents_used', [])}")
863
+
864
+ # Log context information
865
+ logger.info("Context Information:")
866
+ logger.info(f" - Interaction ID: {context_data.get('interaction_id', 'unknown')}")
867
+ logger.info(f" - Timestamp: {context_data.get('timestamp', '')}")
868
+ logger.info(f" - Warnings: {context_data.get('warnings', [])}")
869
+
870
+ # Log skills identification if available
871
+ if skills_html and len(skills_html.strip()) > 0:
872
+ logger.info("Skills Identification:")
873
+ logger.info(f" - Skills HTML: {skills_html}")
874
+
875
+ logger.info("=" * 60)
876
+ logger.info("END PROCESS FLOW LOGGING")
877
+ logger.info("=" * 60)
878
+
879
+ except Exception as e:
880
+ logger.error(f"Error logging process flow: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
881
 
882
+ # Return dynamic values without process flow
883
+ return _build_dynamic_return_values(result, skills_content, _interface_components)
884
  chat_handler_fn = chat_handler_wrapper
885
 
886
  # Initialize orchestrator on module load