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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -104
app.py CHANGED
@@ -29,8 +29,8 @@ print("DEBUG: typing and pydantic imported")
29
  PYDANTIC_AI_LOADED = False
30
  try:
31
  from pydantic_ai import Agent
32
- from pydantic_ai.models.openai import OpenAIModel # MODIFIED import
33
- from pydantic_ai.providers.openai import OpenAIProvider # ADDED import
34
  from pydantic_ai.tools import tool as pydantic_tool
35
  print("DEBUG: pydantic-ai components imported successfully.")
36
  PYDANTIC_AI_LOADED = True
@@ -46,14 +46,11 @@ except ImportError as e:
46
  print("DEBUG: Dummy Pydantic AI Agent run called.")
47
  logging.error("Dummy Pydantic AI Agent run called.")
48
  return "Error: pydantic-ai Agent not loaded."
49
- class OpenAIModel: # MODIFIED DUMMY to match new class name
50
- def __init__(self, *args, **kwargs):
51
- print("DEBUG: Dummy Pydantic AI OpenAIModel initialized.")
52
- logging.error("Dummy Pydantic AI OpenAIModel initialized.")
53
- class OpenAIProvider: # ADDED DUMMY
54
- def __init__(self, *args, **kwargs):
55
- print("DEBUG: Dummy Pydantic AI OpenAIProvider initialized.")
56
- logging.error("Dummy Pydantic AI OpenAIProvider initialized.")
57
 
58
 
59
  from datetime import datetime
@@ -134,62 +131,63 @@ print("DEBUG: Utility functions defined.")
134
  # --- Tool Definitions for Pydantic AI ---
135
  print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
136
 
137
- if PYDANTIC_AI_LOADED:
138
- @pydantic_tool(
139
- 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."
140
- )
141
- async def web_search(query: str) -> str:
142
- print(f"DEBUG: Pydantic AI web_search tool called with query: '{query}'")
143
- serper_api_key = os.environ.get('SERPER_API_KEY')
144
- if not serper_api_key:
145
- logger.error("SERPER_API_KEY not found in environment variables.")
146
- print("DEBUG: ERROR - SERPER_API_KEY not found.")
147
- return "Error: Serper API key not found in environment. Cannot perform web search."
148
-
149
- url = "https://google.serper.dev/search"
150
- headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
151
- payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
152
-
153
- async with aiohttp.ClientSession() as session:
154
- try:
155
- async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
156
- response.raise_for_status()
157
- data = await response.json()
158
- print(f"DEBUG: web_search tool received data for query '{query}'.")
159
- results = []
160
- if 'organic' in data and data['organic']:
161
- for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
162
- title = result.get('title', 'N/A')
163
- snippet = result.get('snippet', 'N/A')
164
- results.append(f"Title: {title}\nSnippet: {snippet}\n---")
165
- if not results and 'knowledgeGraph' in data:
166
- kg = data['knowledgeGraph']
167
- title = kg.get('title', '')
168
- description = kg.get('description', '')
169
- if title or description:
170
- results.append(f"Knowledge Graph: {title}\n{description}\n---")
171
- formatted_output = "\n".join(results) if results else "No relevant search results found."
172
- return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
173
- except asyncio.TimeoutError:
174
- logger.error(f"Timeout performing search for '{query}'")
175
- print(f"DEBUG: ERROR - Timeout in web_search tool for query '{query}'.")
176
- return f"Error: Timeout during web search for '{query}'."
177
- except aiohttp.ClientResponseError as e:
178
- logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
179
- print(f"DEBUG: ERROR - HTTP Error {e.status} in web_search tool for query '{query}'.")
180
- return f"Error performing search (HTTP {e.status}): {e.message}"
181
- except aiohttp.ClientError as e:
182
- logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
183
- print(f"DEBUG: ERROR - ClientError in web_search tool for query '{query}': {str(e)}.")
184
- return f"Error performing search (client error): {str(e)}"
185
- except Exception as e:
186
- logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
187
- print(f"DEBUG: ERROR - Unexpected error in web_search tool for query '{query}': {str(e)}.")
188
- return f"Error performing search: An unexpected error occurred."
189
- else:
190
- async def web_search(query: str) -> str:
191
  return "Error: pydantic-ai not loaded, web_search tool unavailable."
192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  print("DEBUG: Defining PydanticQuestionAnsweringAgent (conceptual).")
194
  print("DEBUG: Defining ChuckAgent (modified for Pydantic AI).")
195
 
@@ -207,7 +205,7 @@ class ChuckAgent:
207
  print("DEBUG: ChuckAgent environment variables checked.")
208
 
209
  self.agent_instance: Optional[Agent] = None
210
- self.llm_for_fallback: Optional[OpenAIModel] = None # MODIFIED type hint
211
 
212
  try:
213
  self.loop = asyncio.get_running_loop()
@@ -227,44 +225,51 @@ class ChuckAgent:
227
  print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing Pydantic AI Agent...")
228
  logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
229
  try:
230
- openai_api_key = os.environ.get('OPENAI_API_KEY')
231
- # MODIFIED LLM and Provider instantiation
232
- provider = OpenAIProvider(api_key=openai_api_key)
233
- llm = OpenAIModel(
234
- model_name=CONFIG.OPENAI_MODEL_ID, # Use model_name parameter
235
- provider=provider
236
- )
237
- self.llm_for_fallback = llm
238
 
239
  self.agent_instance = Agent(
240
- llm=llm,
241
- tools=[web_search],
242
  system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
243
- debug=True
244
  )
245
- print("DEBUG: ChuckAgent - Pydantic AI Agent initialized successfully.")
246
- logger.info("Pydantic AI Agent initialized successfully.")
247
  except Exception as e:
248
  print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
249
  logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
250
- raise
 
 
 
 
251
  elif not PYDANTIC_AI_LOADED:
252
- print("DEBUG: ERROR - Pydantic AI library not loaded, cannot initialize agent.")
253
- logger.error("Pydantic AI library not loaded, cannot initialize agent.")
254
- self.agent_instance = Agent() # Dummy agent
 
255
  else:
256
  print("DEBUG: ChuckAgent - Pydantic AI Agent already initialized.")
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 and isinstance(self.agent_instance, globals().get('Agent'))):
264
- logger.error("Pydantic AI Agent instance not available or is a dummy placeholder.")
265
  print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
 
 
 
 
266
  return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized at process time."
267
 
 
268
  try:
269
  agent_final_text_output = await self.agent_instance.run(question_text)
270
  reasoning_trace = str(agent_final_text_output)
@@ -275,7 +280,8 @@ class ChuckAgent:
275
  if match:
276
  final_answer_for_submission = match.group(1).strip()
277
  print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
278
- elif PYDANTIC_AI_LOADED and self.llm_for_fallback:
 
279
  logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
280
  print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
281
  summarizer_messages = [
@@ -295,7 +301,7 @@ class ChuckAgent:
295
  if concise_answer:
296
  if "Could not determine answer from reasoning." in concise_answer:
297
  print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
298
- final_answer_for_submission = "Could not determine answer."
299
  else:
300
  final_answer_for_submission = concise_answer
301
  print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
@@ -306,8 +312,8 @@ class ChuckAgent:
306
  print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
307
  logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
308
  final_answer_for_submission = reasoning_trace.strip()
309
- else:
310
- logger.warning("Could not find 'FINAL ANSWER:' and no LLM fallback possible/applicable. Using agent's full output.")
311
  final_answer_for_submission = reasoning_trace.strip()
312
 
313
  if not final_answer_for_submission:
@@ -324,12 +330,16 @@ class ChuckAgent:
324
  print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
325
  try:
326
  self._ensure_agent_initialized()
327
- if self.agent_instance is None or \
328
- (not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, globals().get('Agent'))):
329
- error_message = "Pydantic AI Agent was not initialized or is a dummy placeholder due to missing 'pydantic-ai' library."
 
 
 
330
  print(f"DEBUG: ERROR - ChuckAgent.__call__ {error_message}")
331
  raise RuntimeError(error_message)
332
 
 
333
  print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
334
  if not self.loop.is_running():
335
  print(f"DEBUG: WARNING - ChuckAgent event loop {self.loop} is not running. Attempting to run _process_question_async directly.")
@@ -345,6 +355,10 @@ class ChuckAgent:
345
  error_msg = f"Error running ChuckAgent (Pydantic AI): {type(e).__name__} - {str(e)}"
346
  print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
347
  logger.error(error_msg, exc_info=True)
 
 
 
 
348
  return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
349
 
350
  async def shutdown_async(self):
@@ -469,7 +483,7 @@ GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
469
 
470
  print("DEBUG: Defining run_and_submit_all_evaluation function.")
471
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
472
- global GLOBAL_CHUCK_AGENT
473
  print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
474
  logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
475
 
@@ -496,8 +510,9 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
496
  results_log_data: List[Dict[str, Any]] = []
497
 
498
  try:
499
- if not PYDANTIC_AI_LOADED: # Check the global flag set during initial imports
500
- error_msg = "CRITICAL ERROR: The 'pydantic-ai' library is not installed correctly or key submodules are missing (e.g., 'pydantic_ai.models' or 'pydantic_ai.providers'). 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."
 
501
  print(f"DEBUG: {error_msg}")
502
  logger.critical(error_msg)
503
  error_df_data = [{"Task ID": "N/A",
@@ -517,12 +532,13 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
517
  agent_instance = GLOBAL_CHUCK_AGENT
518
 
519
  print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
520
- agent_instance._ensure_agent_initialized()
521
  print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
522
 
523
- if agent_instance.agent_instance is None or \
524
- (not PYDANTIC_AI_LOADED and isinstance(agent_instance.agent_instance, globals().get('Agent'))): # Re-check if somehow a dummy was created
525
- critical_error_msg = "Agent initialization failed or resulted in a dummy agent. This typically means 'pydantic-ai' is missing or core configuration (like API keys) is incorrect."
 
526
  logger.critical(critical_error_msg)
527
  print(f"DEBUG: CRITICAL - {critical_error_msg}")
528
  error_df_data = [{"Task ID": "N/A",
@@ -531,6 +547,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
531
  "Reasoning Trace": critical_error_msg}]
532
  return critical_error_msg, pd.DataFrame(error_df_data)
533
 
 
534
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
535
  answers_payload, results_log_data_processed = process_all_questions(agent_instance, questions_data)
536
  results_log_data.extend(results_log_data_processed)
@@ -547,13 +564,13 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
547
  submission_status = str(e)
548
  if not results_log_data:
549
  results_log_data = [{"Task ID": "N/A", "Question": "Connection/Value Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
550
- except RuntimeError as e:
551
  print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
552
  logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
553
  submission_status = f"Runtime Error: {e}"
554
  if not results_log_data:
555
  results_log_data = [{"Task ID": "N/A", "Question": "Runtime Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
556
- except Exception as e:
557
  print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
558
  logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
559
  submission_status = f"An unexpected error occurred: {e}"
@@ -590,7 +607,7 @@ try:
590
  * **Web Search**: Serper API (`google.serper.dev`) via a Pydantic AI tool.
591
  * **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
592
  * **Gradio Version**: This app is tested with `gradio>=4.0`.
593
- * **`pydantic-ai`**: Ensure `pydantic-ai` and its dependencies (like `openai>=1.3.0`) are in `requirements.txt`.
594
  ---
595
  **Disclaimer**: Processing all questions can take some time.
596
  """
@@ -624,11 +641,11 @@ if __name__ == "__main__":
624
  print(f"Gradio Version: {gr.__version__}")
625
  try:
626
  if PYDANTIC_AI_LOADED:
627
- import pydantic_ai # Local import for version access
628
- print(f"pydantic-ai Version: {pydantic_ai.__version__ if hasattr(pydantic_ai, '__version__') else 'unknown (loaded)'}")
629
  else:
630
  print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
631
- except ImportError:
632
  print("pydantic-ai could not be imported during version check (version unknown).")
633
 
634
  if space_host_startup:
 
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
 
46
  print("DEBUG: Dummy Pydantic AI Agent run called.")
47
  logging.error("Dummy Pydantic AI Agent run called.")
48
  return "Error: pydantic-ai Agent not loaded."
49
+ # Dummy for pydantic_tool if its import fails; this is a basic callable
50
+ def pydantic_tool(*args, **kwargs):
51
+ def decorator(func):
52
+ return func
53
+ return decorator
 
 
 
54
 
55
 
56
  from datetime import datetime
 
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}'")
144
+ serper_api_key = os.environ.get('SERPER_API_KEY')
145
+ if not serper_api_key:
146
+ logger.error("SERPER_API_KEY not found in environment variables.")
147
+ print("DEBUG: ERROR - SERPER_API_KEY not found.")
148
+ return "Error: Serper API key not found in environment. Cannot perform web search."
149
+
150
+ url = "https://google.serper.dev/search"
151
+ headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
152
+ payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
153
+
154
+ async with aiohttp.ClientSession() as session:
155
+ try:
156
+ async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
157
+ response.raise_for_status()
158
+ data = await response.json()
159
+ print(f"DEBUG: web_search tool received data for query '{query}'.")
160
+ results = []
161
+ if 'organic' in data and data['organic']:
162
+ for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
163
+ title = result.get('title', 'N/A')
164
+ snippet = result.get('snippet', 'N/A')
165
+ results.append(f"Title: {title}\nSnippet: {snippet}\n---")
166
+ if not results and 'knowledgeGraph' in data:
167
+ kg = data['knowledgeGraph']
168
+ title = kg.get('title', '')
169
+ description = kg.get('description', '')
170
+ if title or description:
171
+ results.append(f"Knowledge Graph: {title}\n{description}\n---")
172
+ formatted_output = "\n".join(results) if results else "No relevant search results found."
173
+ return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
174
+ except asyncio.TimeoutError:
175
+ logger.error(f"Timeout performing search for '{query}'")
176
+ print(f"DEBUG: ERROR - Timeout in web_search tool for query '{query}'.")
177
+ return f"Error: Timeout during web search for '{query}'."
178
+ except aiohttp.ClientResponseError as e:
179
+ logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
180
+ print(f"DEBUG: ERROR - HTTP Error {e.status} in web_search tool for query '{query}'.")
181
+ return f"Error performing search (HTTP {e.status}): {e.message}"
182
+ except aiohttp.ClientError as e:
183
+ logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
184
+ print(f"DEBUG: ERROR - ClientError in web_search tool for query '{query}': {str(e)}.")
185
+ return f"Error performing search (client error): {str(e)}"
186
+ except Exception as e:
187
+ logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
188
+ print(f"DEBUG: ERROR - Unexpected error in web_search tool for query '{query}': {str(e)}.")
189
+ return f"Error performing search: An unexpected error occurred."
190
+
191
  print("DEBUG: Defining PydanticQuestionAnsweringAgent (conceptual).")
192
  print("DEBUG: Defining ChuckAgent (modified for Pydantic AI).")
193
 
 
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()
 
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)
 
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
  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
  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
 
319
  if not final_answer_for_submission:
 
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
  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
 
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
  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}")
517
  logger.critical(error_msg)
518
  error_df_data = [{"Task ID": "N/A",
 
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}")
544
  error_df_data = [{"Task ID": "N/A",
 
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
  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}"
 
607
  * **Web Search**: Serper API (`google.serper.dev`) via a Pydantic AI tool.
608
  * **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
609
  * **Gradio Version**: This app is tested with `gradio>=4.0`.
610
+ * **`pydantic-ai`**: Ensure `pydantic-ai` (version compatible with documentation, e.g., ~0.2.4 based on PDF) and its dependencies (like `openai>=1.3.0`) are in `requirements.txt`.
611
  ---
612
  **Disclaimer**: Processing all questions can take some time.
613
  """
 
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: