GoodLuckChuck commited on
Commit
5a64626
·
verified ·
1 Parent(s): 42fc37a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -54
app.py CHANGED
@@ -29,8 +29,6 @@ print("DEBUG: typing and pydantic imported")
29
  PYDANTIC_AI_LOADED = False
30
  try:
31
  from pydantic_ai import Agent
32
- # Assuming 'pydantic_ai.tools' might still be a valid module for the decorator.
33
- # If this causes a new error, it will need to be addressed.
34
  from pydantic_ai.tools import tool as pydantic_tool
35
  print("DEBUG: pydantic-ai components imported successfully.")
36
  PYDANTIC_AI_LOADED = True
@@ -131,13 +129,11 @@ print("DEBUG: Utility functions defined.")
131
  # --- Tool Definitions for Pydantic AI ---
132
  print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
133
 
134
- # The web_search tool definition. It will be decorated if PYDANTIC_AI_LOADED is True.
135
- # If PYDANTIC_AI_LOADED is False, pydantic_tool will be the dummy decorator.
136
  @pydantic_tool(
137
  description="Searches the web using Serper API for information. Use this for current events or information not in your knowledge base. Input is the search query."
138
  )
139
  async def web_search(query: str) -> str:
140
- if not PYDANTIC_AI_LOADED: # Explicit check inside if decorator is dummy
141
  return "Error: pydantic-ai not loaded, web_search tool unavailable."
142
 
143
  print(f"DEBUG: Pydantic AI web_search tool called with query: '{query}'")
@@ -203,10 +199,7 @@ class ChuckAgent:
203
  logger.critical(error_msg)
204
  raise EnvironmentError(error_msg)
205
  print("DEBUG: ChuckAgent environment variables checked.")
206
-
207
  self.agent_instance: Optional[Agent] = None
208
- # self.llm_for_fallback removed as it's not directly used by the new Agent init or the direct OpenAI client fallback
209
-
210
  try:
211
  self.loop = asyncio.get_running_loop()
212
  print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
@@ -215,73 +208,64 @@ class ChuckAgent:
215
  self.loop = asyncio.new_event_loop()
216
  asyncio.set_event_loop(self.loop)
217
  print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
218
-
219
  logger.info("ChuckAgent basic initialization complete. Pydantic AI Agent will be created on first use.")
220
  print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")
221
 
222
  def _ensure_agent_initialized(self):
 
223
  print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
224
- if self.agent_instance is None and PYDANTIC_AI_LOADED:
225
  print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing Pydantic AI Agent...")
226
  logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
227
  try:
228
- # API key is expected to be picked up from environment by pydantic-ai
229
- # when using the string model identifier.
230
  model_identifier = f"openai:{CONFIG.OPENAI_MODEL_ID}"
231
  print(f"DEBUG: Initializing Pydantic AI Agent with model identifier: {model_identifier}")
232
-
233
  self.agent_instance = Agent(
234
- model_identifier, # Pass the model string directly
235
- tools=[web_search], # Pass the function; pydantic-ai handles decorated tools
236
  system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
237
- debug=True
238
  )
239
  print("DEBUG: ChuckAgent - Pydantic AI Agent initialized successfully with model string.")
240
  logger.info("Pydantic AI Agent initialized successfully with model string.")
241
  except Exception as e:
242
  print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
243
  logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
244
- # Set PYDANTIC_AI_LOADED to False here if init fails, so fallback kicks in
245
- global PYDANTIC_AI_LOADED
246
- PYDANTIC_AI_LOADED = False # Crucial for error handling flow
247
- self.agent_instance = Agent() # Use dummy agent on failure
248
- raise # Re-raise to be caught by run_and_submit_all_evaluation
249
- elif not PYDANTIC_AI_LOADED:
250
  print("DEBUG: ERROR - Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
251
  logger.error("Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
252
- if self.agent_instance is None: # Ensure dummy is created if not already
253
- self.agent_instance = Agent() # Dummy agent
254
  else:
255
  print("DEBUG: ChuckAgent - Pydantic AI Agent already initialized.")
256
 
257
-
258
  async def _process_question_async(self, question_text: str) -> Tuple[str, str]:
259
  print(f"DEBUG: ChuckAgent._process_question_async called for: '{question_text[:100]}...'")
260
  reasoning_trace = "Pydantic AI Agent execution started."
261
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
262
 
263
- if self.agent_instance is None or not PYDANTIC_AI_LOADED: # Simplified check
264
  logger.error("Pydantic AI Agent instance not available or library not loaded.")
265
  print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
266
- # Return the dummy agent's error message if that's what self.agent_instance is holding
267
- if hasattr(self.agent_instance, 'run'):
268
- dummy_error = await self.agent_instance.run("") # Get dummy error
269
  return dummy_error, "Agent not properly initialized or pydantic-ai not loaded."
270
  return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized at process time."
271
 
272
-
273
  try:
274
  agent_final_text_output = await self.agent_instance.run(question_text)
275
  reasoning_trace = str(agent_final_text_output)
276
-
277
  print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")
278
  match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)
279
 
280
  if match:
281
  final_answer_for_submission = match.group(1).strip()
282
  print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
283
- # Fallback condition modified: only check PYDANTIC_AI_LOADED
284
- elif PYDANTIC_AI_LOADED: # If pydantic-ai was meant to be loaded and working
285
  logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
286
  print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
287
  summarizer_messages = [
@@ -301,7 +285,7 @@ class ChuckAgent:
301
  if concise_answer:
302
  if "Could not determine answer from reasoning." in concise_answer:
303
  print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
304
- final_answer_for_submission = "Could not determine answer from reasoning." # More specific
305
  else:
306
  final_answer_for_submission = concise_answer
307
  print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
@@ -312,7 +296,7 @@ class ChuckAgent:
312
  print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
313
  logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
314
  final_answer_for_submission = reasoning_trace.strip()
315
- else: # No FINAL ANSWER and PYDANTIC_AI_LOADED is false (so we used dummy agent)
316
  logger.warning("Could not find 'FINAL ANSWER:' and Pydantic AI not loaded. Using agent's (dummy) full output.")
317
  final_answer_for_submission = reasoning_trace.strip()
318
 
@@ -327,19 +311,17 @@ class ChuckAgent:
327
  return final_answer_for_submission, reasoning_trace
328
 
329
  def __call__(self, question: str) -> Tuple[str, str]:
 
330
  print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
331
  try:
332
  self._ensure_agent_initialized()
333
- # PYDANTIC_AI_LOADED flag is now the main gatekeeper for real vs dummy agent behavior
334
  if not PYDANTIC_AI_LOADED and self.agent_instance is not None:
335
- # This means we are using the dummy agent because PYDANTIC_AI_LOADED is false
336
  print("DEBUG: ChuckAgent.__call__ - PYDANTIC_AI_LOADED is False, expecting dummy agent behavior.")
337
- elif self.agent_instance is None: # Should not happen if _ensure_agent_initialized works
338
  error_message = "Pydantic AI Agent instance is None after initialization attempt."
339
  print(f"DEBUG: ERROR - ChuckAgent.__call__ {error_message}")
340
  raise RuntimeError(error_message)
341
 
342
-
343
  print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
344
  if not self.loop.is_running():
345
  print(f"DEBUG: WARNING - ChuckAgent event loop {self.loop} is not running. Attempting to run _process_question_async directly.")
@@ -355,10 +337,8 @@ class ChuckAgent:
355
  error_msg = f"Error running ChuckAgent (Pydantic AI): {type(e).__name__} - {str(e)}"
356
  print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
357
  logger.error(error_msg, exc_info=True)
358
- # Ensure PYDANTIC_AI_LOADED reflects failure if error happens here related to agent setup
359
- global PYDANTIC_AI_LOADED
360
- if "Pydantic AI Agent was not initialized" in str(e) or "dummy placeholder" in str(e):
361
- PYDANTIC_AI_LOADED = False
362
  return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
363
 
364
  async def shutdown_async(self):
@@ -483,7 +463,7 @@ GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
483
 
484
  print("DEBUG: Defining run_and_submit_all_evaluation function.")
485
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
486
- global GLOBAL_CHUCK_AGENT, PYDANTIC_AI_LOADED # Ensure PYDANTIC_AI_LOADED can be modified if init fails
487
  print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
488
  logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
489
 
@@ -510,7 +490,6 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
510
  results_log_data: List[Dict[str, Any]] = []
511
 
512
  try:
513
- # This check is now based on the initial import attempt for pydantic-ai components
514
  if not PYDANTIC_AI_LOADED:
515
  error_msg = "CRITICAL ERROR: The 'pydantic-ai' library or its core components could not be imported. The Agent cannot function. Please ensure 'pydantic-ai' is correctly installed (e.g., in requirements.txt) and the environment is correctly set up, then restart the application. Check logs for specific import error."
516
  print(f"DEBUG: {error_msg}")
@@ -532,12 +511,10 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
532
  agent_instance = GLOBAL_CHUCK_AGENT
533
 
534
  print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
535
- agent_instance._ensure_agent_initialized() # This might raise an error if agent init fails
536
  print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
537
 
538
- # After _ensure_agent_initialized, PYDANTIC_AI_LOADED might have been set to False
539
- # if the agent initialization step itself failed. Re-check.
540
- if not PYDANTIC_AI_LOADED:
541
  critical_error_msg = "Agent initialization failed post-import or a secondary import within Agent init failed. PydanticAI is not usable."
542
  logger.critical(critical_error_msg)
543
  print(f"DEBUG: CRITICAL - {critical_error_msg}")
@@ -547,7 +524,6 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
547
  "Reasoning Trace": critical_error_msg}]
548
  return critical_error_msg, pd.DataFrame(error_df_data)
549
 
550
-
551
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
552
  answers_payload, results_log_data_processed = process_all_questions(agent_instance, questions_data)
553
  results_log_data.extend(results_log_data_processed)
@@ -564,13 +540,13 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
564
  submission_status = str(e)
565
  if not results_log_data:
566
  results_log_data = [{"Task ID": "N/A", "Question": "Connection/Value Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
567
- except RuntimeError as e: # Catches issues like agent not initialized properly if it raises RuntimeError from __call__
568
  print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
569
  logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
570
  submission_status = f"Runtime Error: {e}"
571
  if not results_log_data:
572
  results_log_data = [{"Task ID": "N/A", "Question": "Runtime Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
573
- except Exception as e: # Catch-all for other unexpected errors
574
  print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
575
  logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
576
  submission_status = f"An unexpected error occurred: {e}"
@@ -641,11 +617,11 @@ if __name__ == "__main__":
641
  print(f"Gradio Version: {gr.__version__}")
642
  try:
643
  if PYDANTIC_AI_LOADED:
644
- import pydantic_ai
645
  print(f"pydantic-ai Version: {pydantic_ai.__version__ if hasattr(pydantic_ai, '__version__') else 'unknown (loaded, but version attribute missing)'}")
646
  else:
647
  print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
648
- except ImportError: # Should have been caught by PYDANTIC_AI_LOADED already
649
  print("pydantic-ai could not be imported during version check (version unknown).")
650
 
651
  if space_host_startup:
 
29
  PYDANTIC_AI_LOADED = False
30
  try:
31
  from pydantic_ai import Agent
 
 
32
  from pydantic_ai.tools import tool as pydantic_tool
33
  print("DEBUG: pydantic-ai components imported successfully.")
34
  PYDANTIC_AI_LOADED = True
 
129
  # --- Tool Definitions for Pydantic AI ---
130
  print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
131
 
 
 
132
  @pydantic_tool(
133
  description="Searches the web using Serper API for information. Use this for current events or information not in your knowledge base. Input is the search query."
134
  )
135
  async def web_search(query: str) -> str:
136
+ if not PYDANTIC_AI_LOADED:
137
  return "Error: pydantic-ai not loaded, web_search tool unavailable."
138
 
139
  print(f"DEBUG: Pydantic AI web_search tool called with query: '{query}'")
 
199
  logger.critical(error_msg)
200
  raise EnvironmentError(error_msg)
201
  print("DEBUG: ChuckAgent environment variables checked.")
 
202
  self.agent_instance: Optional[Agent] = None
 
 
203
  try:
204
  self.loop = asyncio.get_running_loop()
205
  print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
 
208
  self.loop = asyncio.new_event_loop()
209
  asyncio.set_event_loop(self.loop)
210
  print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
 
211
  logger.info("ChuckAgent basic initialization complete. Pydantic AI Agent will be created on first use.")
212
  print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")
213
 
214
  def _ensure_agent_initialized(self):
215
+ global PYDANTIC_AI_LOADED # Moved to the top
216
  print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
217
+ if self.agent_instance is None and PYDANTIC_AI_LOADED: # Reads PYDANTIC_AI_LOADED
218
  print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing Pydantic AI Agent...")
219
  logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
220
  try:
 
 
221
  model_identifier = f"openai:{CONFIG.OPENAI_MODEL_ID}"
222
  print(f"DEBUG: Initializing Pydantic AI Agent with model identifier: {model_identifier}")
 
223
  self.agent_instance = Agent(
224
+ model_identifier,
225
+ tools=[web_search],
226
  system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
227
+ debug=True
228
  )
229
  print("DEBUG: ChuckAgent - Pydantic AI Agent initialized successfully with model string.")
230
  logger.info("Pydantic AI Agent initialized successfully with model string.")
231
  except Exception as e:
232
  print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
233
  logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
234
+ PYDANTIC_AI_LOADED = False # Modifies PYDANTIC_AI_LOADED
235
+ if self.agent_instance is None: # Ensure dummy if real one failed
236
+ self.agent_instance = Agent()
237
+ raise
238
+ elif not PYDANTIC_AI_LOADED: # Reads PYDANTIC_AI_LOADED
 
239
  print("DEBUG: ERROR - Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
240
  logger.error("Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
241
+ if self.agent_instance is None:
242
+ self.agent_instance = Agent()
243
  else:
244
  print("DEBUG: ChuckAgent - Pydantic AI Agent already initialized.")
245
 
 
246
  async def _process_question_async(self, question_text: str) -> Tuple[str, str]:
247
  print(f"DEBUG: ChuckAgent._process_question_async called for: '{question_text[:100]}...'")
248
  reasoning_trace = "Pydantic AI Agent execution started."
249
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
250
 
251
+ if self.agent_instance is None or not PYDANTIC_AI_LOADED:
252
  logger.error("Pydantic AI Agent instance not available or library not loaded.")
253
  print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
254
+ if hasattr(self.agent_instance, 'run'): # Check if it's the dummy with a run method
255
+ dummy_error = await self.agent_instance.run("")
 
256
  return dummy_error, "Agent not properly initialized or pydantic-ai not loaded."
257
  return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized at process time."
258
 
 
259
  try:
260
  agent_final_text_output = await self.agent_instance.run(question_text)
261
  reasoning_trace = str(agent_final_text_output)
 
262
  print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")
263
  match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)
264
 
265
  if match:
266
  final_answer_for_submission = match.group(1).strip()
267
  print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
268
+ elif PYDANTIC_AI_LOADED:
 
269
  logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
270
  print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
271
  summarizer_messages = [
 
285
  if concise_answer:
286
  if "Could not determine answer from reasoning." in concise_answer:
287
  print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
288
+ final_answer_for_submission = "Could not determine answer from reasoning."
289
  else:
290
  final_answer_for_submission = concise_answer
291
  print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
 
296
  print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
297
  logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
298
  final_answer_for_submission = reasoning_trace.strip()
299
+ else:
300
  logger.warning("Could not find 'FINAL ANSWER:' and Pydantic AI not loaded. Using agent's (dummy) full output.")
301
  final_answer_for_submission = reasoning_trace.strip()
302
 
 
311
  return final_answer_for_submission, reasoning_trace
312
 
313
  def __call__(self, question: str) -> Tuple[str, str]:
314
+ global PYDANTIC_AI_LOADED # Moved to the top
315
  print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
316
  try:
317
  self._ensure_agent_initialized()
 
318
  if not PYDANTIC_AI_LOADED and self.agent_instance is not None:
 
319
  print("DEBUG: ChuckAgent.__call__ - PYDANTIC_AI_LOADED is False, expecting dummy agent behavior.")
320
+ elif self.agent_instance is None:
321
  error_message = "Pydantic AI Agent instance is None after initialization attempt."
322
  print(f"DEBUG: ERROR - ChuckAgent.__call__ {error_message}")
323
  raise RuntimeError(error_message)
324
 
 
325
  print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
326
  if not self.loop.is_running():
327
  print(f"DEBUG: WARNING - ChuckAgent event loop {self.loop} is not running. Attempting to run _process_question_async directly.")
 
337
  error_msg = f"Error running ChuckAgent (Pydantic AI): {type(e).__name__} - {str(e)}"
338
  print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
339
  logger.error(error_msg, exc_info=True)
340
+ if "Pydantic AI Agent was not initialized" in str(e) or "dummy placeholder" in str(e) or "Agent instance is None" in str(e):
341
+ PYDANTIC_AI_LOADED = False # Modifies global
 
 
342
  return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
343
 
344
  async def shutdown_async(self):
 
463
 
464
  print("DEBUG: Defining run_and_submit_all_evaluation function.")
465
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
466
+ global GLOBAL_CHUCK_AGENT, PYDANTIC_AI_LOADED
467
  print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
468
  logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
469
 
 
490
  results_log_data: List[Dict[str, Any]] = []
491
 
492
  try:
 
493
  if not PYDANTIC_AI_LOADED:
494
  error_msg = "CRITICAL ERROR: The 'pydantic-ai' library or its core components could not be imported. The Agent cannot function. Please ensure 'pydantic-ai' is correctly installed (e.g., in requirements.txt) and the environment is correctly set up, then restart the application. Check logs for specific import error."
495
  print(f"DEBUG: {error_msg}")
 
511
  agent_instance = GLOBAL_CHUCK_AGENT
512
 
513
  print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
514
+ agent_instance._ensure_agent_initialized()
515
  print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
516
 
517
+ if not PYDANTIC_AI_LOADED: # Re-check after _ensure_agent_initialized
 
 
518
  critical_error_msg = "Agent initialization failed post-import or a secondary import within Agent init failed. PydanticAI is not usable."
519
  logger.critical(critical_error_msg)
520
  print(f"DEBUG: CRITICAL - {critical_error_msg}")
 
524
  "Reasoning Trace": critical_error_msg}]
525
  return critical_error_msg, pd.DataFrame(error_df_data)
526
 
 
527
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
528
  answers_payload, results_log_data_processed = process_all_questions(agent_instance, questions_data)
529
  results_log_data.extend(results_log_data_processed)
 
540
  submission_status = str(e)
541
  if not results_log_data:
542
  results_log_data = [{"Task ID": "N/A", "Question": "Connection/Value Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
543
+ except RuntimeError as e:
544
  print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
545
  logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
546
  submission_status = f"Runtime Error: {e}"
547
  if not results_log_data:
548
  results_log_data = [{"Task ID": "N/A", "Question": "Runtime Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
549
+ except Exception as e:
550
  print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
551
  logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
552
  submission_status = f"An unexpected error occurred: {e}"
 
617
  print(f"Gradio Version: {gr.__version__}")
618
  try:
619
  if PYDANTIC_AI_LOADED:
620
+ import pydantic_ai
621
  print(f"pydantic-ai Version: {pydantic_ai.__version__ if hasattr(pydantic_ai, '__version__') else 'unknown (loaded, but version attribute missing)'}")
622
  else:
623
  print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
624
+ except ImportError:
625
  print("pydantic-ai could not be imported during version check (version unknown).")
626
 
627
  if space_host_startup: