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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -19
app.py CHANGED
@@ -5,14 +5,19 @@ import pandas as pd
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
- # 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
@@ -24,7 +29,7 @@ except ImportError as e:
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
 
@@ -76,12 +81,6 @@ Formatting rules for the value in FINAL ANSWER:
76
 
77
  CONFIG = AppConfig()
78
 
79
- # --- Logging Setup ---
80
- logging.basicConfig(
81
- level=logging.INFO,
82
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
83
- logger = logging.getLogger(__name__)
84
-
85
  # --- Utility Functions ---
86
  def ensure_dir_exists(directory_path: str):
87
  os.makedirs(directory_path, exist_ok=True)
@@ -225,7 +224,7 @@ class CalculatorTool(Tool):
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
 
@@ -240,21 +239,17 @@ class QuestionAnsweringAgent(CodeAgent):
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
  )
@@ -497,13 +492,13 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
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
 
 
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
+ # MOVED LOGGING SETUP TO THE TOP, BEFORE `logger` IS USED.
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
18
+ logger = logging.getLogger(__name__) # Define logger here
19
+
20
  # Import necessary components from smolagents
 
 
21
  try:
22
  from smolagents import CodeAgent, Tool, OpenAIServerModel
23
  SMOLAGENTS_IMPORTED_SUCCESSFULLY = True
 
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
 
 
81
 
82
  CONFIG = AppConfig()
83
 
 
 
 
 
 
 
84
  # --- Utility Functions ---
85
  def ensure_dir_exists(directory_path: str):
86
  os.makedirs(directory_path, exist_ok=True)
 
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
 
 
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
  try:
248
  super().__init__(
249
  model=effective_model,
250
  tools=tools_list,
251
  system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
252
+ additional_authorized_imports=["PIL", "pandas"],
253
  max_steps=CONFIG.AGENT_MAX_STEPS,
254
  verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
255
  )
 
492
  if GLOBAL_CHUCK_AGENT is None:
493
  GLOBAL_CHUCK_AGENT = ChuckAgent()
494
  agent_instance = GLOBAL_CHUCK_AGENT
495
+ except ImportError as e:
496
  logger.critical(f"Agent instantiation failed due to smolagents import error: {e}", exc_info=True)
497
  return f"Agent Initialization Error: Failed to import smolagents. Check Space logs for build errors.", pd.DataFrame()
498
  except EnvironmentError as e:
499
  logger.critical(f"Agent instantiation failed due to missing env vars: {e}", exc_info=True)
500
  return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
501
+ except Exception as e:
502
  logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
503
  return f"Error initializing agent: {e}", pd.DataFrame()
504