GoodLuckChuck commited on
Commit
c5266da
·
verified ·
1 Parent(s): f5d83a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -168
app.py CHANGED
@@ -105,7 +105,7 @@ async def close_shared_http_session():
105
  logger.info("Closed shared aiohttp.ClientSession.")
106
 
107
  # --- Tool Definitions ---
108
- class WebSearchTool(Tool): # Renamed to GoogleSearchTool
109
  name = "web_search" # Keep the original name for the agent to use
110
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
111
  inputs = {"query": {"type": "string", "description": "The search query to execute."},
@@ -121,7 +121,7 @@ class WebSearchTool(Tool): # Renamed to GoogleSearchTool
121
  if provider != "serpapi":
122
  return "Error: Invalid search provider. Only 'serpapi' is supported."
123
 
124
- logger.info(f"WebSearchTool called with query: {query}, provider: {provider}")
125
  serper_api_key = os.environ.get('SERPER_API_KEY')
126
  if not serper_api_key:
127
  logger.error("SERPER_API_KEY not found.")
@@ -167,7 +167,7 @@ class WebSearchTool(Tool): # Renamed to GoogleSearchTool
167
  class QuestionAnsweringAgent(CodeAgent):
168
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
169
  tools = [
170
- WebSearchTool(session=http_session), # Using GoogleSearchTool
171
  ]
172
 
173
  effective_model = model
@@ -207,33 +207,36 @@ class QuestionAnsweringAgent(CodeAgent):
207
  logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
208
 
209
  if hasattr(self, 'additional_authorized_imports'):
210
- self.additional_authorized_imports = ["PIL"] # Make sure PIL is in requirements if needed
211
- logger.info(f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
 
212
  else:
213
- logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
214
-
 
215
  # The CodeWriter is crucial for CodeAgent. It's usually initialized within CodeAgent's __init__.
216
  # If the minimal super call doesn't set it up, the agent might fail to generate code.
217
  # This is a deeper aspect of the workaround's potential side effects.
218
  if not hasattr(self, 'code_writer') or self.code_writer is None:
219
- logger.warning("self.code_writer might not be initialized due to workaround. Agent may fail to generate code.")
220
-
221
 
222
  except TypeError as e:
223
- logger.error(f"WORKAROUND FAILED: Still got TypeError during minimal super().__init__: {e}", exc_info=True)
224
- raise e
225
-
226
- logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
227
 
 
228
 
229
  async def process_question(self, question_text: str) -> Tuple[str, str]:
230
  reasoning_trace = "Agent execution started."
231
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
232
  try:
233
  logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
234
-
235
- raw_output_obj = self.run(question_text)
236
-
237
  if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
238
  full_agent_response = str(raw_output_obj.log_string())
239
  elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
@@ -242,18 +245,20 @@ class QuestionAnsweringAgent(CodeAgent):
242
  full_agent_response = raw_output_obj
243
  elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
244
  full_agent_response = str(raw_output_obj.result)
245
- else:
246
  full_agent_response = str(raw_output_obj)
247
-
248
  reasoning_trace = full_agent_response
249
  logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
250
 
251
- match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
 
252
  if match:
253
  final_answer_for_submission = match.group(1).strip()
254
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
255
  else:
256
- logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
 
257
  final_answer_for_submission = full_agent_response.strip()
258
 
259
  if not final_answer_for_submission:
@@ -265,150 +270,14 @@ class QuestionAnsweringAgent(CodeAgent):
265
  final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
266
  reasoning_trace += f"\nTypeError encountered: {str(te)}"
267
  except Exception as e:
268
- logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
 
269
  final_answer_for_submission = f"Error in agent processing: {str(e)}"
270
  reasoning_trace += f"\nError encountered: {str(e)}"
271
-
272
  return final_answer_for_submission, reasoning_trace
273
 
274
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
275
- class ChuckAgent:
276
- def __init__(self):
277
- required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
278
- missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
279
- if missing_vars:
280
- error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
281
- logger.critical(error_msg)
282
- raise EnvironmentError(error_msg)
283
-
284
- logger.info("ChuckAgent initialization started")
285
- try:
286
- self.loop = asyncio.get_running_loop()
287
- except RuntimeError:
288
- self.loop = asyncio.new_event_loop()
289
- asyncio.set_event_loop(self.loop)
290
-
291
- self.http_session = self.loop.run_until_complete(get_shared_http_session())
292
- self.agent = QuestionAnsweringAgent(http_session=self.http_session) # This might raise if the workaround fails
293
- logger.info("ChuckAgent fully initialized")
294
-
295
- def __call__(self, question: str) -> Tuple[str, str]:
296
- logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
297
- try:
298
- if asyncio.get_event_loop() is not self.loop:
299
- asyncio.set_event_loop(self.loop)
300
-
301
- final_answer, reasoning_trace = self.loop.run_until_complete(
302
- self.agent.process_question(question)
303
- )
304
- logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
305
- return final_answer, reasoning_trace
306
- except Exception as e:
307
- error_msg = f"Error running ChuckAgent: {str(e)}"
308
- logger.error(error_msg, exc_info=True)
309
- return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
310
-
311
- async def shutdown(self):
312
- logger.info("ChuckAgent shutting down...")
313
- await close_shared_http_session()
314
- logger.info("ChuckAgent shutdown complete.")
315
-
316
- # --- Core Evaluation Logic ---
317
- def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
318
- space_id = os.getenv("SPACE_ID")
319
- agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
320
- return space_id, agent_code_url
321
-
322
- def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
323
- questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
324
- logger.info(f"Fetching questions from: {questions_url}")
325
- try:
326
- response = requests.get(questions_url, timeout=30)
327
- response.raise_for_status()
328
- questions_data = response.json()
329
- if not questions_data or not isinstance(questions_data, list):
330
- logger.warning(f"Fetched questions empty or invalid: {questions_data}")
331
- raise ValueError("Fetched questions list is empty or not a list.")
332
- logger.info(f"Fetched {len(questions_data)} questions.")
333
- return questions_data
334
- except requests.exceptions.RequestException as e:
335
- logger.error(f"Error fetching questions: {e}", exc_info=True)
336
- raise ConnectionError(f"Error fetching questions: {e}") from e
337
- except (requests.exceptions.JSONDecodeError, ValueError) as e:
338
- logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
339
- raise ValueError(f"Error decoding server response for questions: {e}") from e
340
-
341
- def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
342
- answers_payload = []
343
- results_log = []
344
- logger.info(f"Running agent on {len(questions_data)} questions...")
345
-
346
- for i, item in enumerate(questions_data):
347
- task_id = item.get("task_id")
348
- question_text = item.get("question")
349
- if not task_id or question_text is None:
350
- logger.warning(f"Skipping item {i+1} with missing data: {item}")
351
- continue
352
- logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
353
- model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
354
- try:
355
- model_ans, reasoning = agent(question_text)
356
- except Exception as e:
357
- logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
358
- model_ans = f"AGENT_CALL_ERROR: {e}"
359
- reasoning = str(e)
360
-
361
- payload_item = {"task_id": task_id, "submitted_answer": model_ans}
362
- if reasoning:
363
- payload_item["reasoning_trace"] = reasoning
364
- answers_payload.append(payload_item)
365
-
366
- results_log.append({
367
- "Task ID": task_id,
368
- "Question": question_text,
369
- "Submitted Answer": model_ans,
370
- "Reasoning Trace": reasoning
371
- })
372
- return answers_payload, results_log
373
-
374
- def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
375
- if not answers_payload:
376
- logger.warning("Agent did not produce any answers to submit.")
377
- return "Agent did not produce any answers to submit."
378
-
379
- submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
380
- submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
381
- logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
382
- try:
383
- response = requests.post(submit_url, json=submission_data, timeout=60)
384
- response.raise_for_status()
385
- result_data = response.json()
386
- return (
387
- f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
388
- f"Overall Score: {result_data.get('score', 'N/A')}% "
389
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
390
- f"Message: {result_data.get('message', 'No message received.')}"
391
- )
392
- except requests.exceptions.HTTPError as e:
393
- error_detail = f"Server responded with {e.response.status_code}."
394
- try:
395
- error_json = e.response.json()
396
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
397
- except requests.exceptions.JSONDecodeError:
398
- error_detail += f" Raw Response: {e.response.text[:500]}"
399
- logger.error(f"Submission Failed: {error_detail}")
400
- return f"Submission Failed: Network error - {e}"
401
- except requests.exceptions.Timeout:
402
- logger.error("Submission Failed: The request timed out.")
403
- return "Submission Failed: The request timed out."
404
- except requests.exceptions.RequestException as e:
405
- logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
406
- return f"Submission Failed: Network error - {e}"
407
- except Exception as e:
408
- logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
409
- return f"An unexpected error occurred: {e}"
410
-
411
- # --- Gradio Interface Main Function ---
412
  GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
413
 
414
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
@@ -427,9 +296,9 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
427
  logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
428
  break
429
  if not found_profile_in_args and profile is None:
430
- logger.error("Could not identify a valid gr.OAuthProfile object.")
431
- return "Login error: Could not identify user profile.", pd.DataFrame()
432
-
433
  logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
434
 
435
  if not profile:
@@ -445,12 +314,12 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
445
 
446
  try:
447
  if GLOBAL_CHUCK_AGENT is None:
448
- GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
449
  agent_instance = GLOBAL_CHUCK_AGENT
450
- except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
451
  logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
452
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
453
- except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError we're fixing
454
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
455
  return f"Error initializing agent: {e}", pd.DataFrame()
456
 
@@ -463,7 +332,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
463
  except Exception as e:
464
  logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
465
  submission_status = f"An unexpected error occurred: {e}"
466
-
467
  results_df = pd.DataFrame(results_log_data if results_log_data else [])
468
  return submission_status, results_df
469
 
@@ -552,5 +421,4 @@ if __name__ == "__main__":
552
  except Exception as e:
553
  logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
554
  else:
555
- logger.info("No active HTTP session or running loop to close in finally block.")
556
- }
 
105
  logger.info("Closed shared aiohttp.ClientSession.")
106
 
107
  # --- Tool Definitions ---
108
+ class GoogleSearchTool(Tool): # Renamed to GoogleSearchTool
109
  name = "web_search" # Keep the original name for the agent to use
110
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
111
  inputs = {"query": {"type": "string", "description": "The search query to execute."},
 
121
  if provider != "serpapi":
122
  return "Error: Invalid search provider. Only 'serpapi' is supported."
123
 
124
+ logger.info(f"GoogleSearchTool called with query: {query}, provider: {provider}")
125
  serper_api_key = os.environ.get('SERPER_API_KEY')
126
  if not serper_api_key:
127
  logger.error("SERPER_API_KEY not found.")
 
167
  class QuestionAnsweringAgent(CodeAgent):
168
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
169
  tools = [
170
+ GoogleSearchTool(session=http_session), # Using GoogleSearchTool
171
  ]
172
 
173
  effective_model = model
 
207
  logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
208
 
209
  if hasattr(self, 'additional_authorized_imports'):
210
+ self.additional_authorized_imports = ["PIL"] # Make sure PIL is in requirements if needed
211
+ logger.info(
212
+ f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
213
  else:
214
+ logger.warning(
215
+ "Could not set 'additional_authorized_imports' as an attribute after init.")
216
+
217
  # The CodeWriter is crucial for CodeAgent. It's usually initialized within CodeAgent's __init__.
218
  # If the minimal super call doesn't set it up, the agent might fail to generate code.
219
  # This is a deeper aspect of the workaround's potential side effects.
220
  if not hasattr(self, 'code_writer') or self.code_writer is None:
221
+ logger.warning(
222
+ "self.code_writer might not be initialized due to workaround. Agent may fail to generate code.")
223
 
224
  except TypeError as e:
225
+ logger.error(
226
+ f"WORKAROUND FAILED: Still got TypeError during minimal super().__init__: {e}",
227
+ exc_info=True)
228
+ raise e
229
 
230
+ logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
231
 
232
  async def process_question(self, question_text: str) -> Tuple[str, str]:
233
  reasoning_trace = "Agent execution started."
234
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
235
  try:
236
  logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
237
+
238
+ raw_output_obj = self.run(question_text)
239
+
240
  if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
241
  full_agent_response = str(raw_output_obj.log_string())
242
  elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
 
245
  full_agent_response = raw_output_obj
246
  elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
247
  full_agent_response = str(raw_output_obj.result)
248
+ else:
249
  full_agent_response = str(raw_output_obj)
250
+
251
  reasoning_trace = full_agent_response
252
  logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
253
 
254
+ match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response,
255
+ re.IGNORECASE | re.DOTALL)
256
  if match:
257
  final_answer_for_submission = match.group(1).strip()
258
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
259
  else:
260
+ logger.warning(
261
+ "Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
262
  final_answer_for_submission = full_agent_response.strip()
263
 
264
  if not final_answer_for_submission:
 
270
  final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
271
  reasoning_trace += f"\nTypeError encountered: {str(te)}"
272
  except Exception as e:
273
+ logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}",
274
+ exc_info=True)
275
  final_answer_for_submission = f"Error in agent processing: {str(e)}"
276
  reasoning_trace += f"\nError encountered: {str(e)}"
277
+
278
  return final_answer_for_submission, reasoning_trace
279
 
280
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
282
 
283
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
 
296
  logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
297
  break
298
  if not found_profile_in_args and profile is None:
299
+ logger.error("Could not identify a valid gr.OAuthProfile object.")
300
+ return "Login error: Could not identify user profile.", pd.DataFrame()
301
+
302
  logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
303
 
304
  if not profile:
 
314
 
315
  try:
316
  if GLOBAL_CHUCK_AGENT is None:
317
+ GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
318
  agent_instance = GLOBAL_CHUCK_AGENT
319
+ except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
320
  logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
321
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
322
+ except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError we're fixing
323
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
324
  return f"Error initializing agent: {e}", pd.DataFrame()
325
 
 
332
  except Exception as e:
333
  logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
334
  submission_status = f"An unexpected error occurred: {e}"
335
+
336
  results_df = pd.DataFrame(results_log_data if results_log_data else [])
337
  return submission_status, results_df
338
 
 
421
  except Exception as e:
422
  logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
423
  else:
424
+ logger.info("No active HTTP session or running loop to close in finally block.")