GoodLuckChuck commited on
Commit
ee4da95
·
verified ·
1 Parent(s): d03c2ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -98
app.py CHANGED
@@ -5,33 +5,20 @@ import pandas as pd
5
  import asyncio
6
  import re
7
  import json
8
- import logging # Ensure logging is imported before basicConfig
9
  import operator # Used by CalculatorTool
10
  import aiohttp
11
  from typing import Optional, Dict, Any, List, Tuple
12
 
13
- # --- Logging Setup ---
14
- logging.basicConfig(
15
- level=logging.INFO,
16
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
17
- logger = logging.getLogger(__name__) # Define logger here
18
-
19
  # Import necessary components from smolagents
20
- # We are NOT importing CodeWriter explicitly, relying on CodeAgent's internal setup.
21
  try:
22
  from smolagents import CodeAgent, Tool, OpenAIServerModel
23
- SMOLAGENTS_IMPORTED_SUCCESSFULLY = True
24
- logger.info("Successfully imported CodeAgent, Tool, OpenAIServerModel from smolagents.")
25
- except ImportError as e:
26
- logger.error(f"CRITICAL: Failed to import base smolagents components. Error: {e}. Ensure smolagents is correctly installed via requirements.txt.", exc_info=True)
27
- SMOLAGENTS_IMPORTED_SUCCESSFULLY = False
28
  # Dummy classes for script parsing if smolagents is not installed
29
  class CodeAgent: pass
30
  class Tool: pass
31
- class OpenAIServerModel:
32
- def __init__(self, *args, **kwargs):
33
- logging.warning("Using DUMMY OpenAIServerModel due to smolagents import failure.")
34
- pass
35
 
36
  from datetime import datetime
37
 
@@ -41,11 +28,11 @@ class AppConfig:
41
  QUESTIONS_URL_PATH = "/questions"
42
  SUBMIT_URL_PATH = "/submit"
43
  SCREENSHOTS_DIR = "screenshots"
44
- OPENAI_MODEL_ID = "gpt-4o"
45
  SERPER_API_NUM_RESULTS = 3
46
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
47
- AGENT_MAX_STEPS = 12
48
- AGENT_VERBOSITY_LEVEL = 2
49
 
50
  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.
51
  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.
@@ -64,12 +51,18 @@ Follow this process for every question:
64
  # Your Python code to call ONE tool.
65
  # REMEMBER: Use `await` for `web_search` and `image_retriever`.
66
  # ALWAYS print the result of the tool call.
 
 
 
 
 
 
67
  ```<end_code>
68
  4. OBSERVATION: [The system will insert the printed output of your tool call here.]
69
  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.
70
  6. If you have the information, formulate the final answer according to the formatting rules.
71
 
72
- CRITICAL: Your *entire response* for each turn must culminate in the final answer using this exact template on a new line:
73
  FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
74
 
75
  Formatting rules for the value in FINAL ANSWER:
@@ -81,6 +74,12 @@ Formatting rules for the value in FINAL ANSWER:
81
 
82
  CONFIG = AppConfig()
83
 
 
 
 
 
 
 
84
  # --- Utility Functions ---
85
  def ensure_dir_exists(directory_path: str):
86
  os.makedirs(directory_path, exist_ok=True)
@@ -106,11 +105,11 @@ async def close_shared_http_session():
106
 
107
  # --- Tool Definitions ---
108
  class ImageRetrievalTool(Tool):
109
- name = "image_retriever"
110
  description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
111
  inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
112
  output_type = "string"
113
- is_async = True
114
 
115
  def __init__(self, session: aiohttp.ClientSession):
116
  super().__init__()
@@ -141,7 +140,7 @@ class ImageRetrievalTool(Tool):
141
  return f"Error retrieving image: {str(e)}"
142
 
143
  class WebSearchTool(Tool):
144
- name = "web_search"
145
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
146
  inputs = {"query": {"type": "string", "description": "The search query to execute."}}
147
  output_type = "string"
@@ -194,7 +193,7 @@ class WebSearchTool(Tool):
194
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
195
 
196
  class CalculatorTool(Tool):
197
- name = "calculator"
198
  description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
199
  inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
200
  output_type = "string"
@@ -209,7 +208,7 @@ class CalculatorTool(Tool):
209
  }
210
  self.allowed_chars = "0123456789+-*/^(). "
211
 
212
- async def forward(self, expression: str) -> str:
213
  logger.info(f"CalculatorTool called with expression: {expression}")
214
  try:
215
  safe_expr = "".join(c for c in expression if c in self.allowed_chars)
@@ -224,11 +223,7 @@ class CalculatorTool(Tool):
224
  # --- Agent Definition ---
225
  class QuestionAnsweringAgent(CodeAgent):
226
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
227
- if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
228
- logger.error("Cannot initialize QuestionAnsweringAgent: smolagents components failed to import earlier.")
229
- raise ImportError("smolagents components not available for QuestionAnsweringAgent.")
230
-
231
- tools_list = [
232
  WebSearchTool(session=http_session),
233
  CalculatorTool(),
234
  ImageRetrievalTool(session=http_session)
@@ -239,57 +234,54 @@ class QuestionAnsweringAgent(CodeAgent):
239
  openai_api_key = os.environ.get('OPENAI_API_KEY')
240
  if not openai_api_key:
241
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
242
- effective_model = OpenAIServerModel(
243
  model_id=CONFIG.OPENAI_MODEL_ID,
244
- api_key=openai_api_key
245
  )
246
 
247
- # REFINED WORKAROUND for MultiStepAgent internal TypeError
 
 
 
 
 
 
 
248
  try:
249
- # Step 1: Initialize the parent of CodeAgent (MultiStepAgent)
250
- # Pass arguments that MultiStepAgent or its parent (Agent) would expect.
251
- # 'additional_authorized_imports' is handled by the base 'Agent' class.
252
- # 'system_prompt' and 'verbosity_level' are specific to CodeAgent and should NOT be passed here
253
- # if MultiStepAgent does not accept them (which the TypeError indicates).
254
- super(CodeAgent, self).__init__(
255
- model=effective_model,
256
- tools=tools_list,
257
- max_steps=CONFIG.AGENT_MAX_STEPS,
258
- additional_authorized_imports=["PIL", "pandas"] # This is passed to Agent.__init__
259
- )
260
- logger.info("QuestionAnsweringAgent > MultiStepAgent part initialized (workaround) including additional_authorized_imports.")
261
-
262
- # Step 2: Manually set attributes specific to CodeAgent on the instance.
263
- # CodeAgent's own __init__ logic (which runs after its super() call to MultiStepAgent)
264
- # should pick these up to configure itself, especially for its CodeWriter.
265
- self.model = effective_model # Ensure it's set on self for CodeWriter if not already
266
- self.tools = tools_list # Ensure it's set on self for CodeWriter if not already
267
- self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT # CRITICAL
268
- self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL # For CodeAgent's own logging
269
- # self.additional_authorized_imports is set by the super() call.
270
-
271
- # Step 3: Ensure CodeAgent's CodeWriter is properly initialized.
272
- # CodeAgent's __init__ typically does:
273
- # self.code_writer = code_writer_param or CodeWriter(model=self.model, tools=self.tools, system_prompt=self.system_prompt, ...)
274
- # We are relying on the fact that CodeAgent's __init__ (the part that runs *after* its super() call to MultiStepAgent)
275
- # will correctly instantiate or use its internal CodeWriter with the self.system_prompt we've just set.
276
- # We cannot directly import and create CodeWriter if `from smolagents.code_writer import CodeWriter` fails.
277
- if hasattr(self, 'code_writer') and self.code_writer is not None:
278
- logger.info("CodeAgent's internal CodeWriter seems to be initialized.")
279
- # If CodeWriter was created by CodeAgent's __init__ *before* its super() call (unlikely),
280
- # it might have a default system_prompt. We hope it uses self.system_prompt dynamically or
281
- # re-initializes/updates based on self.system_prompt.
282
  else:
283
- logger.warning("CodeAgent's internal CodeWriter might not be initialized or accessible for verification after workaround. Agent may not use custom system_prompt correctly.")
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
  except TypeError as e:
286
- logger.error(f"WORKAROUND FAILED during __init__ (TypeError): {e}. This suggests an issue with the minimal args for MultiStepAgent or how CodeAgent handles its attributes post-super-init.", exc_info=True)
287
  raise e
288
- except Exception as e_init:
289
- logger.error(f"Unexpected error during QuestionAnsweringAgent __init__ (workaround): {e_init}", exc_info=True)
290
- raise e_init
291
 
292
- logger.info(f"QuestionAnsweringAgent initialized (with workaround) with model: {CONFIG.OPENAI_MODEL_ID}.")
293
 
294
 
295
  async def process_question(self, question_text: str) -> Tuple[str, str]:
@@ -320,7 +312,7 @@ class QuestionAnsweringAgent(CodeAgent):
320
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
321
  else:
322
  logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
323
- final_answer_for_submission = full_agent_response.strip()
324
 
325
  if not final_answer_for_submission:
326
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
@@ -340,9 +332,6 @@ class QuestionAnsweringAgent(CodeAgent):
340
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
341
  class ChuckAgent:
342
  def __init__(self):
343
- if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
344
- raise ImportError("smolagents components not available, ChuckAgent cannot be initialized.")
345
-
346
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
347
  missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
348
  if missing_vars:
@@ -358,13 +347,7 @@ class ChuckAgent:
358
  asyncio.set_event_loop(self.loop)
359
 
360
  self.http_session = self.loop.run_until_complete(get_shared_http_session())
361
- try:
362
- self.agent = QuestionAnsweringAgent(http_session=self.http_session)
363
- except Exception as agent_init_error:
364
- logger.error(f"Failed to initialize QuestionAnsweringAgent within ChuckAgent: {agent_init_error}", exc_info=True)
365
- self.loop.run_until_complete(close_shared_http_session())
366
- raise
367
-
368
  logger.info("ChuckAgent fully initialized")
369
 
370
  def __call__(self, question: str) -> Tuple[str, str]:
@@ -389,7 +372,6 @@ class ChuckAgent:
389
  logger.info("ChuckAgent shutdown complete.")
390
 
391
  # --- Core Evaluation Logic ---
392
- # (This section remains unchanged)
393
  def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
394
  space_id = os.getenv("SPACE_ID")
395
  agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
@@ -521,15 +503,12 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
521
 
522
  try:
523
  if GLOBAL_CHUCK_AGENT is None:
524
- GLOBAL_CHUCK_AGENT = ChuckAgent()
525
  agent_instance = GLOBAL_CHUCK_AGENT
526
- except ImportError as e:
527
- logger.critical(f"Agent instantiation failed due to smolagents import error: {e}", exc_info=True)
528
- return f"Agent Initialization Error: Failed to import smolagents. Check Space logs for build errors.", pd.DataFrame()
529
- except EnvironmentError as e:
530
- logger.critical(f"Agent instantiation failed due to missing env vars: {e}", exc_info=True)
531
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
532
- except Exception as e:
533
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
534
  return f"Error initializing agent: {e}", pd.DataFrame()
535
 
@@ -559,7 +538,7 @@ with gr.Blocks() as demo:
559
  )
560
  gr.Markdown(
561
  """
562
- **Disclaimers:** Once clicking on the "submit" button, it can take quite some time for the agent to process all questions. This space provides a basic setup.
563
  """
564
  )
565
  gr.Markdown(
@@ -568,8 +547,8 @@ with gr.Blocks() as demo:
568
  **Technical Notes:**
569
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
570
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
571
- * `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
572
- * A workaround for `smolagents.CodeAgent` initialization is currently active.
573
  """
574
  )
575
 
@@ -620,7 +599,7 @@ if __name__ == "__main__":
620
  if loop_to_use and loop_to_use.is_running():
621
  logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
622
  try:
623
- current_loop = asyncio.get_event_loop_policy().get_event_loop()
624
  if current_loop is not loop_to_use and not loop_to_use.is_closed():
625
  asyncio.set_event_loop(loop_to_use)
626
 
@@ -631,5 +610,4 @@ if __name__ == "__main__":
631
  except Exception as e:
632
  logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
633
  else:
634
- logger.info("No active HTTP session or running loop to close in finally block.")
635
-
 
5
  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
  # Dummy classes for script parsing if smolagents is not installed
19
  class CodeAgent: pass
20
  class Tool: pass
21
+ class OpenAIServerModel: pass
 
 
 
22
 
23
  from datetime import datetime
24
 
 
28
  QUESTIONS_URL_PATH = "/questions"
29
  SUBMIT_URL_PATH = "/submit"
30
  SCREENSHOTS_DIR = "screenshots"
31
+ OPENAI_MODEL_ID = "gpt-4o"
32
  SERPER_API_NUM_RESULTS = 3
33
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
34
+ AGENT_MAX_STEPS = 10
35
+ AGENT_VERBOSITY_LEVEL = 2 # Will attempt to set this via workaround
36
 
37
  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.
38
  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.
 
51
  # Your Python code to call ONE tool.
52
  # REMEMBER: Use `await` for `web_search` and `image_retriever`.
53
  # ALWAYS print the result of the tool call.
54
+ # Example for web_search:
55
+ # search_result = await web_search(query="some specific query")
56
+ # print(search_result)
57
+ # Example for calculator:
58
+ # calc_result = calculator(expression="1+1")
59
+ # print(calc_result)
60
  ```<end_code>
61
  4. OBSERVATION: [The system will insert the printed output of your tool call here.]
62
  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.
63
  6. If you have the information, formulate the final answer according to the formatting rules.
64
 
65
+ CRITICAL: Your *entire response* to the user for each turn must culminate in the final answer using this exact template on a new line:
66
  FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
67
 
68
  Formatting rules for the value in FINAL ANSWER:
 
74
 
75
  CONFIG = AppConfig()
76
 
77
+ # --- Logging Setup ---
78
+ logging.basicConfig(
79
+ level=logging.INFO,
80
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
81
+ logger = logging.getLogger(__name__)
82
+
83
  # --- Utility Functions ---
84
  def ensure_dir_exists(directory_path: str):
85
  os.makedirs(directory_path, exist_ok=True)
 
105
 
106
  # --- Tool Definitions ---
107
  class ImageRetrievalTool(Tool):
108
+ name = "image_retriever"
109
  description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
110
  inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
111
  output_type = "string"
112
+ is_async = True
113
 
114
  def __init__(self, session: aiohttp.ClientSession):
115
  super().__init__()
 
140
  return f"Error retrieving image: {str(e)}"
141
 
142
  class WebSearchTool(Tool):
143
+ name = "web_search"
144
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
145
  inputs = {"query": {"type": "string", "description": "The search query to execute."}}
146
  output_type = "string"
 
193
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
194
 
195
  class CalculatorTool(Tool):
196
+ name = "calculator"
197
  description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
198
  inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
199
  output_type = "string"
 
208
  }
209
  self.allowed_chars = "0123456789+-*/^(). "
210
 
211
+ async def forward(self, expression: str) -> str:
212
  logger.info(f"CalculatorTool called with expression: {expression}")
213
  try:
214
  safe_expr = "".join(c for c in expression if c in self.allowed_chars)
 
223
  # --- Agent Definition ---
224
  class QuestionAnsweringAgent(CodeAgent):
225
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
226
+ tools = [
 
 
 
 
227
  WebSearchTool(session=http_session),
228
  CalculatorTool(),
229
  ImageRetrievalTool(session=http_session)
 
234
  openai_api_key = os.environ.get('OPENAI_API_KEY')
235
  if not openai_api_key:
236
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
237
+ effective_model = OpenAIServerModel(
238
  model_id=CONFIG.OPENAI_MODEL_ID,
239
+ api_key=openai_api_key
240
  )
241
 
242
+ # REINSTATED WORKAROUND for MultiStepAgent TypeError
243
+ # Call super() with only arguments known/likely for MultiStepAgent
244
+ minimal_super_args = {
245
+ "model": effective_model,
246
+ "tools": tools,
247
+ "max_steps": CONFIG.AGENT_MAX_STEPS,
248
+ # "code_writer": None, # If CodeAgent expects a code_writer to be passed to MultiStepAgent explicitly
249
+ }
250
  try:
251
+ super().__init__(**minimal_super_args)
252
+ logger.info("QuestionAnsweringAgent (CodeAgent) super().__init__ called with MINIMAL args (workaround active).")
253
+
254
+ # Explicitly set CodeAgent-specific attributes after init.
255
+ # This relies on CodeAgent using these instance attributes.
256
+ self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
257
+ logger.info(f"Explicitly set self.system_prompt for CodeAgent.")
258
+
259
+ # These might be read-only or set internally in a way this doesn't override.
260
+ # We log a warning if the attribute doesn't exist to be set.
261
+ if hasattr(self, 'verbosity_level'):
262
+ self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
263
+ logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  else:
265
+ logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
266
+
267
+ if hasattr(self, 'additional_authorized_imports'):
268
+ self.additional_authorized_imports = ["PIL"] # Make sure PIL is in requirements if needed
269
+ logger.info(f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
270
+ else:
271
+ logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
272
+
273
+ # The CodeWriter is crucial for CodeAgent. It's usually initialized within CodeAgent's __init__.
274
+ # If the minimal super call doesn't set it up, the agent might fail to generate code.
275
+ # This is a deeper aspect of the workaround's potential side effects.
276
+ if not hasattr(self, 'code_writer') or self.code_writer is None:
277
+ logger.warning("self.code_writer might not be initialized due to workaround. Agent may fail to generate code.")
278
+
279
 
280
  except TypeError as e:
281
+ logger.error(f"WORKAROUND FAILED: Still got TypeError during minimal super().__init__: {e}", exc_info=True)
282
  raise e
 
 
 
283
 
284
+ logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
285
 
286
 
287
  async def process_question(self, question_text: str) -> Tuple[str, str]:
 
312
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
313
  else:
314
  logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
315
+ final_answer_for_submission = full_agent_response.strip()
316
 
317
  if not final_answer_for_submission:
318
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
 
332
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
333
  class ChuckAgent:
334
  def __init__(self):
 
 
 
335
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
336
  missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
337
  if missing_vars:
 
347
  asyncio.set_event_loop(self.loop)
348
 
349
  self.http_session = self.loop.run_until_complete(get_shared_http_session())
350
+ self.agent = QuestionAnsweringAgent(http_session=self.http_session) # This might raise if the workaround fails
 
 
 
 
 
 
351
  logger.info("ChuckAgent fully initialized")
352
 
353
  def __call__(self, question: str) -> Tuple[str, str]:
 
372
  logger.info("ChuckAgent shutdown complete.")
373
 
374
  # --- Core Evaluation Logic ---
 
375
  def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
376
  space_id = os.getenv("SPACE_ID")
377
  agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
 
503
 
504
  try:
505
  if GLOBAL_CHUCK_AGENT is None:
506
+ GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
507
  agent_instance = GLOBAL_CHUCK_AGENT
508
+ except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
509
+ logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
 
 
 
510
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
511
+ except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError we're fixing
512
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
513
  return f"Error initializing agent: {e}", pd.DataFrame()
514
 
 
538
  )
539
  gr.Markdown(
540
  """
541
+ **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.
542
  """
543
  )
544
  gr.Markdown(
 
547
  **Technical Notes:**
548
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
549
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
550
+ * `requirements.txt` should specify a compatible `gradio` version (e.g., `gradio==4.29.0` or `gradio==4.44.1`).
551
+ * The current `smolagents` version might have an internal issue with `CodeAgent` initialization. A workaround is active.
552
  """
553
  )
554
 
 
599
  if loop_to_use and loop_to_use.is_running():
600
  logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
601
  try:
602
+ current_loop = asyncio.get_event_loop_policy().get_event_loop() # More robust way to get current loop
603
  if current_loop is not loop_to_use and not loop_to_use.is_closed():
604
  asyncio.set_event_loop(loop_to_use)
605
 
 
610
  except Exception as e:
611
  logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
612
  else:
613
+ logger.info("No active HTTP session or running loop to close in finally block.")