Update app.py
Browse files
app.py
CHANGED
|
@@ -11,21 +11,26 @@ import aiohttp
|
|
| 11 |
from typing import Optional, Dict, Any, List, Tuple
|
| 12 |
|
| 13 |
# Import necessary components from smolagents
|
| 14 |
-
# We
|
| 15 |
-
# The explicit CodeWriter import is removed as it might be causing the root import error.
|
| 16 |
try:
|
| 17 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 18 |
-
|
|
|
|
| 19 |
except ImportError:
|
| 20 |
-
logging.error("CRITICAL: Failed to import base smolagents components (CodeAgent, Tool, OpenAIServerModel). Ensure smolagents is correctly installed via requirements.txt.")
|
|
|
|
| 21 |
# Dummy classes for script parsing if smolagents is not installed
|
| 22 |
class CodeAgent: pass
|
| 23 |
class Tool: pass
|
| 24 |
-
class OpenAIServerModel:
|
| 25 |
-
def __init__(self, *args, **kwargs):
|
| 26 |
logging.warning("Using DUMMY OpenAIServerModel due to import failure.")
|
| 27 |
pass
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
from datetime import datetime
|
| 31 |
|
|
@@ -224,6 +229,10 @@ class CalculatorTool(Tool):
|
|
| 224 |
# --- Agent Definition ---
|
| 225 |
class QuestionAnsweringAgent(CodeAgent):
|
| 226 |
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
tools_list = [
|
| 228 |
WebSearchTool(session=http_session),
|
| 229 |
CalculatorTool(),
|
|
@@ -235,35 +244,53 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 235 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 236 |
if not openai_api_key:
|
| 237 |
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 238 |
-
# This
|
| 239 |
-
# because the DUMMY OpenAIServerModel was being used due to earlier import failure.
|
| 240 |
-
# If the main `from smolagents import ... OpenAIServerModel` works, this will be the REAL one.
|
| 241 |
-
effective_model = OpenAIServerModel(
|
| 242 |
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 243 |
-
api_key=openai_api_key
|
| 244 |
)
|
| 245 |
|
| 246 |
-
#
|
| 247 |
-
# This assumes that if `smolagents` imports correctly, its internal
|
| 248 |
-
# `CodeAgent` -> `MultiStepAgent` initialization will work.
|
| 249 |
-
# If the "MultiStepAgent TypeError" returns, it means the installed `smolagents` version
|
| 250 |
-
# still has that internal issue.
|
| 251 |
try:
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
model=effective_model,
|
| 254 |
tools=tools_list,
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
)
|
| 260 |
-
logger.info(
|
|
|
|
| 261 |
except TypeError as e:
|
| 262 |
-
logger.error(f"
|
| 263 |
-
raise e
|
| 264 |
-
except Exception as e_init:
|
| 265 |
-
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e_init}", exc_info=True)
|
| 266 |
raise e_init
|
|
|
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
|
@@ -272,7 +299,6 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 272 |
try:
|
| 273 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 274 |
|
| 275 |
-
# self.run() is synchronous for CodeAgent in some smolagents versions/setups
|
| 276 |
raw_output_obj = self.run(question_text)
|
| 277 |
|
| 278 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
|
@@ -315,6 +341,11 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 315 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 316 |
class ChuckAgent:
|
| 317 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
| 319 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 320 |
if missing_vars:
|
|
@@ -330,16 +361,12 @@ class ChuckAgent:
|
|
| 330 |
asyncio.set_event_loop(self.loop)
|
| 331 |
|
| 332 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
| 333 |
-
# This is where QuestionAnsweringAgent is instantiated
|
| 334 |
-
# If the import of smolagents failed, OpenAIServerModel(...) will use the dummy and raise TypeError
|
| 335 |
-
# If smolagents imported but has internal issues, QuestionAnsweringAgent's super().__init__ might raise
|
| 336 |
try:
|
| 337 |
self.agent = QuestionAnsweringAgent(http_session=self.http_session)
|
| 338 |
except Exception as agent_init_error:
|
| 339 |
-
logger.error(f"Failed to initialize QuestionAnsweringAgent: {agent_init_error}", exc_info=True)
|
| 340 |
-
#
|
| 341 |
-
|
| 342 |
-
raise # Re-raise the error to stop ChuckAgent creation
|
| 343 |
|
| 344 |
logger.info("ChuckAgent fully initialized")
|
| 345 |
|
|
@@ -365,7 +392,6 @@ class ChuckAgent:
|
|
| 365 |
logger.info("ChuckAgent shutdown complete.")
|
| 366 |
|
| 367 |
# --- Core Evaluation Logic ---
|
| 368 |
-
# (This section remains unchanged from your last version)
|
| 369 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 370 |
space_id = os.getenv("SPACE_ID")
|
| 371 |
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,7 +529,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 503 |
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 504 |
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 505 |
except Exception as e:
|
| 506 |
-
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 507 |
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 508 |
|
| 509 |
try:
|
|
@@ -542,7 +568,7 @@ with gr.Blocks() as demo:
|
|
| 542 |
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 543 |
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 544 |
* `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
|
| 545 |
-
*
|
| 546 |
"""
|
| 547 |
)
|
| 548 |
|
|
|
|
| 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 |
# --- 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),
|
| 238 |
CalculatorTool(),
|
|
|
|
| 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]:
|
|
|
|
| 299 |
try:
|
| 300 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 301 |
|
|
|
|
| 302 |
raw_output_obj = self.run(question_text)
|
| 303 |
|
| 304 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
|
|
|
| 341 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 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']
|
| 350 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 351 |
if missing_vars:
|
|
|
|
| 361 |
asyncio.set_event_loop(self.loop)
|
| 362 |
|
| 363 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
|
|
|
|
|
|
|
|
|
| 364 |
try:
|
| 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")
|
| 372 |
|
|
|
|
| 392 |
logger.info("ChuckAgent shutdown complete.")
|
| 393 |
|
| 394 |
# --- Core Evaluation Logic ---
|
|
|
|
| 395 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 396 |
space_id = os.getenv("SPACE_ID")
|
| 397 |
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)"
|
|
|
|
| 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 |
|
| 535 |
try:
|
|
|
|
| 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 |
|