GoodLuckChuck commited on
Commit
3926e70
·
verified ·
1 Parent(s): 9be2fea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -73
app.py CHANGED
@@ -10,15 +10,36 @@ 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,11 +49,11 @@ class AppConfig:
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,18 +72,12 @@ Follow this process for every question:
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,12 +89,6 @@ 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,11 +114,11 @@ async def close_shared_http_session():
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,7 +149,7 @@ class ImageRetrievalTool(Tool):
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,7 +202,7 @@ class WebSearchTool(Tool):
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,7 +217,7 @@ class CalculatorTool(Tool):
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,7 +232,11 @@ class CalculatorTool(Tool):
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,54 +247,58 @@ class QuestionAnsweringAgent(CodeAgent):
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,7 +329,7 @@ class QuestionAnsweringAgent(CodeAgent):
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,6 +349,9 @@ class QuestionAnsweringAgent(CodeAgent):
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,7 +367,13 @@ class ChuckAgent:
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,6 +398,7 @@ class ChuckAgent:
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,12 +530,15 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
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,7 +568,7 @@ with gr.Blocks() as demo:
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,8 +577,8 @@ with gr.Blocks() as demo:
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,7 +629,7 @@ if __name__ == "__main__":
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,4 +640,5 @@ if __name__ == "__main__":
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.")
 
 
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__)
18
+
19
  # Import necessary components from smolagents
20
  try:
21
  from smolagents import CodeAgent, Tool, OpenAIServerModel
22
+ from smolagents.code_writer import CodeWriter
23
+ from smolagents.execution import LocalPythonExecutor # MODIFIED: Added import
24
+ SMOLAGENTS_IMPORTED_SUCCESSFULLY = True
25
+ logger.info("Successfully imported CodeAgent, Tool, OpenAIServerModel, CodeWriter, and LocalPythonExecutor from smolagents.")
26
+ except ImportError as e:
27
+ logger.error(f"CRITICAL: Failed to import base smolagents components. Error: {e}. Ensure smolagents is correctly installed via requirements.txt.", exc_info=True)
28
+ SMOLAGENTS_IMPORTED_SUCCESSFULLY = False
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
+ class CodeWriter:
36
+ def __init__(self, *args, **kwargs):
37
+ logging.warning("Using DUMMY CodeWriter due to smolagents.code_writer import failure.")
38
+ pass
39
+ class LocalPythonExecutor: # Dummy if import fails
40
+ def __init__(self, *args, **kwargs):
41
+ logging.warning("Using DUMMY LocalPythonExecutor due to smolagents.execution import failure.")
42
+ pass
43
 
44
  from datetime import datetime
45
 
 
49
  QUESTIONS_URL_PATH = "/questions"
50
  SUBMIT_URL_PATH = "/submit"
51
  SCREENSHOTS_DIR = "screenshots"
52
+ OPENAI_MODEL_ID = "gpt-4o"
53
  SERPER_API_NUM_RESULTS = 3
54
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
55
+ AGENT_MAX_STEPS = 12
56
+ AGENT_VERBOSITY_LEVEL = 2
57
 
58
  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.
59
  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.
 
72
  # Your Python code to call ONE tool.
73
  # REMEMBER: Use `await` for `web_search` and `image_retriever`.
74
  # ALWAYS print the result of the tool call.
 
 
 
 
 
 
75
  ```<end_code>
76
  4. OBSERVATION: [The system will insert the printed output of your tool call here.]
77
  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.
78
  6. If you have the information, formulate the final answer according to the formatting rules.
79
 
80
+ CRITICAL: Your *entire response* for each turn must culminate in the final answer using this exact template on a new line:
81
  FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
82
 
83
  Formatting rules for the value in FINAL ANSWER:
 
89
 
90
  CONFIG = AppConfig()
91
 
 
 
 
 
 
 
92
  # --- Utility Functions ---
93
  def ensure_dir_exists(directory_path: str):
94
  os.makedirs(directory_path, exist_ok=True)
 
114
 
115
  # --- Tool Definitions ---
116
  class ImageRetrievalTool(Tool):
117
+ name = "image_retriever"
118
  description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
119
  inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
120
  output_type = "string"
121
+ is_async = True
122
 
123
  def __init__(self, session: aiohttp.ClientSession):
124
  super().__init__()
 
149
  return f"Error retrieving image: {str(e)}"
150
 
151
  class WebSearchTool(Tool):
152
+ name = "web_search"
153
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
154
  inputs = {"query": {"type": "string", "description": "The search query to execute."}}
155
  output_type = "string"
 
202
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
203
 
204
  class CalculatorTool(Tool):
205
+ name = "calculator"
206
  description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
207
  inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
208
  output_type = "string"
 
217
  }
218
  self.allowed_chars = "0123456789+-*/^(). "
219
 
220
+ async def forward(self, expression: str) -> str:
221
  logger.info(f"CalculatorTool called with expression: {expression}")
222
  try:
223
  safe_expr = "".join(c for c in expression if c in self.allowed_chars)
 
232
  # --- Agent Definition ---
233
  class QuestionAnsweringAgent(CodeAgent):
234
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
235
+ if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
236
+ logger.error("Cannot initialize QuestionAnsweringAgent: smolagents components failed to import earlier.")
237
+ raise ImportError("smolagents components not available for QuestionAnsweringAgent.")
238
+
239
+ tools_list = [
240
  WebSearchTool(session=http_session),
241
  CalculatorTool(),
242
  ImageRetrievalTool(session=http_session)
 
247
  openai_api_key = os.environ.get('OPENAI_API_KEY')
248
  if not openai_api_key:
249
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
250
+ effective_model = OpenAIServerModel(
251
  model_id=CONFIG.OPENAI_MODEL_ID,
252
+ api_key=openai_api_key
253
  )
254
 
255
+ # REFINED WORKAROUND for MultiStepAgent internal TypeError
 
 
 
 
 
 
 
256
  try:
257
+ # Step 1: Initialize the parent of CodeAgent (MultiStepAgent)
258
+ # Pass arguments that MultiStepAgent or its parent (Agent) would expect.
259
+ # `additional_authorized_imports` is handled by the base `Agent` class.
260
+ super(CodeAgent, self).__init__(
261
+ model=effective_model,
262
+ tools=tools_list,
263
+ max_steps=CONFIG.AGENT_MAX_STEPS,
264
+ additional_authorized_imports=["PIL", "pandas"] # This should be handled by Agent.__init__
265
+ )
266
+ logger.info("QuestionAnsweringAgent > MultiStepAgent part initialized (workaround for init).")
 
 
 
 
 
267
 
268
+ # Step 2: Manually set attributes specific to CodeAgent on the instance.
269
+ self.model = effective_model
270
+ self.tools = tools_list
271
+ self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
272
+ self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
273
+
274
+ # Step 3: Manually initialize CodeAgent's `code_writer`.
275
+ if SMOLAGENTS_IMPORTED_SUCCESSFULLY:
276
+ self.code_writer = CodeWriter(
277
+ model=self.model,
278
+ tools=self.tools,
279
+ system_prompt=self.system_prompt,
280
+ additional_authorized_imports=self.additional_authorized_imports # Use the one set by Agent base
281
+ )
282
+ logger.info("Manually initialized self.code_writer for CodeAgent.")
283
  else:
284
+ logger.error("SMOLAGENTS_IMPORTED_SUCCESSFULLY is False. Cannot initialize self.code_writer.")
285
 
286
+ # Step 4: Manually set the executor with timeout disabled to address "signal" error
287
+ if SMOLAGENTS_IMPORTED_SUCCESSFULLY:
288
+ self.executor = LocalPythonExecutor(timeout_seconds=None)
289
+ logger.info("Manually set self.executor with timeout_seconds=None.")
290
+ else:
291
+ logger.error("SMOLAGENTS_IMPORTED_SUCCESSFULLY is False. Cannot initialize self.executor.")
292
 
293
 
294
  except TypeError as e:
295
+ logger.error(f"WORKAROUND FAILED during __init__ (TypeError): {e}.", exc_info=True)
296
  raise e
297
+ except Exception as e_init:
298
+ logger.error(f"Unexpected error during QuestionAnsweringAgent __init__ (workaround): {e_init}", exc_info=True)
299
+ raise e_init
300
 
301
+ logger.info(f"QuestionAnsweringAgent initialized (with workaround) with model: {CONFIG.OPENAI_MODEL_ID}.")
302
 
303
 
304
  async def process_question(self, question_text: str) -> Tuple[str, str]:
 
329
  logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
330
  else:
331
  logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
332
+ final_answer_for_submission = full_agent_response.strip()
333
 
334
  if not final_answer_for_submission:
335
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
 
349
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
350
  class ChuckAgent:
351
  def __init__(self):
352
+ if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
353
+ raise ImportError("smolagents components not available, ChuckAgent cannot be initialized.")
354
+
355
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
356
  missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
357
  if missing_vars:
 
367
  asyncio.set_event_loop(self.loop)
368
 
369
  self.http_session = self.loop.run_until_complete(get_shared_http_session())
370
+ try:
371
+ self.agent = QuestionAnsweringAgent(http_session=self.http_session)
372
+ except Exception as agent_init_error:
373
+ logger.error(f"Failed to initialize QuestionAnsweringAgent within ChuckAgent: {agent_init_error}", exc_info=True)
374
+ self.loop.run_until_complete(close_shared_http_session())
375
+ raise
376
+
377
  logger.info("ChuckAgent fully initialized")
378
 
379
  def __call__(self, question: str) -> Tuple[str, str]:
 
398
  logger.info("ChuckAgent shutdown complete.")
399
 
400
  # --- Core Evaluation Logic ---
401
+ # (This section remains unchanged)
402
  def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
403
  space_id = os.getenv("SPACE_ID")
404
  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)"
 
530
 
531
  try:
532
  if GLOBAL_CHUCK_AGENT is None:
533
+ GLOBAL_CHUCK_AGENT = ChuckAgent()
534
  agent_instance = GLOBAL_CHUCK_AGENT
535
+ except ImportError as e:
536
+ logger.critical(f"Agent instantiation failed due to smolagents import error: {e}", exc_info=True)
537
+ return f"Agent Initialization Error: Failed to import smolagents. Check Space logs for build errors.", pd.DataFrame()
538
+ except EnvironmentError as e:
539
+ logger.critical(f"Agent instantiation failed due to missing env vars: {e}", exc_info=True)
540
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
541
+ except Exception as e:
542
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
543
  return f"Error initializing agent: {e}", pd.DataFrame()
544
 
 
568
  )
569
  gr.Markdown(
570
  """
571
+ **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.
572
  """
573
  )
574
  gr.Markdown(
 
577
  **Technical Notes:**
578
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
579
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
580
+ * `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
581
+ * A workaround for `smolagents.CodeAgent` initialization is currently active.
582
  """
583
  )
584
 
 
629
  if loop_to_use and loop_to_use.is_running():
630
  logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
631
  try:
632
+ current_loop = asyncio.get_event_loop_policy().get_event_loop()
633
  if current_loop is not loop_to_use and not loop_to_use.is_closed():
634
  asyncio.set_event_loop(loop_to_use)
635
 
 
640
  except Exception as e:
641
  logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
642
  else:
643
+ logger.info("No active HTTP session or running loop to close in finally block.")
644
+