GuglielmoTor commited on
Commit
8cdee8f
·
verified ·
1 Parent(s): 917a83b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -29
app.py CHANGED
@@ -649,27 +649,27 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"),
649
 
650
  # --- NEW: Handler for Employer Branding Agent Chat ---
651
  eb_agent_instance_dict = {"agent": None} # To store agent instance across calls if needed, or re-init
652
-
653
  async def handle_eb_agent_chat(user_message: str, chat_history_list: list, current_token_state: dict):
654
  # Expected outputs: [eb_agent_chatbot_ui, eb_agent_chat_history_st, eb_agent_chat_input_ui, eb_agent_status_md, eb_agent_schema_display_md]
655
  # (5 components)
656
-
657
  if not EB_AGENT_AVAILABLE or not os.getenv('GEMINI_API_KEY'):
658
  no_key_msg = "L'Agente AI non è disponibile. Assicurati che GEMINI_API_KEY sia configurata."
659
  chat_history_list.append([user_message, no_key_msg])
660
  # Yield updates for all 5 components
661
  yield chat_history_list, chat_history_list, gr.update(value=""), gr.update(value=no_key_msg), gr.update(value="Nessuno schema disponibile.")
662
  return
663
-
664
  if not user_message.strip():
665
  # Yield updates for all 5 components
666
  yield chat_history_list, chat_history_list, gr.update(value=""), gr.update(value="Stato Agente: Per favore, inserisci una domanda."), gr.update() # No change to schema display
667
  return
668
-
669
  status_update_msg = "Stato Agente: Elaborazione della tua richiesta..."
670
  # Show user message immediately, update status
671
  yield chat_history_list + [[user_message, None]], chat_history_list + [[user_message, None]], gr.update(value=""), gr.update(value=status_update_msg), gr.update()
672
-
673
  # Prepare DataFrames for the agent
674
  df_follower_stats = current_token_state.get("bubble_follower_stats_df", pd.DataFrame())
675
  df_posts = current_token_state.get("bubble_posts_df", pd.DataFrame())
@@ -699,46 +699,45 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"),
699
  embedding_model_name=EB_AGENT_EMBEDDING_MODEL
700
  )
701
 
 
702
  agent_internal_history = []
703
- for user_q, ai_r in chat_history_list: # Use the passed chat_history_list
704
  if user_q: agent_internal_history.append({"role": "user", "content": user_q})
705
- if ai_r: agent_internal_history.append({"role": "assistant", "content": ai_r})
 
 
 
706
  current_agent.chat_history = agent_internal_history
707
-
708
  try:
 
 
 
 
 
 
 
 
709
  logging.info(f"Sending to EB Agent. User: '{user_message}'. DF Keys: {list(dataframes_for_agent.keys())}")
710
  ai_response = await current_agent.process_query(user_query=user_message)
711
 
712
- updated_gradio_history = []
713
- temp_hist = current_agent.chat_history
714
- for i in range(0, len(temp_hist), 2):
715
- u_msg = temp_hist[i]['content']
716
- a_msg = temp_hist[i+1]['content'] if i+1 < len(temp_hist) else "Thinking..."
717
- updated_gradio_history.append([u_msg, a_msg])
718
 
719
  status_update_msg = "Stato Agente: Risposta ricevuta."
720
  # Yield final updates for all 5 components
721
- yield updated_gradio_history, updated_gradio_history, gr.update(value=""), gr.update(value=status_update_msg), gr.update(value=schemas_text_for_display)
722
-
723
  except Exception as e:
724
  logging.error(f"Error during EB Agent processing: {e}", exc_info=True)
725
  error_msg = f"# Errore dell'Agente AI:\n{type(e).__name__}: {str(e)}"
726
 
727
- # Ensure the current turn in chat_history_list reflects the error
728
- # The last item in chat_history_list is [user_message, None] from the first yield
729
- current_turn_history = chat_history_list + [[user_message, error_msg]] # This might duplicate user message if not careful
730
-
731
- # Let's reconstruct history carefully to avoid duplicates
732
- final_error_history = chat_history_list # This already has [user_message, None] as last item if first yield happened
733
- if final_error_history and final_error_history[-1][0] == user_message and final_error_history[-1][1] is None:
734
- final_error_history[-1][1] = error_msg # Update the assistant part of the last entry
735
- else: # Should not happen if first yield was correct
736
- final_error_history.append([user_message, error_msg])
737
-
738
-
739
  status_update_msg = f"Stato Agente: Errore - {type(e).__name__}"
740
  # Yield error updates for all 5 components
741
- yield final_error_history, final_error_history, gr.update(value=""), gr.update(value=status_update_msg), gr.update(value=schemas_text_for_display)
742
 
743
 
744
  def clear_eb_agent_chat_history():
 
649
 
650
  # --- NEW: Handler for Employer Branding Agent Chat ---
651
  eb_agent_instance_dict = {"agent": None} # To store agent instance across calls if needed, or re-init
652
+
653
  async def handle_eb_agent_chat(user_message: str, chat_history_list: list, current_token_state: dict):
654
  # Expected outputs: [eb_agent_chatbot_ui, eb_agent_chat_history_st, eb_agent_chat_input_ui, eb_agent_status_md, eb_agent_schema_display_md]
655
  # (5 components)
656
+
657
  if not EB_AGENT_AVAILABLE or not os.getenv('GEMINI_API_KEY'):
658
  no_key_msg = "L'Agente AI non è disponibile. Assicurati che GEMINI_API_KEY sia configurata."
659
  chat_history_list.append([user_message, no_key_msg])
660
  # Yield updates for all 5 components
661
  yield chat_history_list, chat_history_list, gr.update(value=""), gr.update(value=no_key_msg), gr.update(value="Nessuno schema disponibile.")
662
  return
663
+
664
  if not user_message.strip():
665
  # Yield updates for all 5 components
666
  yield chat_history_list, chat_history_list, gr.update(value=""), gr.update(value="Stato Agente: Per favore, inserisci una domanda."), gr.update() # No change to schema display
667
  return
668
+
669
  status_update_msg = "Stato Agente: Elaborazione della tua richiesta..."
670
  # Show user message immediately, update status
671
  yield chat_history_list + [[user_message, None]], chat_history_list + [[user_message, None]], gr.update(value=""), gr.update(value=status_update_msg), gr.update()
672
+
673
  # Prepare DataFrames for the agent
674
  df_follower_stats = current_token_state.get("bubble_follower_stats_df", pd.DataFrame())
675
  df_posts = current_token_state.get("bubble_posts_df", pd.DataFrame())
 
699
  embedding_model_name=EB_AGENT_EMBEDDING_MODEL
700
  )
701
 
702
+ # Initialize the agent's chat history with previous conversation
703
  agent_internal_history = []
704
+ for user_q, ai_r in chat_history_list:
705
  if user_q: agent_internal_history.append({"role": "user", "content": user_q})
706
+ if ai_r: agent_internal_history.append({"role": "model", "content": ai_r})
707
+
708
+ # ADD THE CURRENT USER MESSAGE TO THE AGENT'S HISTORY - THIS WAS MISSING!
709
+ agent_internal_history.append({"role": "user", "content": user_message})
710
  current_agent.chat_history = agent_internal_history
711
+
712
  try:
713
+ # Initialize the agent first
714
+ init_success = await current_agent.initialize()
715
+ if not init_success:
716
+ error_msg = "Errore: Impossibile inizializzare l'agente AI."
717
+ updated_history = chat_history_list + [[user_message, error_msg]]
718
+ yield updated_history, updated_history, gr.update(value=""), gr.update(value="Stato Agente: Errore di inizializzazione"), gr.update(value=schemas_text_for_display)
719
+ return
720
+
721
  logging.info(f"Sending to EB Agent. User: '{user_message}'. DF Keys: {list(dataframes_for_agent.keys())}")
722
  ai_response = await current_agent.process_query(user_query=user_message)
723
 
724
+ # Update the chat history with the AI response
725
+ updated_history = chat_history_list + [[user_message, ai_response]]
 
 
 
 
726
 
727
  status_update_msg = "Stato Agente: Risposta ricevuta."
728
  # Yield final updates for all 5 components
729
+ yield updated_history, updated_history, gr.update(value=""), gr.update(value=status_update_msg), gr.update(value=schemas_text_for_display)
730
+
731
  except Exception as e:
732
  logging.error(f"Error during EB Agent processing: {e}", exc_info=True)
733
  error_msg = f"# Errore dell'Agente AI:\n{type(e).__name__}: {str(e)}"
734
 
735
+ # Update history with error message
736
+ updated_history = chat_history_list + [[user_message, error_msg]]
737
+
 
 
 
 
 
 
 
 
 
738
  status_update_msg = f"Stato Agente: Errore - {type(e).__name__}"
739
  # Yield error updates for all 5 components
740
+ yield updated_history, updated_history, gr.update(value=""), gr.update(value=status_update_msg), gr.update(value=schemas_text_for_display)
741
 
742
 
743
  def clear_eb_agent_chat_history():