GoodLuckChuck commited on
Commit
b106a8f
·
verified ·
1 Parent(s): 5049fca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -131
app.py CHANGED
@@ -15,6 +15,7 @@ try:
15
  from smolagents import CodeAgent, Tool, OpenAIServerModel
16
  except ImportError:
17
  logging.error("Failed to import smolagents. Please ensure it is installed.")
 
18
  class CodeAgent: pass
19
  class Tool: pass
20
  class OpenAIServerModel: pass
@@ -27,12 +28,52 @@ class AppConfig:
27
  QUESTIONS_URL_PATH = "/questions"
28
  SUBMIT_URL_PATH = "/submit"
29
  SCREENSHOTS_DIR = "screenshots"
30
- OPENAI_MODEL_ID = "gpt-3.5-turbo" # Defaulting to faster/cheaper model
31
  SERPER_API_NUM_RESULTS = 3
32
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
33
- AGENT_MAX_STEPS = 10
34
- AGENT_VERBOSITY_LEVEL = 2
35
- AGENT_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  CONFIG = AppConfig()
38
 
@@ -67,10 +108,11 @@ async def close_shared_http_session():
67
 
68
  # --- Tool Definitions ---
69
  class ImageRetrievalTool(Tool):
70
- name = "image_retriever"
71
- description = "Retrieves images from web pages. Input is a URL to an image. Returns a success/error message."
72
- inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
73
  output_type = "string"
 
74
 
75
  def __init__(self, session: aiohttp.ClientSession):
76
  super().__init__()
@@ -86,9 +128,7 @@ class ImageRetrievalTool(Tool):
86
  image_data = await response.read()
87
  image_id = f"image_{self.screenshot_count}"
88
  self.image_memory[image_id] = {
89
- 'data': image_data,
90
- 'url': url,
91
- 'timestamp': datetime.now().isoformat()
92
  }
93
  self.screenshot_count += 1
94
  return f"Image retrieved successfully from {url}. Stored in memory as {image_id}."
@@ -103,10 +143,11 @@ class ImageRetrievalTool(Tool):
103
  return f"Error retrieving image: {str(e)}"
104
 
105
  class WebSearchTool(Tool):
106
- name = "web_search"
107
- description = "Performs web searches using Serper API to find information. Input is a search query."
108
- inputs = {"query": {"type": "string", "description": "The search query to execute"}}
109
  output_type = "string"
 
110
 
111
  def __init__(self, session: aiohttp.ClientSession):
112
  super().__init__()
@@ -155,10 +196,11 @@ class WebSearchTool(Tool):
155
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
156
 
157
  class CalculatorTool(Tool):
158
- name = "calculator"
159
- description = "Performs mathematical calculations. Input is a mathematical expression string (e.g., '2+2*5')."
160
- inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate"}}
161
  output_type = "string"
 
162
 
163
  def __init__(self):
164
  super().__init__()
@@ -169,7 +211,7 @@ class CalculatorTool(Tool):
169
  }
170
  self.allowed_chars = "0123456789+-*/^(). "
171
 
172
- async def forward(self, expression: str) -> str:
173
  logger.info(f"CalculatorTool called with expression: {expression}")
174
  try:
175
  safe_expr = "".join(c for c in expression if c in self.allowed_chars)
@@ -200,88 +242,59 @@ class QuestionAnsweringAgent(CodeAgent):
200
  api_key=openai_api_key
201
  )
202
 
203
- # Call super() with ONLY arguments known to be core for MultiStepAgent
204
- # We will lose system_prompt, verbosity, and additional_imports for now,
205
- # which will likely make the agent not perform as intended, but this is
206
- # to see if the base MultiStepAgent initializes.
207
- try:
208
- super().__init__(
209
- model=effective_model,
210
- tools=tools,
211
- max_steps=CONFIG.AGENT_MAX_STEPS
212
- # system_prompt IS DELIBERATELY OMITTED for this test
213
- # verbosity_level IS DELIBERATELY OMITTED for this test
214
- # additional_authorized_imports IS DELIBERATELY OMITTED for this test
215
- )
216
- logger.info("QuestionAnsweringAgent (CodeAgent) super().__init__ called with minimal args.")
217
-
218
- # If the above works, CodeAgent is initialized but might not have its specific settings.
219
- # We can try to set them now if they are attributes.
220
- # This depends on CodeAgent's internal design.
221
- if hasattr(self, 'system_prompt'):
222
- self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
223
- logger.info(f"Set self.system_prompt to: {self.system_prompt[:50]}...")
224
- else:
225
- logger.warning("CodeAgent instance does not have attribute 'system_prompt' to set after init.")
226
-
227
- if hasattr(self, 'verbosity_level'):
228
- self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
229
- logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
230
- else:
231
- logger.warning("CodeAgent instance does not have attribute 'verbosity_level' to set after init.")
232
-
233
- if hasattr(self, 'additional_authorized_imports'):
234
- self.additional_authorized_imports = ["PIL"]
235
- logger.info(f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
236
- else:
237
- logger.warning("CodeAgent instance does not have attribute 'additional_authorized_imports' to set after init.")
238
-
239
- except TypeError as e:
240
- logger.error(f"Still got TypeError during minimal super().__init__: {e}", exc_info=True)
241
- # This would mean even model, tools, or max_steps is an issue for MultiStepAgent's init
242
- # or CodeAgent itself requires more in its direct init before calling super.
243
- raise e # re-raise the error
244
-
245
  logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
246
 
247
  async def process_question(self, question_text: str) -> Tuple[str, str]:
248
- """Processes a question and returns the final answer and reasoning trace."""
249
  reasoning_trace = "Agent execution started."
250
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
251
  try:
252
  logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
253
- # MODIFICATION: Removed 'await' if self.run() is not async
254
- # This assumes self.run() returns an object that can be converted to string,
255
- # or an object that CodeAgent expects. If self.run() is truly async,
256
- # then AgentText might be an intermediate result not meant to be awaited directly.
257
- raw_output_obj = self.run(question_text)
258
 
259
- # Convert raw_output_obj to string. This might need adjustment
260
- # depending on what self.run() actually returns (e.g., AgentText might have a .text property)
261
- if hasattr(raw_output_obj, 'text'): # Common pattern for such objects
 
 
 
262
  full_agent_response = str(raw_output_obj.text)
263
- elif isinstance(raw_output_obj, str):
264
  full_agent_response = raw_output_obj
265
- else: # Fallback, try to stringify directly
266
- full_agent_response = str(raw_output_obj)
 
 
267
 
268
- reasoning_trace = full_agent_response # Use the full response as the trace
269
-
270
  logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
271
 
272
  match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
273
  if match:
274
  final_answer_for_submission = match.group(1).strip()
 
 
 
275
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
276
  else:
277
  logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback (may be incorrect for submission).")
278
- final_answer_for_submission = full_agent_response.strip()
 
 
 
279
 
280
- if not final_answer_for_submission: # If empty after stripping
281
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
282
  final_answer_for_submission = "Could not determine answer."
283
 
284
- except TypeError as te: # Catching the specific TypeError first
285
  logger.error(f"TypeError during agent processing (likely self.run call): {str(te)}", exc_info=True)
286
  final_answer_for_submission = f"Error in agent processing: {str(te)}"
287
  reasoning_trace += f"\nTypeError encountered: {str(te)}"
@@ -360,41 +373,36 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
360
  raise ValueError(f"Error decoding server response for questions: {e}") from e
361
 
362
  def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
363
- # Level 1 indentation for lines inside the function
364
  answers_payload = []
365
  results_log = []
366
  logger.info(f"Running agent on {len(questions_data)} questions...")
367
 
368
- for i, item in enumerate(questions_data): # Level 1 indentation for the loop itself
369
- # Level 2 indentation for lines inside the for loop
370
  task_id = item.get("task_id")
371
  question_text = item.get("question")
372
  if not task_id or question_text is None:
373
  logger.warning(f"Skipping item {i+1} with missing data: {item}")
374
- continue # This continue is part of the if, which is part of the for
375
  logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
376
  model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
377
- try: # Level 2 for try
378
- # Level 3 for lines inside try
379
  model_ans, reasoning = agent(question_text)
380
- except Exception as e: # Level 2 for except
381
- # Level 3 for lines inside except
382
  logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
383
  model_ans = f"AGENT_CALL_ERROR: {e}"
384
  reasoning = str(e)
385
 
386
- payload_item = {"task_id": task_id, "submitted_answer": model_ans} # Level 2
387
- if reasoning: # Level 2
388
- payload_item["reasoning_trace"] = reasoning # Level 3
389
- answers_payload.append(payload_item) # Level 2
390
 
391
- results_log.append({ # Level 2
392
  "Task ID": task_id,
393
  "Question": question_text,
394
  "Submitted Answer": model_ans,
395
  "Reasoning Trace": reasoning
396
- }) # Level 2 for the closing brace of append's argument
397
- # The for loop has ended. Now, back to Level 1 indentation for the return.
398
  return answers_payload, results_log
399
 
400
  def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
@@ -437,46 +445,32 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
437
  # --- Gradio Interface Main Function ---
438
  GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
439
 
440
- # MODIFIED: Added *args to catch unexpected additional arguments
441
- # and ensure 'profile' is keyword-or-positional
442
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
443
  global GLOBAL_CHUCK_AGENT
444
-
445
- # Log what was actually received
446
  logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
447
  if args:
448
  logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
449
 
450
- # The actual profile data should come from the named 'profile' argument
451
- # due to the 'inputs=[login_button]' mapping.
452
- # If 'profile' is None here but args contains something, it's an issue.
453
-
454
  if not isinstance(profile, gr.OAuthProfile) and profile is not None:
455
- # This can happen if Gradio passes something unexpected as the first argument.
456
- # We could try to see if the profile is in args, but it should be the named parameter.
457
  logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
458
- # Attempt to find the profile in args if it was misplaced
459
  found_profile_in_args = False
460
- for arg in args:
461
- if isinstance(arg, gr.OAuthProfile):
462
- profile = arg
463
  found_profile_in_args = True
464
  logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
465
  break
466
- if not found_profile_in_args and profile is None: # if profile was not None but wrong type, it will still fail below
467
  logger.error("Could not identify a valid gr.OAuthProfile object.")
468
  return "Login error: Could not identify user profile.", pd.DataFrame()
469
-
470
-
471
  logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
472
 
473
-
474
- if not profile: # This check remains important
475
  logger.warning("User not logged in for evaluation.")
476
  return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
477
 
478
  username = profile.username
479
- # ... rest of your function code ...
480
  logger.info(f"User logged in: {username}")
481
 
482
  _, agent_code_url = get_space_id_agent_code_url()
@@ -486,7 +480,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
486
  try:
487
  if GLOBAL_CHUCK_AGENT is None:
488
  GLOBAL_CHUCK_AGENT = ChuckAgent()
489
- agent = GLOBAL_CHUCK_AGENT
490
  except EnvironmentError as e:
491
  logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
492
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
@@ -496,7 +490,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
496
 
497
  try:
498
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
499
- answers_payload, results_log_data = process_all_questions(agent, questions_data)
500
  submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
501
  except (ConnectionError, ValueError) as e:
502
  submission_status = str(e)
@@ -508,10 +502,8 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
508
  return submission_status, results_df
509
 
510
  # --- Build Gradio Interface ---
511
- # This is the UI part that was adjusted to look more like the screenshot
512
  with gr.Blocks() as demo:
513
  gr.Markdown("# Basic Agent Evaluation Runner")
514
-
515
  gr.Markdown(
516
  """
517
  **Instructions:**
@@ -520,20 +512,18 @@ with gr.Blocks() as demo:
520
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
521
  """
522
  )
523
-
524
  gr.Markdown(
525
  """
526
  **Disclaimers:** Once clicking on the "submit" button, it can take quite some time ( this is the time for the agent to go through all the questions). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions in async.
527
  """
528
  )
529
-
530
  gr.Markdown(
531
  f"""
532
  ---
533
  **Technical Notes:**
534
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
535
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
536
- * `requirements.txt` should specify `gradio>=4.19.2` or newer.
537
  * Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` (current default) or `"gpt-4"` in the script for different performance/capability.
538
  """
539
  )
@@ -541,7 +531,7 @@ with gr.Blocks() as demo:
541
  login_button = gr.LoginButton()
542
  run_button = gr.Button("Run Evaluation & Submit All Answers")
543
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
544
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
545
 
546
  run_button.click(
547
  fn=run_and_submit_all_evaluation,
@@ -569,37 +559,31 @@ if __name__ == "__main__":
569
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
570
 
571
  print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
572
- print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}") # For visibility
573
  print("-"*(60 + len(" App Starting ")) + "\n")
574
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
575
 
576
  try:
577
  demo.launch(debug=True, share=False)
578
  finally:
579
- # Attempt to gracefully close the aiohttp session on exit
580
- # This part is a bit tricky with how Gradio's launch() blocks
581
- # and how different environments handle script termination.
582
  loop_to_use = None
583
  if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
584
  loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
585
- elif SHARED_HTTP_SESSION:
586
  loop_to_use = SHARED_HTTP_SESSION.loop
587
 
588
  if loop_to_use and loop_to_use.is_running():
589
  logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
590
- # Ensure we are using the correct event loop that the session was created with.
591
- # This can be complex if multiple loops were involved or if the main loop closed.
592
  try:
593
  current_loop = asyncio.get_event_loop()
594
- if current_loop is not loop_to_use:
595
  asyncio.set_event_loop(loop_to_use)
596
 
597
  if GLOBAL_CHUCK_AGENT:
598
  loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
599
- elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed: # Fallback
600
  loop_to_use.run_until_complete(close_shared_http_session())
601
-
602
- except Exception as e:
603
  logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
604
  else:
605
- logger.info("No active HTTP session or loop to close in finally block.")
 
15
  from smolagents import CodeAgent, Tool, OpenAIServerModel
16
  except ImportError:
17
  logging.error("Failed to import smolagents. Please ensure it is installed.")
18
+ # Dummy classes for script parsing if smolagents is not installed
19
  class CodeAgent: pass
20
  class Tool: pass
21
  class OpenAIServerModel: pass
 
28
  QUESTIONS_URL_PATH = "/questions"
29
  SUBMIT_URL_PATH = "/submit"
30
  SCREENSHOTS_DIR = "screenshots"
31
+ OPENAI_MODEL_ID = "gpt-3.5-turbo" # Sticking with this for speed/cost
32
  SERPER_API_NUM_RESULTS = 3
33
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
34
+ AGENT_MAX_STEPS = 10 # Keep an eye on logs; increase if agent often hits max_steps before solving
35
+ AGENT_VERBOSITY_LEVEL = 2 # Set to 2 for more detailed logs from smolagents
36
+
37
+ # MODIFIED AND ENHANCED AGENT_SYSTEM_PROMPT
38
+ AGENT_SYSTEM_PROMPT = """You are a highly intelligent and meticulous AI assistant. Your primary goal is to answer the user's question accurately and concisely.
39
+ You have access to a specific set of Python tools. You MUST use these exact function names as provided when you decide to use a tool.
40
+ When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
41
+
42
+ Available Tools:
43
+ 1. `web_search(query: str) -> str`: Use this tool to search the internet for current information or information you do not possess. This tool is asynchronous, so your generated code MUST call it using `await`.
44
+ Example of generated code: `print(await web_search(query="current weather in London"))`
45
+ 2. `calculator(expression: str) -> str`: Use this tool for any mathematical calculations. This tool is synchronous.
46
+ Example of generated code: `print(calculator(expression="((1024 / 8) + 55 - 5) * 2"))`
47
+ 3. `image_retriever(url: str) -> str`: Use this tool to retrieve an image from a specific URL. This tool is asynchronous and MUST be called using `await`. It returns a status message about the retrieval (e.g., "Image retrieved successfully...").
48
+ Example of generated code: `print(await image_retriever(url="https://example.com/image.jpg"))`
49
+
50
+ Follow this thought process for every question:
51
+ 1. THOUGHT: Understand the user's question. Identify the core information needed.
52
+ 2. THOUGHT: Decide if one of your available tools (`web_search`, `calculator`, `image_retriever`) can help obtain this information. If yes, state which tool you will use and what input you will provide to it. If no tool is needed, explain that you can answer directly.
53
+ 3. CODE (if using a tool):
54
+ ```python
55
+ # Your Python code to call ONE tool.
56
+ # REMEMBER: Use `await` for `web_search` and `image_retriever`.
57
+ # ALWAYS print the result of the tool call.
58
+ # Example:
59
+ # async_tool_result = await web_search(query="some specific query")
60
+ # print(async_tool_result)
61
+ # sync_tool_result = calculator(expression="1+1")
62
+ # print(sync_tool_result)
63
+ ```<end_code>
64
+ 4. OBSERVATION: [The system will insert the printed output of your tool call here.]
65
+ 5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, what is your next step? (e.g., use another tool, refine a previous tool call, or formulate the answer). If you need to use another tool, go back to step 2.
66
+ 6. If you have the information, formulate the final answer according to the formatting rules.
67
+
68
+ CRITICAL: Your *entire response* to the user for each turn must culminate in the final answer using this exact template on a new line:
69
+ FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
70
+
71
+ Formatting rules for the value in FINAL ANSWER:
72
+ - If the question asks for a number: Provide only the number (e.g., 42). Do not use commas for thousands separation (e.g., use 1234 not 1,234). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
73
+ - If the question asks for a string: Provide the most concise string possible. Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like "NYC" for "New York City") unless the question implies it. Write out numerical digits as words (e.g., "two" instead of 2) unless the question specifically asks for digits.
74
+ - If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., item one,item two,three). NO space after the comma unless it's part of the item itself.
75
+ - If the answer is a calculation result, provide just the number.
76
+ """
77
 
78
  CONFIG = AppConfig()
79
 
 
108
 
109
  # --- Tool Definitions ---
110
  class ImageRetrievalTool(Tool):
111
+ name = "image_retriever" # Exact name LLM must use
112
+ description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
113
+ inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
114
  output_type = "string"
115
+ is_async = True # Hint for some executors, though LLM must generate await
116
 
117
  def __init__(self, session: aiohttp.ClientSession):
118
  super().__init__()
 
128
  image_data = await response.read()
129
  image_id = f"image_{self.screenshot_count}"
130
  self.image_memory[image_id] = {
131
+ 'data': image_data, 'url': url, 'timestamp': datetime.now().isoformat()
 
 
132
  }
133
  self.screenshot_count += 1
134
  return f"Image retrieved successfully from {url}. Stored in memory as {image_id}."
 
143
  return f"Error retrieving image: {str(e)}"
144
 
145
  class WebSearchTool(Tool):
146
+ name = "web_search" # Exact name LLM must use
147
+ description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
148
+ inputs = {"query": {"type": "string", "description": "The search query to execute."}}
149
  output_type = "string"
150
+ is_async = True # Hint for some executors
151
 
152
  def __init__(self, session: aiohttp.ClientSession):
153
  super().__init__()
 
196
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
197
 
198
  class CalculatorTool(Tool):
199
+ name = "calculator" # Exact name LLM must use
200
+ description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
201
+ inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
202
  output_type = "string"
203
+ is_async = False # Explicitly synchronous
204
 
205
  def __init__(self):
206
  super().__init__()
 
211
  }
212
  self.allowed_chars = "0123456789+-*/^(). "
213
 
214
+ async def forward(self, expression: str) -> str: # Still async for Tool compatibility, but logic is sync
215
  logger.info(f"CalculatorTool called with expression: {expression}")
216
  try:
217
  safe_expr = "".join(c for c in expression if c in self.allowed_chars)
 
242
  api_key=openai_api_key
243
  )
244
 
245
+ # Standard call to CodeAgent's __init__
246
+ super().__init__(
247
+ model=effective_model,
248
+ tools=tools,
249
+ system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
250
+ additional_authorized_imports=["PIL"], # Only if LLM might generate code needing PIL
251
+ max_steps=CONFIG.AGENT_MAX_STEPS,
252
+ verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
253
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
255
 
256
  async def process_question(self, question_text: str) -> Tuple[str, str]:
 
257
  reasoning_trace = "Agent execution started."
258
  final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
259
  try:
260
  logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
 
 
 
 
 
261
 
262
+ raw_output_obj = self.run(question_text) # Assuming self.run() is synchronous
263
+
264
+ # Attempt to get the most complete textual output from the agent's run
265
+ if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
266
+ full_agent_response = str(raw_output_obj.log_string())
267
+ elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
268
  full_agent_response = str(raw_output_obj.text)
269
+ elif isinstance(raw_output_obj, str): # If run() itself returns a string
270
  full_agent_response = raw_output_obj
271
+ elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None: # Another common attribute
272
+ full_agent_response = str(raw_output_obj.result)
273
+ else:
274
+ full_agent_response = str(raw_output_obj) # Fallback
275
 
276
+ reasoning_trace = full_agent_response
 
277
  logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
278
 
279
  match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
280
  if match:
281
  final_answer_for_submission = match.group(1).strip()
282
+ # Further clean up if necessary, e.g., removing trailing thoughts if any part of the thought process
283
+ # accidentally got included after "FINAL ANSWER:" due to LLM verbosity.
284
+ # This simple strip might be enough for now.
285
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
286
  else:
287
  logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback (may be incorrect for submission).")
288
+ # If "FINAL ANSWER:" is not found, the LLM didn't follow instructions.
289
+ # The full_agent_response might be just thoughts, or a conversational answer.
290
+ # For submission, this might be penalized.
291
+ final_answer_for_submission = full_agent_response.strip() # Fallback
292
 
293
+ if not final_answer_for_submission:
294
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
295
  final_answer_for_submission = "Could not determine answer."
296
 
297
+ except TypeError as te:
298
  logger.error(f"TypeError during agent processing (likely self.run call): {str(te)}", exc_info=True)
299
  final_answer_for_submission = f"Error in agent processing: {str(te)}"
300
  reasoning_trace += f"\nTypeError encountered: {str(te)}"
 
373
  raise ValueError(f"Error decoding server response for questions: {e}") from e
374
 
375
  def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
 
376
  answers_payload = []
377
  results_log = []
378
  logger.info(f"Running agent on {len(questions_data)} questions...")
379
 
380
+ for i, item in enumerate(questions_data):
 
381
  task_id = item.get("task_id")
382
  question_text = item.get("question")
383
  if not task_id or question_text is None:
384
  logger.warning(f"Skipping item {i+1} with missing data: {item}")
385
+ continue
386
  logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
387
  model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
388
+ try:
 
389
  model_ans, reasoning = agent(question_text)
390
+ except Exception as e:
 
391
  logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
392
  model_ans = f"AGENT_CALL_ERROR: {e}"
393
  reasoning = str(e)
394
 
395
+ payload_item = {"task_id": task_id, "submitted_answer": model_ans}
396
+ if reasoning:
397
+ payload_item["reasoning_trace"] = reasoning
398
+ answers_payload.append(payload_item)
399
 
400
+ results_log.append({
401
  "Task ID": task_id,
402
  "Question": question_text,
403
  "Submitted Answer": model_ans,
404
  "Reasoning Trace": reasoning
405
+ })
 
406
  return answers_payload, results_log
407
 
408
  def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
 
445
  # --- Gradio Interface Main Function ---
446
  GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
447
 
 
 
448
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
449
  global GLOBAL_CHUCK_AGENT
 
 
450
  logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
451
  if args:
452
  logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
453
 
 
 
 
 
454
  if not isinstance(profile, gr.OAuthProfile) and profile is not None:
 
 
455
  logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
 
456
  found_profile_in_args = False
457
+ for arg_val in args: # Renamed arg to arg_val to avoid conflict with outer scope 'args' name
458
+ if isinstance(arg_val, gr.OAuthProfile):
459
+ profile = arg_val
460
  found_profile_in_args = True
461
  logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
462
  break
463
+ if not found_profile_in_args and profile is None:
464
  logger.error("Could not identify a valid gr.OAuthProfile object.")
465
  return "Login error: Could not identify user profile.", pd.DataFrame()
466
+
 
467
  logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
468
 
469
+ if not profile:
 
470
  logger.warning("User not logged in for evaluation.")
471
  return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
472
 
473
  username = profile.username
 
474
  logger.info(f"User logged in: {username}")
475
 
476
  _, agent_code_url = get_space_id_agent_code_url()
 
480
  try:
481
  if GLOBAL_CHUCK_AGENT is None:
482
  GLOBAL_CHUCK_AGENT = ChuckAgent()
483
+ agent_instance = GLOBAL_CHUCK_AGENT # Use a local variable for clarity
484
  except EnvironmentError as e:
485
  logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
486
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
 
490
 
491
  try:
492
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
493
+ answers_payload, results_log_data = process_all_questions(agent_instance, questions_data) # Use agent_instance
494
  submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
495
  except (ConnectionError, ValueError) as e:
496
  submission_status = str(e)
 
502
  return submission_status, results_df
503
 
504
  # --- Build Gradio Interface ---
 
505
  with gr.Blocks() as demo:
506
  gr.Markdown("# Basic Agent Evaluation Runner")
 
507
  gr.Markdown(
508
  """
509
  **Instructions:**
 
512
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
513
  """
514
  )
 
515
  gr.Markdown(
516
  """
517
  **Disclaimers:** Once clicking on the "submit" button, it can take quite some time ( this is the time for the agent to go through all the questions). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions in async.
518
  """
519
  )
 
520
  gr.Markdown(
521
  f"""
522
  ---
523
  **Technical Notes:**
524
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
525
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
526
+ * `requirements.txt` should specify `gradio>=4.19.2` or newer. (`gradio==4.25.0` or a similar fixed version recommended from previous discussions).
527
  * Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` (current default) or `"gpt-4"` in the script for different performance/capability.
528
  """
529
  )
 
531
  login_button = gr.LoginButton()
532
  run_button = gr.Button("Run Evaluation & Submit All Answers")
533
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
534
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # max_rows removed
535
 
536
  run_button.click(
537
  fn=run_and_submit_all_evaluation,
 
559
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
560
 
561
  print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
562
+ print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
563
  print("-"*(60 + len(" App Starting ")) + "\n")
564
  print("Launching Gradio Interface for Chuck Agent Evaluation...")
565
 
566
  try:
567
  demo.launch(debug=True, share=False)
568
  finally:
 
 
 
569
  loop_to_use = None
570
  if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
571
  loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
572
+ elif SHARED_HTTP_SESSION: # Fallback if agent not fully created but session was
573
  loop_to_use = SHARED_HTTP_SESSION.loop
574
 
575
  if loop_to_use and loop_to_use.is_running():
576
  logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
 
 
577
  try:
578
  current_loop = asyncio.get_event_loop()
579
+ if current_loop is not loop_to_use and not loop_to_use.is_closed(): # Check if loop_to_use is not closed
580
  asyncio.set_event_loop(loop_to_use)
581
 
582
  if GLOBAL_CHUCK_AGENT:
583
  loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
584
+ elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
585
  loop_to_use.run_until_complete(close_shared_http_session())
586
+ except Exception as e: # Catch broader exceptions during cleanup
 
587
  logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
588
  else:
589
+ logger.info("No active HTTP session or running loop to close in finally block.")