GoodLuckChuck commited on
Commit
3806bd4
·
verified ·
1 Parent(s): e17f547

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -14
app.py CHANGED
@@ -11,19 +11,20 @@ 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
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
@@ -32,6 +33,11 @@ except ImportError as e:
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
 
@@ -44,7 +50,7 @@ class AppConfig:
44
  OPENAI_MODEL_ID = "gpt-4o"
45
  SERPER_API_NUM_RESULTS = 3
46
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
47
- AGENT_MAX_STEPS = 10
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.
@@ -244,22 +250,45 @@ class QuestionAnsweringAgent(CodeAgent):
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
  )
256
- logger.info(f"QuestionAnsweringAgent initialized successfully with model: {CONFIG.OPENAI_MODEL_ID}.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  except TypeError as e:
258
- logger.error(f"TypeError during QuestionAnsweringAgent super().__init__: {e}. This might be the 'MultiStepAgent' issue if smolagents version is problematic.", exc_info=True)
259
  raise e
260
- except Exception as e_init:
261
- logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e_init}", exc_info=True)
262
  raise e_init
 
 
263
 
264
 
265
  async def process_question(self, question_text: str) -> Tuple[str, str]:
@@ -538,7 +567,7 @@ with gr.Blocks() as demo:
538
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
539
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
540
  * `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
541
- * If `smolagents` initialization errors occur, it might be due to internal library issues with the installed version.
542
  """
543
  )
544
 
 
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 need CodeWriter for the __init__ workaround.
21
  try:
22
  from smolagents import CodeAgent, Tool, OpenAIServerModel
23
+ from smolagents.code_writer import CodeWriter # For the __init__ workaround
24
  SMOLAGENTS_IMPORTED_SUCCESSFULLY = True
25
+ logger.info("Successfully imported CodeAgent, Tool, OpenAIServerModel, and CodeWriter from smolagents.")
26
  except ImportError as e:
27
+ logger.error(f"CRITICAL: Failed to import base smolagents components or smolagents.code_writer. Error: {e}. Ensure smolagents is correctly installed via requirements.txt.", exc_info=True)
28
  SMOLAGENTS_IMPORTED_SUCCESSFULLY = False
29
  # Dummy classes for script parsing if smolagents is not installed
30
  class CodeAgent: pass
 
33
  def __init__(self, *args, **kwargs):
34
  logging.warning("Using DUMMY OpenAIServerModel due to smolagents import failure.")
35
  pass
36
+ class CodeWriter: # Dummy for parsing if import fails
37
+ def __init__(self, *args, **kwargs):
38
+ logging.warning("Using DUMMY CodeWriter due to smolagents.code_writer import failure.")
39
+ pass
40
+
41
 
42
  from datetime import datetime
43
 
 
50
  OPENAI_MODEL_ID = "gpt-4o"
51
  SERPER_API_NUM_RESULTS = 3
52
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
53
+ AGENT_MAX_STEPS = 12 # Slightly increased max_steps
54
  AGENT_VERBOSITY_LEVEL = 2
55
 
56
  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.
 
250
  api_key=openai_api_key
251
  )
252
 
253
+ # REINSTATED WORKAROUND for MultiStepAgent TypeError
254
  try:
255
+ # Step 1: Initialize the parent of CodeAgent (MultiStepAgent) with minimal arguments.
256
+ super(CodeAgent, self).__init__(
257
  model=effective_model,
258
  tools=tools_list,
259
+ max_steps=CONFIG.AGENT_MAX_STEPS
 
 
 
260
  )
261
+ logger.info("QuestionAnsweringAgent > MultiStepAgent super().__init__ called with MINIMAL args (workaround active).")
262
+
263
+ # Step 2: Set CodeAgent's own specific attributes directly.
264
+ self.model = effective_model
265
+ self.tools = tools_list
266
+ self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
267
+ self.additional_authorized_imports = ["PIL", "pandas"]
268
+ self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
269
+
270
+ # Step 3: Manually create and assign CodeAgent's CodeWriter.
271
+ # This is critical for the system_prompt to be used correctly by the LLM.
272
+ if SMOLAGENTS_IMPORTED_SUCCESSFULLY: # Only if CodeWriter was actually imported
273
+ self.code_writer = CodeWriter(
274
+ model=self.model,
275
+ tools=self.tools,
276
+ system_prompt=self.system_prompt,
277
+ additional_authorized_imports=self.additional_authorized_imports
278
+ )
279
+ logger.info("Manually initialized self.code_writer for CodeAgent.")
280
+ else:
281
+ logger.error("Cannot initialize self.code_writer because CodeWriter component from smolagents failed to import.")
282
+ # The agent will likely not function correctly without a code_writer.
283
+
284
  except TypeError as e:
285
+ logger.error(f"WORKAROUND FAILED during __init__ (TypeError): {e}. This suggests an issue with the minimal args for MultiStepAgent or CodeWriter.", exc_info=True)
286
  raise e
287
+ except Exception as e_init:
288
+ logger.error(f"Unexpected error during QuestionAnsweringAgent __init__ (workaround): {e_init}", exc_info=True)
289
  raise e_init
290
+
291
+ logger.info(f"QuestionAnsweringAgent initialized (with workaround) with model: {CONFIG.OPENAI_MODEL_ID}.")
292
 
293
 
294
  async def process_question(self, question_text: str) -> Tuple[str, str]:
 
567
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
568
  * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
569
  * `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
570
+ * A workaround is active for `smolagents.CodeAgent` initialization.
571
  """
572
  )
573