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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -69
app.py CHANGED
@@ -6,6 +6,7 @@ import asyncio
6
  import re
7
  import json
8
  import logging
 
9
  import aiohttp
10
  from typing import Optional, Dict, Any, List, Tuple
11
 
@@ -44,7 +45,7 @@ You have access to a specific set of Python tools. You MUST use these exact func
44
  When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
45
 
46
  Available Tools:
47
- 1. `web_search(query: str, provider: str = "serpapi") -> str`: Use this tool to search the internet for current information or information you do not possess. The 'provider' parameter MUST be set to "serpapi". This tool is asynchronous, so your generated code MUST call it using `await`. Example: `search_results = await web_search(query="latest news on AI", provider="serpapi")\nprint(search_results)`
48
 
49
  Follow this process for every question:
50
  1. THOUGHT: Understand the user's question. Identify the core information needed.
@@ -104,7 +105,7 @@ async def close_shared_http_session():
104
  logger.info("Closed shared aiohttp.ClientSession.")
105
 
106
  # --- Tool Definitions ---
107
- class GoogleSearchTool(Tool): # Renamed to GoogleSearchTool
108
  name = "web_search" # Keep the original name for the agent to use
109
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
110
  inputs = {"query": {"type": "string", "description": "The search query to execute."},
@@ -120,7 +121,7 @@ class GoogleSearchTool(Tool): # Renamed to GoogleSearchTool
120
  if provider != "serpapi":
121
  return "Error: Invalid search provider. Only 'serpapi' is supported."
122
 
123
- logger.info(f"GoogleSearchTool called with query: {query}, provider: {provider}")
124
  serper_api_key = os.environ.get('SERPER_API_KEY')
125
  if not serper_api_key:
126
  logger.error("SERPER_API_KEY not found.")
@@ -166,15 +167,14 @@ class GoogleSearchTool(Tool): # Renamed to GoogleSearchTool
166
  class QuestionAnsweringAgent(CodeAgent):
167
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
168
  tools = [
169
- GoogleSearchTool(session=http_session), # Using GoogleSearchTool
170
  ]
171
-
172
  effective_model = model
173
  if effective_model is None:
174
  openai_api_key = os.environ.get('OPENAI_API_KEY')
175
  if not openai_api_key:
176
- raise EnvironmentError(
177
- "OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
178
  effective_model = OpenAIServerModel(
179
  model_id=CONFIG.OPENAI_MODEL_ID,
180
  api_key=openai_api_key
@@ -204,40 +204,36 @@ class QuestionAnsweringAgent(CodeAgent):
204
  self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
205
  logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
206
  else:
207
- logger.warning(
208
- "Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
209
 
210
  if hasattr(self, 'additional_authorized_imports'):
211
- self.additional_authorized_imports = ["PIL"] # Make sure PIL is in requirements if needed
212
- logger.info(
213
- f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
214
  else:
215
- logger.warning(
216
- "Could not set 'additional_authorized_imports' as an attribute after init.")
217
-
218
  # The CodeWriter is crucial for CodeAgent. It's usually initialized within CodeAgent's __init__.
219
  # If the minimal super call doesn't set it up, the agent might fail to generate code.
220
  # This is a deeper aspect of the workaround's potential side effects.
221
  if not hasattr(self, 'code_writer') or self.code_writer is None:
222
- logger.warning(
223
- "self.code_writer might not be initialized due to workaround. Agent may fail to generate code.")
224
 
225
- except TypeError as e:
226
- logger.error(
227
- f"WORKAROUND FAILED: Still got TypeError during minimal super().__init__: {e}",
228
- exc_info=True)
229
- raise e
230
 
 
 
 
 
231
  logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
232
 
 
233
  async def process_question(self, question_text: str) -> Tuple[str, str]:
234
  reasoning_trace = "Agent execution started."
235
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
236
  try:
237
  logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
238
-
239
- raw_output_obj = self.run(question_text)
240
-
241
  if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
242
  full_agent_response = str(raw_output_obj.log_string())
243
  elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
@@ -246,20 +242,18 @@ class QuestionAnsweringAgent(CodeAgent):
246
  full_agent_response = raw_output_obj
247
  elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
248
  full_agent_response = str(raw_output_obj.result)
249
- else:
250
  full_agent_response = str(raw_output_obj)
251
-
252
  reasoning_trace = full_agent_response
253
  logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
254
 
255
- match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response,
256
- re.IGNORECASE | re.DOTALL)
257
  if match:
258
  final_answer_for_submission = match.group(1).strip()
259
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
260
  else:
261
- logger.warning(
262
- "Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
263
  final_answer_for_submission = full_agent_response.strip()
264
 
265
  if not final_answer_for_submission:
@@ -271,11 +265,10 @@ class QuestionAnsweringAgent(CodeAgent):
271
  final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
272
  reasoning_trace += f"\nTypeError encountered: {str(te)}"
273
  except Exception as e:
274
- logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}",
275
- exc_info=True)
276
  final_answer_for_submission = f"Error in agent processing: {str(e)}"
277
  reasoning_trace += f"\nError encountered: {str(e)}"
278
-
279
  return final_answer_for_submission, reasoning_trace
280
 
281
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
@@ -287,7 +280,7 @@ class ChuckAgent:
287
  error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
288
  logger.critical(error_msg)
289
  raise EnvironmentError(error_msg)
290
-
291
  logger.info("ChuckAgent initialization started")
292
  try:
293
  self.loop = asyncio.get_running_loop()
@@ -296,21 +289,18 @@ class ChuckAgent:
296
  asyncio.set_event_loop(self.loop)
297
 
298
  self.http_session = self.loop.run_until_complete(get_shared_http_session())
299
- self.agent = QuestionAnsweringAgent(
300
- http_session=self.http_session) # This might raise if the workaround fails
301
  logger.info("ChuckAgent fully initialized")
302
-
303
  def __call__(self, question: str) -> Tuple[str, str]:
304
  logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
305
  try:
306
  if asyncio.get_event_loop() is not self.loop:
307
- asyncio.set_event_loop(self.loop)
308
-
309
- # Schedule the agent's processing within the current event loop
310
- agent_task = asyncio.ensure_future(self.agent.process_question(question),
311
- loop=self.loop)
312
- final_answer, reasoning_trace = self.loop.run_until_complete(agent_task)
313
 
 
 
 
314
  logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
315
  return final_answer, reasoning_trace
316
  except Exception as e:
@@ -345,13 +335,10 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
345
  logger.error(f"Error fetching questions: {e}", exc_info=True)
346
  raise ConnectionError(f"Error fetching questions: {e}") from e
347
  except (requests.exceptions.JSONDecodeError, ValueError) as e:
348
- logger.error(
349
- f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}",
350
- exc_info=True)
351
  raise ValueError(f"Error decoding server response for questions: {e}") from e
352
 
353
- def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[
354
- List[Dict[str, Any]], List[Dict[str, Any]]]:
355
  answers_payload = []
356
  results_log = []
357
  logger.info(f"Running agent on {len(questions_data)} questions...")
@@ -360,9 +347,9 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
360
  task_id = item.get("task_id")
361
  question_text = item.get("question")
362
  if not task_id or question_text is None:
363
- logger.warning(f"Skipping item {i + 1} with missing data: {item}")
364
  continue
365
- logger.info(f"Processing task {i + 1}/{len(questions_data)}, ID: {task_id}")
366
  model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
367
  try:
368
  model_ans, reasoning = agent(question_text)
@@ -370,29 +357,27 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
370
  logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
371
  model_ans = f"AGENT_CALL_ERROR: {e}"
372
  reasoning = str(e)
373
-
374
- payload_item = {"task_id": task_id, "submitted_answer": model_ans}
375
- if reasoning:
376
  payload_item["reasoning_trace"] = reasoning
377
  answers_payload.append(payload_item)
378
-
379
  results_log.append({
380
- "Task ID": task_id,
381
- "Question": question_text,
382
- "Submitted Answer": model_ans,
383
  "Reasoning Trace": reasoning
384
  })
385
  return answers_payload, results_log
386
 
387
- def submit_answers(base_api_url: str, username: str, agent_code_url: str,
388
- answers_payload: List[Dict[str, Any]]) -> str:
389
  if not answers_payload:
390
  logger.warning("Agent did not produce any answers to submit.")
391
  return "Agent did not produce any answers to submit."
392
 
393
  submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
394
- submission_data = {"username": username.strip(), "agent_code": agent_code_url,
395
- "answers": answers_payload}
396
  logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
397
  try:
398
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -442,9 +427,9 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
442
  logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
443
  break
444
  if not found_profile_in_args and profile is None:
445
- logger.error("Could not identify a valid gr.OAuthProfile object.")
446
- return "Login error: Could not identify user profile.", pd.DataFrame()
447
-
448
  logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
449
 
450
  if not profile:
@@ -460,12 +445,12 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
460
 
461
  try:
462
  if GLOBAL_CHUCK_AGENT is None:
463
- GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
464
  agent_instance = GLOBAL_CHUCK_AGENT
465
- except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
466
  logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
467
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
468
- except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError we're fixing
469
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
470
  return f"Error initializing agent: {e}", pd.DataFrame()
471
 
@@ -478,7 +463,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
478
  except Exception as e:
479
  logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
480
  submission_status = f"An unexpected error occurred: {e}"
481
-
482
  results_df = pd.DataFrame(results_log_data if results_log_data else [])
483
  return submission_status, results_df
484
 
 
6
  import re
7
  import json
8
  import logging
9
+ import operator # Used by CalculatorTool
10
  import aiohttp
11
  from typing import Optional, Dict, Any, List, Tuple
12
 
 
45
  When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
46
 
47
  Available Tools:
48
+ 1. `web_search(query: str, provider: str) -> str`: Use this tool to search the internet for current information. The 'provider' parameter MUST be set to "serpapi". This tool is asynchronous, so your generated code MUST call it using `await`. Example: `search_results = await web_search(query="latest news on AI", provider="serpapi")\nprint(search_results)`
49
 
50
  Follow this process for every question:
51
  1. THOUGHT: Understand the user's question. Identify the core information needed.
 
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
  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
  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
174
  if effective_model is None:
175
  openai_api_key = os.environ.get('OPENAI_API_KEY')
176
  if not openai_api_key:
177
+ raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
 
178
  effective_model = OpenAIServerModel(
179
  model_id=CONFIG.OPENAI_MODEL_ID,
180
  api_key=openai_api_key
 
204
  self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
205
  logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
206
  else:
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
  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
  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) ---
 
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()
 
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:
 
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...")
 
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)
 
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)
 
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
 
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
  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