GoodLuckChuck commited on
Commit
98644f2
·
verified ·
1 Parent(s): 3812c47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +418 -171
app.py CHANGED
@@ -6,24 +6,33 @@ import asyncio
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
 
13
  # Import necessary components from smolagents
14
  try:
15
  from smolagents import CodeAgent, Tool, OpenAIServerModel
16
- except ImportError:
17
- logging.error("Failed to import smolagents. Please ensure it is installed.")
18
-
19
- # Dummy classes for script parsing if smolagents is not installed
20
  class CodeAgent:
 
 
 
 
 
21
  pass
22
 
23
  class Tool:
 
 
24
  pass
25
 
26
  class OpenAIServerModel:
 
 
27
  pass
28
 
29
  from datetime import datetime
@@ -33,12 +42,12 @@ class AppConfig:
33
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
34
  QUESTIONS_URL_PATH = "/questions"
35
  SUBMIT_URL_PATH = "/submit"
36
- SCREENSHOTS_DIR = "screenshots"
37
- OPENAI_MODEL_ID = "gpt-4o"
38
  SERPER_API_NUM_RESULTS = 3
39
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
40
  AGENT_MAX_STEPS = 10
41
- AGENT_VERBOSITY_LEVEL = 2
42
 
43
  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.
44
  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.
@@ -68,7 +77,7 @@ FINAL ANSWER: [Your concise answer, strictly following the formatting rules belo
68
 
69
  Formatting rules for the value in FINAL ANSWER:
70
  - If the question asks for a number: Provide only the number itself (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.
71
- - 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 numerical digits are requested.
72
  - 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.
73
  - If the answer is a calculation result, provide just the number.
74
  """
@@ -83,48 +92,51 @@ logger = logging.getLogger(__name__)
83
 
84
  # --- Utility Functions ---
85
  def ensure_dir_exists(directory_path: str):
 
86
  os.makedirs(directory_path, exist_ok=True)
87
 
88
  ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
89
 
 
 
 
 
 
 
 
 
 
 
90
  # --- HTTP Client Session Management ---
91
- SHARED_HTTP_SESSION: Optional[aiohttp.ClientSession] = None
92
-
93
- async def get_shared_http_session() -> aiohttp.ClientSession:
94
- global SHARED_HTTP_SESSION
95
- if SHARED_HTTP_SESSION is None or SHARED_HTTP_SESSION.closed:
96
- SHARED_HTTP_SESSION = aiohttp.ClientSession()
97
- logger.info("Created shared aiohttp.ClientSession.")
98
- return SHARED_HTTP_SESSION
99
-
100
- async def close_shared_http_session():
101
- global SHARED_HTTP_SESSION
102
- if SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
103
- await SHARED_HTTP_SESSION.close()
104
- SHARED_HTTP_SESSION = None
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."},
112
- "provider": {"type": "string", "description": "The search provider. MUST be 'serpapi'.", "default": "serpapi"}}
 
 
113
  output_type = "string"
114
- is_async = True
115
 
116
  def __init__(self, session: aiohttp.ClientSession):
117
  super().__init__()
118
- self._session = session
119
 
120
- async def forward(self, query: str, provider: str = "serpapi") -> str: # Added provider
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.")
128
  return "Error: Serper API key not found in environment."
129
 
130
  url = "https://google.serper.dev/search"
@@ -132,74 +144,83 @@ class GoogleSearchTool(Tool): # Renamed to GoogleSearchTool
132
  payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
133
 
134
  try:
 
135
  async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
136
- response.raise_for_status()
137
  data = await response.json()
138
  return self._format_results(data)
139
  except asyncio.TimeoutError:
140
  logger.error(f"Timeout performing search for '{query}'")
141
  return f"Error: Timeout during web search for '{query}'."
142
- except aiohttp.ClientError as e:
 
 
 
143
  logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
144
  return f"Error performing search (client error): {str(e)}"
145
  except Exception as e:
146
- logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}")
147
- return f"Error performing search: {str(e)}"
148
 
149
  def _format_results(self, data: Dict[str, Any]) -> str:
 
150
  results = []
151
  if 'organic' in data and data['organic']:
152
  for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
153
  title = result.get('title', 'N/A')
154
  snippet = result.get('snippet', 'N/A')
 
155
  results.append(f"Title: {title}\nSnippet: {snippet}\n---")
156
- if not results and 'knowledgeGraph' in data:
 
157
  kg = data['knowledgeGraph']
158
  title = kg.get('title', '')
159
  description = kg.get('description', '')
160
- if title or description:
161
  results.append(f"Knowledge Graph: {title}\n{description}\n---")
 
162
  formatted_output = "\n".join(results) if results else "No relevant search results found."
163
- return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
164
-
165
 
166
  # --- Agent Definition ---
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
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
181
  )
182
 
183
- # REINSTATED WORKAROUND for MultiStepAgent TypeError
184
- # Call super() with only arguments known/likely for MultiStepAgent
 
185
  minimal_super_args = {
186
  "model": effective_model,
187
  "tools": tools,
188
  "max_steps": CONFIG.AGENT_MAX_STEPS,
189
- # "code_writer": None, # If CodeAgent expects a code_writer to be passed to MultiStepAgent explicitly
 
190
  }
191
  try:
192
  super().__init__(**minimal_super_args)
193
- logger.info(
194
- "QuestionAnsweringAgent (CodeAgent) super().__init__ called with MINIMAL args (workaround active).")
195
 
196
- # Explicitly set CodeAgent-specific attributes after init.
197
- # This relies on CodeAgent using these instance attributes.
198
  self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
199
  logger.info(f"Explicitly set self.system_prompt for CodeAgent.")
200
-
201
- # These might be read-only or set internally in a way this doesn't override.
202
- # We log a warning if the attribute doesn't exist to be set.
203
  if hasattr(self, 'verbosity_level'):
204
  self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
205
  logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
@@ -207,218 +228,444 @@ 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(
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:
243
  full_agent_response = str(raw_output_obj.text)
244
- elif isinstance(raw_output_obj, str):
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:
265
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
266
  final_answer_for_submission = "Could not determine answer."
267
 
268
- except TypeError as te:
269
- logger.error(f"TypeError during agent processing: {str(te)}", exc_info=True)
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]:
 
 
 
 
 
 
284
  global GLOBAL_CHUCK_AGENT
285
- logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
286
- if args:
287
- logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
288
-
289
- if not isinstance(profile, gr.OAuthProfile) and profile is not None:
290
- logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
291
- found_profile_in_args = False
 
292
  for arg_val in args:
293
  if isinstance(arg_val, gr.OAuthProfile):
294
- profile = arg_val
295
- found_profile_in_args = True
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:
305
- logger.warning("User not logged in for evaluation.")
306
  return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
307
 
308
- username = profile.username
309
  logger.info(f"User logged in: {username}")
310
 
311
- _, agent_code_url = get_space_id_agent_code_url()
312
- logger.info(f"Agent code URL: {agent_code_url}")
313
- results_log_data: List[Dict[str, Any]] = []
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
 
326
- try:
327
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
328
  answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
329
  submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
330
- except (ConnectionError, ValueError) as e:
 
 
 
 
 
331
  submission_status = str(e)
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
 
 
339
  # --- Build Gradio Interface ---
340
- with gr.Blocks() as demo:
341
- gr.Markdown("# Basic Agent Evaluation Runner")
342
  gr.Markdown(
343
  """
344
  **Instructions:**
345
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
346
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
347
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
 
 
348
  """
349
  )
350
  gr.Markdown(
351
- """
352
- **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.
353
- """
354
- )
355
- gr.Markdown(
356
- f"""
 
 
 
357
  ---
358
- **Technical Notes:**
359
- * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
360
- * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
361
- * `requirements.txt` should specify a compatible `gradio` version (e.g., `gradio==4.29.0` or `gradio==4.44.1`).
362
- * The current `smolagents` version might have an internal issue with `CodeAgent` initialization. A workaround is active.
363
  """
364
  )
365
 
366
  login_button = gr.LoginButton()
367
- run_button = gr.Button("Run Evaluation & Submit All Answers")
368
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
369
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
 
 
370
 
371
  run_button.click(
372
  fn=run_and_submit_all_evaluation,
373
- inputs=[login_button],
374
  outputs=[status_output, results_table]
375
  )
376
 
377
  # --- Application Startup & Shutdown Handling ---
378
  if __name__ == "__main__":
379
- print("\n" + "-"*30 + " App Starting " + "-"*30)
 
 
380
  space_host_startup = os.getenv("SPACE_HOST")
381
  space_id_startup, agent_url_startup = get_space_id_agent_code_url()
382
 
 
 
 
 
 
 
 
 
 
 
383
  if space_host_startup:
384
  print(f"✅ SPACE_HOST found: {space_host_startup}")
385
  print(f" Runtime URL might be: https://{space_host_startup}")
386
  else:
387
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
388
 
389
  if space_id_startup:
390
  print(f"✅ SPACE_ID found: {space_id_startup}")
391
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
392
  print(f" Agent Code URL reported to server: {agent_url_startup}")
393
  else:
394
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
395
 
396
- print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
397
- print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
398
- print("-"*(60 + len(" App Starting ")) + "\n")
399
- print("Launching Gradio Interface for Chuck Agent Evaluation...")
400
 
 
 
 
 
401
  try:
402
- demo.launch(debug=True, share=False)
 
 
403
  finally:
404
- loop_to_use = None
405
- if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
406
- loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
407
- elif SHARED_HTTP_SESSION:
408
- loop_to_use = SHARED_HTTP_SESSION.loop
409
-
410
- if loop_to_use and loop_to_use.is_running():
411
- logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
412
- try:
413
- current_loop = asyncio.get_event_loop_policy().get_event_loop() # More robust way to get current loop
414
- if current_loop is not loop_to_use and not loop_to_use.is_closed():
415
  asyncio.set_event_loop(loop_to_use)
416
-
417
- if GLOBAL_CHUCK_AGENT:
418
  loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
419
- elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
420
- loop_to_use.run_until_complete(close_shared_http_session())
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.")
 
 
 
6
  import re
7
  import json
8
  import logging
9
+ import operator # Used by CalculatorTool (if you re-add it)
10
  import aiohttp
11
+ from typing import Optional, Dict, Any, List, Tuple # Added Tuple
12
 
13
  # Import necessary components from smolagents
14
  try:
15
  from smolagents import CodeAgent, Tool, OpenAIServerModel
16
+ except ImportError as e: # Catch the specific error for better logging
17
+ logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
18
+ # Dummy classes for script parsing if smolagents is not installed or fails to import
19
+ # This allows the rest of the script to be parsed, but it won't run correctly.
20
  class CodeAgent:
21
+ def __init__(self, *args, **kwargs):
22
+ logging.error("Dummy CodeAgent initialized because smolagents failed to import.")
23
+ def run(self, *args, **kwargs):
24
+ logging.error("Dummy CodeAgent run called.")
25
+ return "Error: smolagents not loaded."
26
  pass
27
 
28
  class Tool:
29
+ def __init__(self, *args, **kwargs):
30
+ logging.error("Dummy Tool initialized because smolagents failed to import.")
31
  pass
32
 
33
  class OpenAIServerModel:
34
+ def __init__(self, *args, **kwargs):
35
+ logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
36
  pass
37
 
38
  from datetime import datetime
 
42
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
43
  QUESTIONS_URL_PATH = "/questions"
44
  SUBMIT_URL_PATH = "/submit"
45
+ SCREENSHOTS_DIR = "screenshots" # Currently not used, but kept for consistency
46
+ OPENAI_MODEL_ID = "gpt-4o" # Using a newer model, ensure API key has access
47
  SERPER_API_NUM_RESULTS = 3
48
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
49
  AGENT_MAX_STEPS = 10
50
+ AGENT_VERBOSITY_LEVEL = 2 # 0: silent, 1: info, 2: debug
51
 
52
  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.
53
  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.
 
77
 
78
  Formatting rules for the value in FINAL ANSWER:
79
  - If the question asks for a number: Provide only the number itself (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.
80
+ - 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 numerical digits are requested.
81
  - 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.
82
  - If the answer is a calculation result, provide just the number.
83
  """
 
92
 
93
  # --- Utility Functions ---
94
  def ensure_dir_exists(directory_path: str):
95
+ """Creates a directory if it doesn't already exist."""
96
  os.makedirs(directory_path, exist_ok=True)
97
 
98
  ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
99
 
100
+ def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
101
+ """Gets Space ID and constructs the agent code URL."""
102
+ space_id = os.getenv("SPACE_ID")
103
+ if space_id:
104
+ agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
105
+ else:
106
+ agent_code_url = "Agent code URL not found (SPACE_ID not set)"
107
+ return space_id, agent_code_url
108
+
109
+
110
  # --- HTTP Client Session Management ---
111
+ # Using a global session can be problematic with asyncio event loops,
112
+ # especially with Gradio. It's often better to create sessions when needed
113
+ # or manage them within the scope of an async function/class.
114
+ # For this script's structure, we'll manage it within ChuckAgent.
 
 
 
 
 
 
 
 
 
 
 
115
 
116
  # --- Tool Definitions ---
117
+ class GoogleSearchTool(Tool):
118
+ name = "web_search" # This is the name the LLM will use to call the tool
119
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
120
+ inputs = {
121
+ "query": {"type": "string", "description": "The search query to execute."},
122
+ "provider": {"type": "string", "description": "The search provider. MUST be 'serpapi'.", "default": "serpapi"}
123
+ }
124
  output_type = "string"
125
+ is_async = True # Important for smolagents to know this tool's forward method is async
126
 
127
  def __init__(self, session: aiohttp.ClientSession):
128
  super().__init__()
129
+ self._session = session # Use the session passed from ChuckAgent
130
 
131
+ async def forward(self, query: str, provider: str = "serpapi") -> str:
132
  if provider != "serpapi":
133
+ logger.warning(f"GoogleSearchTool called with invalid provider: {provider}. Defaulting or erroring.")
134
+ return "Error: Invalid search provider. Only 'serpapi' is supported for the web_search tool."
135
 
136
+ logger.info(f"GoogleSearchTool (web_search) called with query: '{query}', provider: '{provider}'")
137
  serper_api_key = os.environ.get('SERPER_API_KEY')
138
  if not serper_api_key:
139
+ logger.error("SERPER_API_KEY not found in environment variables.")
140
  return "Error: Serper API key not found in environment."
141
 
142
  url = "https://google.serper.dev/search"
 
144
  payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
145
 
146
  try:
147
+ # Use the session provided during initialization
148
  async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
149
+ response.raise_for_status() # Raises an error for bad status codes (4xx or 5xx)
150
  data = await response.json()
151
  return self._format_results(data)
152
  except asyncio.TimeoutError:
153
  logger.error(f"Timeout performing search for '{query}'")
154
  return f"Error: Timeout during web search for '{query}'."
155
+ except aiohttp.ClientResponseError as e:
156
+ logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
157
+ return f"Error performing search (HTTP {e.status}): {e.message}"
158
+ except aiohttp.ClientError as e: # Catches other aiohttp client errors (e.g., connection issues)
159
  logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
160
  return f"Error performing search (client error): {str(e)}"
161
  except Exception as e:
162
+ logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
163
+ return f"Error performing search: An unexpected error occurred."
164
 
165
  def _format_results(self, data: Dict[str, Any]) -> str:
166
+ """Formats search results from Serper API into a string."""
167
  results = []
168
  if 'organic' in data and data['organic']:
169
  for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
170
  title = result.get('title', 'N/A')
171
  snippet = result.get('snippet', 'N/A')
172
+ # link = result.get('link', '#') # Links are not directly useful for the LLM in this context
173
  results.append(f"Title: {title}\nSnippet: {snippet}\n---")
174
+
175
+ if not results and 'knowledgeGraph' in data: # Fallback to knowledge graph if no organic results
176
  kg = data['knowledgeGraph']
177
  title = kg.get('title', '')
178
  description = kg.get('description', '')
179
+ if title or description: # Ensure there's something to add
180
  results.append(f"Knowledge Graph: {title}\n{description}\n---")
181
+
182
  formatted_output = "\n".join(results) if results else "No relevant search results found."
183
+ return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH] # Truncate to manage context length
 
184
 
185
  # --- Agent Definition ---
186
  class QuestionAnsweringAgent(CodeAgent):
187
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
188
  tools = [
189
+ GoogleSearchTool(session=http_session), # Pass the shared session
190
+ # You can add CalculatorTool here if needed, ensuring it also uses async forward if it performs I/O
191
  ]
192
 
193
  effective_model = model
194
  if effective_model is None:
195
  openai_api_key = os.environ.get('OPENAI_API_KEY')
196
  if not openai_api_key:
197
+ logger.critical("OPENAI_API_KEY not found. Cannot initialize OpenAIServerModel.")
198
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
199
  effective_model = OpenAIServerModel(
200
  model_id=CONFIG.OPENAI_MODEL_ID,
201
  api_key=openai_api_key
202
  )
203
 
204
+ # WORKAROUND for potential smolagents CodeAgent/MultiStepAgent __init__ TypeError
205
+ # This attempts to initialize with arguments known to be accepted by the base MultiStepAgent,
206
+ # and then sets CodeAgent-specific attributes. This is fragile and depends on smolagents internal structure.
207
  minimal_super_args = {
208
  "model": effective_model,
209
  "tools": tools,
210
  "max_steps": CONFIG.AGENT_MAX_STEPS,
211
+ # "code_writer": None, # CodeAgent usually creates its own CodeWriter if not provided.
212
+ # If MultiStepAgent expects it, this might be an issue.
213
  }
214
  try:
215
  super().__init__(**minimal_super_args)
216
+ logger.info("QuestionAnsweringAgent (CodeAgent) super().__init__ called with MINIMAL args (workaround active).")
 
217
 
218
+ # Explicitly set CodeAgent-specific attributes after the minimal super init.
 
219
  self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
220
  logger.info(f"Explicitly set self.system_prompt for CodeAgent.")
221
+
222
+ # Attempt to set other CodeAgent/MultiStepAgent parameters if they exist as attributes
223
+ # This is not guaranteed to work if these are properties or handled differently internally.
224
  if hasattr(self, 'verbosity_level'):
225
  self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
226
  logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
 
228
  logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
229
 
230
  if hasattr(self, 'additional_authorized_imports'):
231
+ self.additional_authorized_imports = ["PIL"] # Example, ensure PIL is in requirements.txt if used by agent code
232
+ logger.info(f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
 
233
  else:
234
+ logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
235
+
236
+ # Check if code_writer was initialized by the super call or needs attention
 
 
 
237
  if not hasattr(self, 'code_writer') or self.code_writer is None:
238
+ logger.warning("self.code_writer might not be initialized due to the __init__ workaround. Agent may fail to generate or execute code.")
 
239
 
240
  except TypeError as e:
241
  logger.error(
242
+ f"WORKAROUND FAILED: Still encountered TypeError during minimal super().__init__ for QuestionAnsweringAgent: {e}. "
243
+ "This likely means the __init__ signature of smolagents.CodeAgent or its parent MultiStepAgent "
244
+ "is incompatible with this workaround or has changed.",
245
+ exc_info=True
246
+ )
247
+ raise # Re-raise the TypeError to halt execution, as the agent is not properly initialized.
248
+ except Exception as e:
249
+ logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
250
+ raise
251
+
252
+ logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID} and tools.")
253
 
 
254
 
255
  async def process_question(self, question_text: str) -> Tuple[str, str]:
256
+ """Processes a single question using the CodeAgent's run method and extracts the answer."""
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 (text: '{question_text[:100]}...')")
261
+
262
+ # The self.run() method in smolagents' CodeAgent is synchronous by default in some versions,
263
+ # but it calls tools that might be async.
264
+ # If self.run itself needs to be awaited (e.g., if CodeAgent is made fully async in future smolagents versions),
265
+ # this would need to change. For now, assuming self.run() orchestrates async tool calls internally
266
+ # and returns a result object or string.
267
+ raw_output_obj = self.run(question_text) # This is a blocking call in current smolagents
268
+
269
+ # Extracting the response string from various possible output structures of self.run()
270
  if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
271
  full_agent_response = str(raw_output_obj.log_string())
272
+ elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None: # Common for LLM responses
273
  full_agent_response = str(raw_output_obj.text)
274
+ elif isinstance(raw_output_obj, str): # If run directly returns a string
275
  full_agent_response = raw_output_obj
276
+ elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None: # Another possible attribute
277
  full_agent_response = str(raw_output_obj.result)
278
+ else: # Fallback to direct string conversion
279
  full_agent_response = str(raw_output_obj)
280
+ logger.warning(f"Raw output from agent.run() was of type {type(raw_output_obj)}. Used generic str() conversion.")
281
 
282
+ reasoning_trace = full_agent_response # The full conversation log
283
  logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
284
 
285
+ # Extract the final answer based on the specified template
286
+ match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
287
  if match:
288
  final_answer_for_submission = match.group(1).strip()
289
+ logger.info(f"Extracted FINAL ANSWER: '{final_answer_for_submission}'")
290
  else:
291
+ logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
292
+ final_answer_for_submission = full_agent_response.strip() # Fallback, may not be correctly formatted
 
293
 
294
+ if not final_answer_for_submission: # If the extracted answer is empty
295
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
296
  final_answer_for_submission = "Could not determine answer."
297
 
298
+ except TypeError as te: # Specifically catch TypeErrors that might arise from the __init__ workaround
299
+ logger.error(f"TypeError during agent processing, possibly due to __init__ workaround: {str(te)}", exc_info=True)
300
  final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
301
+ reasoning_trace += f"\nTypeError encountered during processing: {str(te)}"
302
  except Exception as e:
303
+ logger.error(f"Error processing question in QuestionAnsweringAgent: {type(e).__name__} - {str(e)}", exc_info=True)
 
304
  final_answer_for_submission = f"Error in agent processing: {str(e)}"
305
  reasoning_trace += f"\nError encountered: {str(e)}"
306
+
307
  return final_answer_for_submission, reasoning_trace
308
 
309
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
310
+ class ChuckAgent:
311
+ """An adapter class to manage the QuestionAnsweringAgent and its async operations."""
312
+ def __init__(self):
313
+ logger.info("ChuckAgent initialization started.")
314
+ # Ensure required API keys are present before initializing the actual agent
315
+ required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
316
+ missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
317
+ if missing_vars:
318
+ error_msg = f"Missing required environment variables: {', '.join(missing_vars)}. Please set them in Space Secrets."
319
+ logger.critical(error_msg)
320
+ raise EnvironmentError(error_msg)
321
+
322
+ self.loop = asyncio.new_event_loop()
323
+ asyncio.set_event_loop(self.loop)
324
+
325
+ # Initialize the shared aiohttp session for this agent instance
326
+ self.http_session = self.loop.run_until_complete(self._get_or_create_session())
327
+
328
+ # QuestionAnsweringAgent instantiation is now within the try-except block in run_and_submit_all_evaluation
329
+ # to catch initialization errors (like the smolagents SyntaxError or our workaround TypeError).
330
+ # Here, we just prepare for it.
331
+ self.agent_instance: Optional[QuestionAnsweringAgent] = None
332
+ logger.info("ChuckAgent basic initialization complete. Actual QuestionAnsweringAgent will be created on first use.")
333
+
334
+ async def _get_or_create_session(self) -> aiohttp.ClientSession:
335
+ """Creates and returns an aiohttp.ClientSession."""
336
+ logger.info("Creating aiohttp.ClientSession for ChuckAgent.")
337
+ return aiohttp.ClientSession()
338
+
339
+ def _ensure_agent_initialized(self):
340
+ """Initializes the QuestionAnsweringAgent if not already done."""
341
+ if self.agent_instance is None:
342
+ logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
343
+ try:
344
+ # Pass the http_session managed by ChuckAgent
345
+ self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
346
+ logger.info("QuestionAnsweringAgent initialized successfully.")
347
+ except Exception as e: # Catch any error during agent init
348
+ logger.error(f"Failed to initialize QuestionAnsweringAgent: {e}", exc_info=True)
349
+ # This exception will propagate up and be caught by the caller (run_and_submit_all_evaluation)
350
+ raise
351
+
352
+
353
+ def __call__(self, question: str) -> Tuple[str, str]:
354
+ """Synchronous wrapper for the agent's async process_question method."""
355
+ logger.info(f"ChuckAgent received question (first 50 chars): '{question[:50]}...'")
356
+
357
+ try:
358
+ self._ensure_agent_initialized() # Initialize agent on first call
359
+ if self.agent_instance is None: # Should not happen if _ensure_agent_initialized works
360
+ raise RuntimeError("QuestionAnsweringAgent was not initialized.")
361
+
362
+ # Run the async method in the event loop
363
+ future = asyncio.run_coroutine_threadsafe(self.agent_instance.process_question(question), self.loop)
364
+ final_answer, reasoning_trace = future.result(timeout=120) # Add a timeout
365
+ logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
366
+ return final_answer, reasoning_trace
367
+ except Exception as e:
368
+ error_msg = f"Error running ChuckAgent: {type(e).__name__} - {str(e)}"
369
+ logger.error(error_msg, exc_info=True)
370
+ # Return a tuple even in case of error, as expected by the caller
371
+ return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
372
+
373
+ async def shutdown(self):
374
+ """Closes the aiohttp session and cleans up."""
375
+ logger.info("ChuckAgent shutdown called.")
376
+ if self.http_session and not self.http_session.closed:
377
+ await self.http_session.close()
378
+ logger.info("Closed ChuckAgent's aiohttp.ClientSession.")
379
+ self.http_session = None # type: ignore
380
+ # If the loop was started by this agent, it could be stopped here,
381
+ # but Gradio manages its own loop, so typically we don't stop it.
382
+ # if self.loop.is_running():
383
+ # self.loop.stop() # This might be too aggressive if loop is shared
384
+ logger.info("ChuckAgent shutdown complete.")
385
+
386
+
387
+ # --- Orchestration Functions ---
388
+ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
389
+ """Fetches questions from the scoring server."""
390
+ questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
391
+ logger.info(f"Fetching questions from: {questions_url}")
392
+ try:
393
+ response = requests.get(questions_url, timeout=30)
394
+ response.raise_for_status()
395
+ questions_data = response.json()
396
+ if not isinstance(questions_data, list) or not questions_data:
397
+ logger.warning(f"Fetched questions empty or invalid format: {questions_data}")
398
+ raise ValueError("Fetched questions list is empty or not a list.")
399
+ logger.info(f"Fetched {len(questions_data)} questions.")
400
+ return questions_data
401
+ except requests.exceptions.RequestException as e:
402
+ logger.error(f"Error fetching questions: {e}", exc_info=True)
403
+ raise ConnectionError(f"Error fetching questions: {e}")
404
+ except requests.exceptions.JSONDecodeError as e:
405
+ logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
406
+ raise ValueError(f"Error decoding server response for questions: {e}")
407
+
408
+ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
409
+ """Runs the agent on all questions and collects answers and logs."""
410
+ answers_payload = []
411
+ results_log_data = []
412
+ logger.info(f"Running agent on {len(questions_data)} questions...")
413
+
414
+ for i, item in enumerate(questions_data):
415
+ task_id = item.get("task_id")
416
+ question_text = item.get("question")
417
+
418
+ if not task_id or question_text is None:
419
+ logger.warning(f"Skipping item with missing task_id or question: {item}")
420
+ continue
421
+
422
+ logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}, Question: '{question_text[:50]}...'")
423
+ try:
424
+ model_ans, reasoning = agent(question_text) # Call ChuckAgent
425
+
426
+ payload_item = {"task_id": task_id, "model_answer": model_ans}
427
+ if reasoning: # Add reasoning_trace if available and not empty
428
+ payload_item["reasoning_trace"] = reasoning
429
+ answers_payload.append(payload_item)
430
+
431
+ results_log_data.append({
432
+ "Task ID": task_id,
433
+ "Question": question_text,
434
+ "Submitted Answer": model_ans,
435
+ "Reasoning Trace": reasoning
436
+ })
437
+ except Exception as e:
438
+ logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
439
+ error_answer = f"AGENT_CALL_ERROR: {str(e)}"
440
+ answers_payload.append({"task_id": task_id, "model_answer": error_answer, "reasoning_trace": str(e)})
441
+ results_log_data.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
442
+
443
+ if not answers_payload:
444
+ logger.warning("Agent did not produce any answers.")
445
+ # Still return empty lists rather than raising an error here, let the caller decide.
446
+ return answers_payload, results_log_data
447
+
448
+ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
449
+ """Submits the collected answers to the scoring server."""
450
+ if not answers_payload:
451
+ logger.warning("No answers to submit.")
452
+ return "Agent did not produce any answers to submit."
453
+
454
+ submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
455
+ submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
456
+
457
+ logger.info(f"Submitting {len(answers_payload)} answers for user '{username}' to {submit_url}...")
458
+ # logger.debug(f"Submission payload: {json.dumps(submission_data, indent=2)}") # Be careful logging full payload if sensitive
459
+
460
+ try:
461
+ response = requests.post(submit_url, json=submission_data, timeout=60)
462
+ response.raise_for_status()
463
+ result_data = response.json()
464
+ final_status = (
465
+ f"Submission Successful!\n"
466
+ f"User: {result_data.get('username', 'N/A')}\n"
467
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
468
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
469
+ f"Message: {result_data.get('message', 'No message received.')}"
470
+ )
471
+ logger.info(f"Submission successful for user '{username}'. Score: {result_data.get('score', 'N/A')}%")
472
+ except requests.exceptions.HTTPError as e:
473
+ error_detail = f"Server responded with {e.response.status_code}."
474
+ try:
475
+ error_json = e.response.json()
476
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
477
+ except requests.exceptions.JSONDecodeError:
478
+ error_detail += f" Raw Response: {e.response.text[:500]}" # Log only a snippet of raw response
479
+ final_status = f"Submission Failed: {error_detail}"
480
+ logger.error(final_status)
481
+ except requests.exceptions.Timeout:
482
+ final_status = "Submission Failed: The request timed out."
483
+ logger.error(final_status)
484
+ except requests.exceptions.RequestException as e:
485
+ final_status = f"Submission Failed: Network error - {e}"
486
+ logger.error(final_status, exc_info=True)
487
+ except Exception as e: # Catch any other unexpected error during submission
488
+ final_status = f"An unexpected error occurred during submission: {e}"
489
+ logger.error(final_status, exc_info=True)
490
+ return final_status
491
+
492
+ # --- Gradio Interface and Main Execution Logic ---
493
+ GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None # To hold the single agent instance
494
 
495
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
496
+ """
497
+ Orchestrates fetching questions, running the agent, submitting answers,
498
+ and handling Gradio interaction.
499
+ The `*args` is present due to a previous Gradio issue with `gr.LoginButton()` potentially sending
500
+ extra arguments. It's safer to keep it to catch them if they reappear.
501
+ """
502
  global GLOBAL_CHUCK_AGENT
503
+ logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
504
+
505
+ # Handle potential inconsistencies with Gradio's profile argument passing
506
+ effective_profile: Optional[gr.OAuthProfile] = None
507
+ if isinstance(profile, gr.OAuthProfile):
508
+ effective_profile = profile
509
+ elif args: # Check if profile was passed in *args
510
+ logger.warning(f"Profile not directly passed or None. Checking *args: {args}")
511
  for arg_val in args:
512
  if isinstance(arg_val, gr.OAuthProfile):
513
+ effective_profile = arg_val
514
+ logger.info(f"Found gr.OAuthProfile in *args: {effective_profile.username if effective_profile else 'None (from args)'}")
 
515
  break
516
+
517
+ if not effective_profile:
518
+ logger.warning("User not logged in or profile not correctly passed for evaluation.")
 
 
 
 
 
519
  return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
520
 
521
+ username = effective_profile.username
522
  logger.info(f"User logged in: {username}")
523
 
524
+ _, agent_code_url = get_space_id_agent_code_url() # Get current agent code URL
525
+ results_log_data: List[Dict[str, Any]] = [] # Initialize here for broader scope
 
526
 
527
  try:
528
+ # Initialize or get existing ChuckAgent instance
529
  if GLOBAL_CHUCK_AGENT is None:
530
+ logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance.")
531
+ GLOBAL_CHUCK_AGENT = ChuckAgent()
532
  agent_instance = GLOBAL_CHUCK_AGENT
533
+
534
+ # Ensure the underlying QuestionAnsweringAgent is also initialized
535
+ # This call might raise an exception if QuestionAnsweringAgent init fails (e.g., smolagents issue, API key issue)
536
+ agent_instance._ensure_agent_initialized()
 
 
537
 
 
538
  questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
539
  answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
540
  submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
541
+
542
+ except EnvironmentError as e: # Catches missing API keys from ChuckAgent or QuestionAnsweringAgent init
543
+ logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
544
+ submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
545
+ except (ConnectionError, ValueError) as e: # Errors from fetch_questions or submit_answers
546
+ logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
547
  submission_status = str(e)
548
+ except RuntimeError as e: # Catches errors like "smolagents not loaded" or "QuestionAnsweringAgent not initialized"
549
+ logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
550
+ submission_status = f"Runtime Error: {e}"
551
+ except Exception as e: # Catch-all for other unexpected errors
552
+ logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
553
  submission_status = f"An unexpected error occurred: {e}"
554
+ # If the error is critical, results_log_data might be empty or incomplete
555
+ if not results_log_data: # Ensure it's at least an empty list for DataFrame
556
+ results_log_data = [{"Task ID": "N/A", "Question": "N/A", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
557
+
558
 
559
  results_df = pd.DataFrame(results_log_data if results_log_data else [])
560
  return submission_status, results_df
561
 
562
+
563
  # --- Build Gradio Interface ---
564
+ with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
565
+ gr.Markdown("# Chuck's Agent Evaluation Runner")
566
  gr.Markdown(
567
  """
568
  **Instructions:**
569
+ 1. This interface allows you to evaluate your AI agent against a predefined set of questions.
570
+ 2. **Log in** to your Hugging Face account using the button below. Your HF username is used for submitting results.
571
+ 3. Click '**Run Evaluation & Submit All Answers**'. This will:
572
+ a. Fetch questions from the evaluation server.
573
+ b. Run your configured agent (defined in `app.py`) on each question.
574
+ c. Submit the answers back to the server.
575
+ d. Display the overall status and a table of questions, your agent's answers, and reasoning.
576
  """
577
  )
578
  gr.Markdown(
579
+ f"""
580
+ ---
581
+ **Technical Notes & Configuration:**
582
+ * **Agent Backend**: `smolagents` framework.
583
+ * **OpenAI Model**: `{CONFIG.OPENAI_MODEL_ID}`.
584
+ * **Web Search**: Serper API (`google.serper.dev`).
585
+ * **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
586
+ * **Gradio Version**: This app is tested with `gradio>=4.0`. Check `requirements.txt`.
587
+ * **`smolagents` Issue**: The primary issue you encountered (`SyntaxError: f-string: unmatched '('`) is likely within the `smolagents` library itself. Please ensure you have tried upgrading or reinstalling it (`pip install --upgrade smolagents`). A workaround for a *different* potential `TypeError` during `CodeAgent` initialization is active in this script but won't fix the `SyntaxError`.
588
  ---
589
+ **Disclaimer**: Processing all questions can take some time. The interface will update once the entire process is complete. For a production system, consider asynchronous operations or background tasks for a smoother user experience.
 
 
 
 
590
  """
591
  )
592
 
593
  login_button = gr.LoginButton()
594
+ run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
595
+
596
+ with gr.Column():
597
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
598
+ results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True, max_rows=20)
599
 
600
  run_button.click(
601
  fn=run_and_submit_all_evaluation,
602
+ inputs=[login_button],
603
  outputs=[status_output, results_table]
604
  )
605
 
606
  # --- Application Startup & Shutdown Handling ---
607
  if __name__ == "__main__":
608
+ print("\n" + "="*15 + " Application Startup " + "="*15) # Make it more visible
609
+
610
+ # Log essential startup info
611
  space_host_startup = os.getenv("SPACE_HOST")
612
  space_id_startup, agent_url_startup = get_space_id_agent_code_url()
613
 
614
+ print(f"Python Version: {'.'.join(map(str, asyncio.sys.version_info[:3]))}") # Log Python version
615
+ print(f"Gradio Version: {gr.__version__}") # Log Gradio version
616
+ # Consider logging smolagents version if import is successful
617
+ try:
618
+ import smolagents
619
+ print(f"smolagents Version: {smolagents.__version__ if hasattr(smolagents, '__version__') else 'unknown'}")
620
+ except ImportError:
621
+ print("smolagents could not be imported (version unknown). This is expected if the SyntaxError persists.")
622
+
623
+
624
  if space_host_startup:
625
  print(f"✅ SPACE_HOST found: {space_host_startup}")
626
  print(f" Runtime URL might be: https://{space_host_startup}")
627
  else:
628
+ print("ℹ️ SPACE_HOST environment variable not found (likely running locally).")
629
 
630
  if space_id_startup:
631
  print(f"✅ SPACE_ID found: {space_id_startup}")
632
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
633
  print(f" Agent Code URL reported to server: {agent_url_startup}")
634
  else:
635
+ print("ℹ️ SPACE_ID environment variable not found. Repo URL cannot be determined.")
636
 
637
+ print(f" Default API URL for scoring: {CONFIG.DEFAULT_API_URL}")
638
+ print(f" OpenAI Model ID for Agent: {CONFIG.OPENAI_MODEL_ID}")
639
+ print("="* (30 + len(" Application Startup ")) + "\n")
 
640
 
641
+ print("Launching Gradio Interface for Chuck Agent Evaluation...")
642
+ print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
643
+ print("If you encounter 'SyntaxError: f-string: unmatched '('', please upgrade/reinstall 'smolagents'.")
644
+
645
  try:
646
+ demo.launch(debug=True, share=False) # share=False for security unless specifically needed
647
+ except Exception as e:
648
+ logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
649
  finally:
650
+ logger.info("Gradio demo has been closed or failed to launch.")
651
+ if GLOBAL_CHUCK_AGENT:
652
+ logger.info("Attempting to shutdown ChuckAgent and close its HTTP session...")
653
+ # Get the loop from the agent if it exists and is running
654
+ loop_to_use = None
655
+ if hasattr(GLOBAL_CHUCK_AGENT, 'loop') and GLOBAL_CHUCK_AGENT.loop and GLOBAL_CHUCK_AGENT.loop.is_running():
656
+ loop_to_use = GLOBAL_CHUCK_AGENT.loop
657
+
658
+ if loop_to_use:
659
+ try:
660
+ # Ensure we are using the correct event loop context for shutdown
661
  asyncio.set_event_loop(loop_to_use)
 
 
662
  loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
663
+ logger.info("ChuckAgent shutdown process completed.")
664
+ except Exception as e_shutdown:
665
+ logger.error(f"Error during ChuckAgent final shutdown: {e_shutdown}", exc_info=True)
666
+ else:
667
+ logger.warning("Could not get a running event loop from GLOBAL_CHUCK_AGENT for shutdown.")
668
  else:
669
+ logger.info("No GLOBAL_CHUCK_AGENT instance to shutdown.")
670
+ print("="*15 + " Application Shutdown " + "="*15)
671
+