GoodLuckChuck commited on
Commit
57b3972
·
verified ·
1 Parent(s): 7eae2af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -56
app.py CHANGED
@@ -11,26 +11,22 @@ import aiohttp
11
  from typing import Optional, Dict, Any, List, Tuple
12
 
13
  # Import necessary components from smolagents
14
- # We need CodeWriter for the workaround.
 
15
  try:
16
  from smolagents import CodeAgent, Tool, OpenAIServerModel
17
- from smolagents.code_writer import CodeWriter # For the __init__ workaround
18
  SMOLAGENTS_IMPORTED_SUCCESSFULLY = True
19
- except ImportError:
20
- logging.error("CRITICAL: Failed to import base smolagents components (CodeAgent, Tool, OpenAIServerModel) or smolagents.code_writer. Ensure smolagents is correctly installed via requirements.txt.")
 
21
  SMOLAGENTS_IMPORTED_SUCCESSFULLY = False
22
  # Dummy classes for script parsing if smolagents is not installed
23
  class CodeAgent: pass
24
  class Tool: pass
25
  class OpenAIServerModel:
26
- def __init__(self, *args, **kwargs):
27
- logging.warning("Using DUMMY OpenAIServerModel due to import failure.")
28
  pass
29
- class CodeWriter: # Dummy for parsing if import fails
30
- def __init__(self, *args, **kwargs):
31
- logging.warning("Using DUMMY CodeWriter due to import failure.")
32
- pass
33
-
34
 
35
  from datetime import datetime
36
 
@@ -229,9 +225,9 @@ class CalculatorTool(Tool):
229
  # --- Agent Definition ---
230
  class QuestionAnsweringAgent(CodeAgent):
231
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
232
- if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
233
- logger.error("Cannot initialize QuestionAnsweringAgent: smolagents components failed to import.")
234
- raise ImportError("smolagents components not available.")
235
 
236
  tools_list = [
237
  WebSearchTool(session=http_session),
@@ -244,53 +240,31 @@ class QuestionAnsweringAgent(CodeAgent):
244
  openai_api_key = os.environ.get('OPENAI_API_KEY')
245
  if not openai_api_key:
246
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
247
- effective_model = OpenAIServerModel( # This will be the REAL OpenAIServerModel if import was successful
248
  model_id=CONFIG.OPENAI_MODEL_ID,
249
  api_key=openai_api_key
250
  )
251
 
252
- # REINSTATED WORKAROUND for MultiStepAgent TypeError
 
 
 
253
  try:
254
- # Step 1: Initialize the parent of CodeAgent (MultiStepAgent) with minimal arguments.
255
- # CodeAgent's __init__ is: def __init__(self, model, tools, system_prompt=..., code_writer=None, max_steps=..., verbosity_level=..., **kwargs)
256
- # It then calls: super().__init__(model=model, tools=tools, max_steps=max_steps, code_writer=self.code_writer, **kwargs)
257
- # The **kwargs in CodeAgent's super() call is what causes issues if system_prompt etc. are in it.
258
- # So, we call CodeAgent's super() (which is MultiStepAgent.__init__) directly with only what it expects.
259
- super(CodeAgent, self).__init__( # Explicitly calling MultiStepAgent.__init__
260
  model=effective_model,
261
  tools=tools_list,
262
- max_steps=CONFIG.AGENT_MAX_STEPS
263
- )
264
- logger.info("QuestionAnsweringAgent > MultiStepAgent super().__init__ called with MINIMAL args (workaround active).")
265
-
266
- # Step 2: Set CodeAgent's own specific attributes.
267
- # These are attributes CodeAgent uses for its own logic, not passed to MultiStepAgent.
268
- self.model = effective_model # CodeAgent also uses self.model
269
- self.tools = tools_list # CodeAgent also uses self.tools
270
- self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
271
- self.additional_authorized_imports = ["PIL", "pandas"] # Added "pandas"
272
- self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
273
- # self.max_steps is already set by the super() call to MultiStepAgent.
274
-
275
- # Step 3: Manually create and assign CodeAgent's CodeWriter.
276
- # This is critical for the system_prompt and tool descriptions to be used by the LLM.
277
- # CodeWriter is imported at the top of the file.
278
- self.code_writer = CodeWriter(
279
- model=self.model, # Use the model assigned to the agent
280
- tools=self.tools, # Use the tools assigned to the agent
281
- system_prompt=self.system_prompt, # Pass the detailed system prompt
282
- additional_authorized_imports=self.additional_authorized_imports
283
  )
284
- logger.info("Manually initialized self.code_writer for CodeAgent.")
285
-
286
  except TypeError as e:
287
- logger.error(f"WORKAROUND FAILED during __init__ (TypeError): {e}. This suggests an issue with the minimal args for MultiStepAgent or CodeWriter.", exc_info=True)
288
  raise e
289
- except Exception as e_init: # Catch any other exception during this delicate init
290
- logger.error(f"Unexpected error during QuestionAnsweringAgent __init__ (workaround): {e_init}", exc_info=True)
291
  raise e_init
292
-
293
- logger.info(f"QuestionAnsweringAgent initialized (with workaround) with model: {CONFIG.OPENAI_MODEL_ID}.")
294
 
295
 
296
  async def process_question(self, question_text: str) -> Tuple[str, str]:
@@ -342,8 +316,6 @@ class QuestionAnsweringAgent(CodeAgent):
342
  class ChuckAgent:
343
  def __init__(self):
344
  if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
345
- # This check is a bit redundant if QuestionAnsweringAgent also checks,
346
- # but good for clarity if ChuckAgent was used elsewhere.
347
  raise ImportError("smolagents components not available, ChuckAgent cannot be initialized.")
348
 
349
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
@@ -365,7 +337,7 @@ class ChuckAgent:
365
  self.agent = QuestionAnsweringAgent(http_session=self.http_session)
366
  except Exception as agent_init_error:
367
  logger.error(f"Failed to initialize QuestionAnsweringAgent within ChuckAgent: {agent_init_error}", exc_info=True)
368
- self.loop.run_until_complete(close_shared_http_session()) # Cleanup session
369
  raise
370
 
371
  logger.info("ChuckAgent fully initialized")
@@ -525,10 +497,13 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
525
  if GLOBAL_CHUCK_AGENT is None:
526
  GLOBAL_CHUCK_AGENT = ChuckAgent()
527
  agent_instance = GLOBAL_CHUCK_AGENT
 
 
 
528
  except EnvironmentError as e:
529
- logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
530
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
531
- except Exception as e:
532
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
533
  return f"Error initializing agent: {e}", pd.DataFrame()
534
 
@@ -568,7 +543,7 @@ with gr.Blocks() as demo:
568
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
569
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
570
  * `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
571
- * A workaround is active for `smolagents.CodeAgent` initialization.
572
  """
573
  )
574
 
 
11
  from typing import Optional, Dict, Any, List, Tuple
12
 
13
  # Import necessary components from smolagents
14
+ # Simplified import block to isolate the issue.
15
+ # We are no longer trying to import CodeWriter directly here.
16
  try:
17
  from smolagents import CodeAgent, Tool, OpenAIServerModel
 
18
  SMOLAGENTS_IMPORTED_SUCCESSFULLY = True
19
+ logger.info("Successfully imported CodeAgent, Tool, OpenAIServerModel from smolagents.")
20
+ except ImportError as e:
21
+ logger.error(f"CRITICAL: Failed to import base smolagents components. Error: {e}. Ensure smolagents is correctly installed via requirements.txt.", exc_info=True)
22
  SMOLAGENTS_IMPORTED_SUCCESSFULLY = False
23
  # Dummy classes for script parsing if smolagents is not installed
24
  class CodeAgent: pass
25
  class Tool: pass
26
  class OpenAIServerModel:
27
+ def __init__(self, *args, **kwargs): # Make dummy accept args to avoid immediate crash
28
+ logging.warning("Using DUMMY OpenAIServerModel due to smolagents import failure.")
29
  pass
 
 
 
 
 
30
 
31
  from datetime import datetime
32
 
 
225
  # --- Agent Definition ---
226
  class QuestionAnsweringAgent(CodeAgent):
227
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
228
+ if not SMOLAGENTS_IMPORTED_SUCCESSFULLY: # Check if base imports were successful
229
+ logger.error("Cannot initialize QuestionAnsweringAgent: smolagents components failed to import earlier.")
230
+ raise ImportError("smolagents components not available for QuestionAnsweringAgent.")
231
 
232
  tools_list = [
233
  WebSearchTool(session=http_session),
 
240
  openai_api_key = os.environ.get('OPENAI_API_KEY')
241
  if not openai_api_key:
242
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
243
+ effective_model = OpenAIServerModel( # This will use the REAL OpenAIServerModel
244
  model_id=CONFIG.OPENAI_MODEL_ID,
245
  api_key=openai_api_key
246
  )
247
 
248
+ # REVERTED TO STANDARD CodeAgent INITIALIZATION
249
+ # This is the standard way to initialize CodeAgent.
250
+ # If this still causes a "MultiStepAgent... system_prompt" TypeError,
251
+ # it means the installed version of smolagents has an internal bug.
252
  try:
253
+ super().__init__(
 
 
 
 
 
254
  model=effective_model,
255
  tools=tools_list,
256
+ system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
257
+ additional_authorized_imports=["PIL", "pandas"], # Added "pandas"
258
+ max_steps=CONFIG.AGENT_MAX_STEPS,
259
+ verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  )
261
+ logger.info(f"QuestionAnsweringAgent initialized successfully with model: {CONFIG.OPENAI_MODEL_ID}.")
 
262
  except TypeError as e:
263
+ logger.error(f"TypeError during QuestionAnsweringAgent super().__init__: {e}. This might be the 'MultiStepAgent' issue if smolagents version is problematic.", exc_info=True)
264
  raise e
265
+ except Exception as e_init:
266
+ logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e_init}", exc_info=True)
267
  raise e_init
 
 
268
 
269
 
270
  async def process_question(self, question_text: str) -> Tuple[str, str]:
 
316
  class ChuckAgent:
317
  def __init__(self):
318
  if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
 
 
319
  raise ImportError("smolagents components not available, ChuckAgent cannot be initialized.")
320
 
321
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
 
337
  self.agent = QuestionAnsweringAgent(http_session=self.http_session)
338
  except Exception as agent_init_error:
339
  logger.error(f"Failed to initialize QuestionAnsweringAgent within ChuckAgent: {agent_init_error}", exc_info=True)
340
+ self.loop.run_until_complete(close_shared_http_session())
341
  raise
342
 
343
  logger.info("ChuckAgent fully initialized")
 
497
  if GLOBAL_CHUCK_AGENT is None:
498
  GLOBAL_CHUCK_AGENT = ChuckAgent()
499
  agent_instance = GLOBAL_CHUCK_AGENT
500
+ except ImportError as e: # Catch the specific import error from ChuckAgent
501
+ logger.critical(f"Agent instantiation failed due to smolagents import error: {e}", exc_info=True)
502
+ return f"Agent Initialization Error: Failed to import smolagents. Check Space logs for build errors.", pd.DataFrame()
503
  except EnvironmentError as e:
504
+ logger.critical(f"Agent instantiation failed due to missing env vars: {e}", exc_info=True)
505
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
506
+ except Exception as e: # Catches other errors, like the MultiStepAgent TypeError if it returns
507
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
508
  return f"Error initializing agent: {e}", pd.DataFrame()
509
 
 
543
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
544
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
545
  * `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
546
+ * If `smolagents` initialization errors occur, it might be due to internal library issues with the installed version.
547
  """
548
  )
549