Update app.py
Browse files
app.py
CHANGED
|
@@ -1,43 +1,63 @@
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
|
|
|
| 5 |
import asyncio
|
|
|
|
| 6 |
import re
|
|
|
|
| 7 |
import json
|
|
|
|
| 8 |
import logging
|
|
|
|
| 9 |
import operator # Used by CalculatorTool (if you re-add it)
|
|
|
|
| 10 |
import aiohttp
|
|
|
|
| 11 |
from typing import Optional, Dict, Any, List, Tuple # Added Tuple
|
|
|
|
| 12 |
|
| 13 |
# Import necessary components from smolagents
|
| 14 |
try:
|
| 15 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
|
|
|
| 16 |
except ImportError as e: # Catch the specific error for better logging
|
|
|
|
| 17 |
logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
|
| 18 |
# Dummy classes for script parsing if smolagents is not installed or fails to import
|
| 19 |
# This allows the rest of the script to be parsed, but it won't run correctly.
|
| 20 |
class CodeAgent:
|
| 21 |
def __init__(self, *args, **kwargs):
|
|
|
|
| 22 |
logging.error("Dummy CodeAgent initialized because smolagents failed to import.")
|
| 23 |
def run(self, *args, **kwargs):
|
|
|
|
| 24 |
logging.error("Dummy CodeAgent run called.")
|
| 25 |
return "Error: smolagents not loaded."
|
| 26 |
pass
|
| 27 |
|
| 28 |
class Tool:
|
| 29 |
def __init__(self, *args, **kwargs):
|
|
|
|
| 30 |
logging.error("Dummy Tool initialized because smolagents failed to import.")
|
| 31 |
pass
|
| 32 |
|
| 33 |
class OpenAIServerModel:
|
| 34 |
def __init__(self, *args, **kwargs):
|
|
|
|
| 35 |
logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 36 |
pass
|
| 37 |
|
| 38 |
from datetime import datetime
|
|
|
|
| 39 |
|
| 40 |
# --- Configuration ---
|
|
|
|
| 41 |
class AppConfig:
|
| 42 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 43 |
QUESTIONS_URL_PATH = "/questions"
|
|
@@ -83,16 +103,19 @@ Formatting rules for the value in FINAL ANSWER:
|
|
| 83 |
"""
|
| 84 |
|
| 85 |
CONFIG = AppConfig()
|
|
|
|
| 86 |
|
| 87 |
# --- Logging Setup ---
|
| 88 |
logging.basicConfig(
|
| 89 |
level=logging.INFO,
|
| 90 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 91 |
logger = logging.getLogger(__name__)
|
|
|
|
| 92 |
|
| 93 |
# --- Utility Functions ---
|
| 94 |
def ensure_dir_exists(directory_path: str):
|
| 95 |
"""Creates a directory if it doesn't already exist."""
|
|
|
|
| 96 |
os.makedirs(directory_path, exist_ok=True)
|
| 97 |
|
| 98 |
ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
|
@@ -104,22 +127,24 @@ def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
|
| 104 |
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 105 |
else:
|
| 106 |
agent_code_url = "Agent code URL not found (SPACE_ID not set)"
|
|
|
|
| 107 |
return space_id, agent_code_url
|
| 108 |
|
| 109 |
-
|
| 110 |
-
# --- HTTP Client Session Management ---
|
| 111 |
-
# Using a global session can be problematic with asyncio event loops,
|
| 112 |
-
# especially with Gradio. It's often better to create sessions when needed
|
| 113 |
-
# or manage them within the scope of an async function/class.
|
| 114 |
-
# For this script's structure, we'll manage it within ChuckAgent.
|
| 115 |
|
| 116 |
# --- Tool Definitions ---
|
|
|
|
| 117 |
class GoogleSearchTool(Tool):
|
| 118 |
name = "web_search" # This is the name the LLM will use to call the tool
|
| 119 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 120 |
inputs = {
|
| 121 |
"query": {"type": "string", "description": "The search query to execute."},
|
| 122 |
-
"provider": {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
}
|
| 124 |
output_type = "string"
|
| 125 |
is_async = True # Important for smolagents to know this tool's forward method is async
|
|
@@ -127,16 +152,22 @@ class GoogleSearchTool(Tool):
|
|
| 127 |
def __init__(self, session: aiohttp.ClientSession):
|
| 128 |
super().__init__()
|
| 129 |
self._session = session # Use the session passed from ChuckAgent
|
|
|
|
| 130 |
|
| 131 |
async def forward(self, query: str, provider: str = "serpapi") -> str:
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
logger.info(f"GoogleSearchTool (web_search) called with query: '{query}', provider: '{provider}'")
|
| 137 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 138 |
if not serper_api_key:
|
| 139 |
logger.error("SERPER_API_KEY not found in environment variables.")
|
|
|
|
| 140 |
return "Error: Serper API key not found in environment."
|
| 141 |
|
| 142 |
url = "https://google.serper.dev/search"
|
|
@@ -144,249 +175,276 @@ class GoogleSearchTool(Tool):
|
|
| 144 |
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
|
| 145 |
|
| 146 |
try:
|
| 147 |
-
# Use the session provided during initialization
|
| 148 |
async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
|
| 149 |
-
response.raise_for_status()
|
| 150 |
data = await response.json()
|
|
|
|
| 151 |
return self._format_results(data)
|
| 152 |
except asyncio.TimeoutError:
|
| 153 |
logger.error(f"Timeout performing search for '{query}'")
|
|
|
|
| 154 |
return f"Error: Timeout during web search for '{query}'."
|
| 155 |
except aiohttp.ClientResponseError as e:
|
| 156 |
logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
|
|
|
|
| 157 |
return f"Error performing search (HTTP {e.status}): {e.message}"
|
| 158 |
-
except aiohttp.ClientError as e:
|
| 159 |
logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
|
|
|
|
| 160 |
return f"Error performing search (client error): {str(e)}"
|
| 161 |
except Exception as e:
|
| 162 |
logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
|
|
|
|
| 163 |
return f"Error performing search: An unexpected error occurred."
|
| 164 |
|
| 165 |
def _format_results(self, data: Dict[str, Any]) -> str:
|
| 166 |
-
"""Formats search results from Serper API into a string."""
|
| 167 |
results = []
|
| 168 |
if 'organic' in data and data['organic']:
|
| 169 |
for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
|
| 170 |
title = result.get('title', 'N/A')
|
| 171 |
snippet = result.get('snippet', 'N/A')
|
| 172 |
-
# link = result.get('link', '#') # Links are not directly useful for the LLM in this context
|
| 173 |
results.append(f"Title: {title}\nSnippet: {snippet}\n---")
|
| 174 |
-
|
| 175 |
-
if not results and 'knowledgeGraph' in data: # Fallback to knowledge graph if no organic results
|
| 176 |
kg = data['knowledgeGraph']
|
| 177 |
title = kg.get('title', '')
|
| 178 |
description = kg.get('description', '')
|
| 179 |
-
if title or description:
|
| 180 |
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
| 181 |
-
|
| 182 |
formatted_output = "\n".join(results) if results else "No relevant search results found."
|
| 183 |
-
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 184 |
|
| 185 |
# --- Agent Definition ---
|
|
|
|
| 186 |
class QuestionAnsweringAgent(CodeAgent):
|
| 187 |
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
|
|
|
|
| 188 |
tools = [
|
| 189 |
-
GoogleSearchTool(session=http_session),
|
| 190 |
-
# You can add CalculatorTool here if needed, ensuring it also uses async forward if it performs I/O
|
| 191 |
]
|
|
|
|
| 192 |
|
| 193 |
effective_model = model
|
| 194 |
if effective_model is None:
|
|
|
|
| 195 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 196 |
if not openai_api_key:
|
|
|
|
| 197 |
logger.critical("OPENAI_API_KEY not found. Cannot initialize OpenAIServerModel.")
|
| 198 |
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 199 |
effective_model = OpenAIServerModel(
|
| 200 |
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 201 |
api_key=openai_api_key
|
| 202 |
)
|
|
|
|
| 203 |
|
| 204 |
-
# WORKAROUND for potential smolagents CodeAgent/MultiStepAgent __init__ TypeError
|
| 205 |
-
# This attempts to initialize with arguments known to be accepted by the base MultiStepAgent,
|
| 206 |
-
# and then sets CodeAgent-specific attributes. This is fragile and depends on smolagents internal structure.
|
| 207 |
minimal_super_args = {
|
| 208 |
"model": effective_model,
|
| 209 |
"tools": tools,
|
| 210 |
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
| 211 |
-
# "code_writer": None, # CodeAgent usually creates its own CodeWriter if not provided.
|
| 212 |
-
# If MultiStepAgent expects it, this might be an issue.
|
| 213 |
}
|
|
|
|
| 214 |
try:
|
| 215 |
super().__init__(**minimal_super_args)
|
| 216 |
-
|
| 217 |
|
| 218 |
-
# Explicitly set CodeAgent-specific attributes after the minimal super init.
|
| 219 |
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
|
| 220 |
-
|
| 221 |
|
| 222 |
-
# Attempt to set other CodeAgent/MultiStepAgent parameters if they exist as attributes
|
| 223 |
-
# This is not guaranteed to work if these are properties or handled differently internally.
|
| 224 |
if hasattr(self, 'verbosity_level'):
|
| 225 |
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
|
| 226 |
-
|
| 227 |
else:
|
|
|
|
| 228 |
logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
|
| 229 |
|
| 230 |
if hasattr(self, 'additional_authorized_imports'):
|
| 231 |
-
self.additional_authorized_imports = ["PIL"]
|
| 232 |
-
|
| 233 |
else:
|
|
|
|
| 234 |
logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
|
| 235 |
|
| 236 |
-
# Check if code_writer was initialized by the super call or needs attention
|
| 237 |
if not hasattr(self, 'code_writer') or self.code_writer is None:
|
|
|
|
| 238 |
logger.warning("self.code_writer might not be initialized due to the __init__ workaround. Agent may fail to generate or execute code.")
|
| 239 |
|
| 240 |
except TypeError as e:
|
|
|
|
| 241 |
logger.error(
|
| 242 |
f"WORKAROUND FAILED: Still encountered TypeError during minimal super().__init__ for QuestionAnsweringAgent: {e}. "
|
| 243 |
"This likely means the __init__ signature of smolagents.CodeAgent or its parent MultiStepAgent "
|
| 244 |
"is incompatible with this workaround or has changed.",
|
| 245 |
exc_info=True
|
| 246 |
)
|
| 247 |
-
raise
|
| 248 |
-
except Exception as e:
|
|
|
|
| 249 |
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
|
| 250 |
raise
|
| 251 |
-
|
| 252 |
-
logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID} and tools.")
|
| 253 |
-
|
| 254 |
|
| 255 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
| 256 |
-
"
|
| 257 |
reasoning_trace = "Agent execution started."
|
| 258 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 259 |
try:
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
# but it calls tools that might be async.
|
| 264 |
-
# If self.run itself needs to be awaited (e.g., if CodeAgent is made fully async in future smolagents versions),
|
| 265 |
-
# this would need to change. For now, assuming self.run() orchestrates async tool calls internally
|
| 266 |
-
# and returns a result object or string.
|
| 267 |
-
raw_output_obj = self.run(question_text) # This is a blocking call in current smolagents
|
| 268 |
-
|
| 269 |
-
# Extracting the response string from various possible output structures of self.run()
|
| 270 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 271 |
full_agent_response = str(raw_output_obj.log_string())
|
| 272 |
-
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 273 |
full_agent_response = str(raw_output_obj.text)
|
| 274 |
-
elif isinstance(raw_output_obj, str):
|
| 275 |
full_agent_response = raw_output_obj
|
| 276 |
-
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 277 |
full_agent_response = str(raw_output_obj.result)
|
| 278 |
-
else:
|
| 279 |
full_agent_response = str(raw_output_obj)
|
| 280 |
logger.warning(f"Raw output from agent.run() was of type {type(raw_output_obj)}. Used generic str() conversion.")
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
# Extract the final answer based on the specified template
|
| 286 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 287 |
if match:
|
| 288 |
final_answer_for_submission = match.group(1).strip()
|
| 289 |
-
|
| 290 |
else:
|
| 291 |
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
| 292 |
-
|
|
|
|
| 293 |
|
| 294 |
-
if not final_answer_for_submission:
|
| 295 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
|
|
|
| 296 |
final_answer_for_submission = "Could not determine answer."
|
| 297 |
|
| 298 |
-
except TypeError as te:
|
|
|
|
| 299 |
logger.error(f"TypeError during agent processing, possibly due to __init__ workaround: {str(te)}", exc_info=True)
|
| 300 |
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 301 |
reasoning_trace += f"\nTypeError encountered during processing: {str(te)}"
|
| 302 |
except Exception as e:
|
|
|
|
| 303 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {type(e).__name__} - {str(e)}", exc_info=True)
|
| 304 |
final_answer_for_submission = f"Error in agent processing: {str(e)}"
|
| 305 |
reasoning_trace += f"\nError encountered: {str(e)}"
|
| 306 |
-
|
| 307 |
return final_answer_for_submission, reasoning_trace
|
| 308 |
|
| 309 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
|
|
|
| 310 |
class ChuckAgent:
|
| 311 |
-
"""An adapter class to manage the QuestionAnsweringAgent and its async operations."""
|
| 312 |
def __init__(self):
|
|
|
|
| 313 |
logger.info("ChuckAgent initialization started.")
|
| 314 |
-
# Ensure required API keys are present before initializing the actual agent
|
| 315 |
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
| 316 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 317 |
if missing_vars:
|
| 318 |
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}. Please set them in Space Secrets."
|
|
|
|
| 319 |
logger.critical(error_msg)
|
| 320 |
raise EnvironmentError(error_msg)
|
|
|
|
| 321 |
|
| 322 |
-
|
| 323 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
-
|
| 326 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
|
| 328 |
-
# QuestionAnsweringAgent instantiation is now within the try-except block in run_and_submit_all_evaluation
|
| 329 |
-
# to catch initialization errors (like the smolagents SyntaxError or our workaround TypeError).
|
| 330 |
-
# Here, we just prepare for it.
|
| 331 |
self.agent_instance: Optional[QuestionAnsweringAgent] = None
|
| 332 |
logger.info("ChuckAgent basic initialization complete. Actual QuestionAnsweringAgent will be created on first use.")
|
|
|
|
| 333 |
|
| 334 |
async def _get_or_create_session(self) -> aiohttp.ClientSession:
|
| 335 |
-
"
|
| 336 |
logger.info("Creating aiohttp.ClientSession for ChuckAgent.")
|
| 337 |
return aiohttp.ClientSession()
|
| 338 |
|
| 339 |
def _ensure_agent_initialized(self):
|
| 340 |
-
"
|
| 341 |
if self.agent_instance is None:
|
|
|
|
| 342 |
logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
|
| 343 |
try:
|
| 344 |
-
# Pass the http_session managed by ChuckAgent
|
| 345 |
self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
|
|
|
|
| 346 |
logger.info("QuestionAnsweringAgent initialized successfully.")
|
| 347 |
-
except Exception as e:
|
|
|
|
| 348 |
logger.error(f"Failed to initialize QuestionAnsweringAgent: {e}", exc_info=True)
|
| 349 |
-
# This exception will propagate up and be caught by the caller (run_and_submit_all_evaluation)
|
| 350 |
raise
|
|
|
|
|
|
|
| 351 |
|
| 352 |
|
| 353 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 354 |
-
"
|
| 355 |
-
logger.info(f"ChuckAgent received question (first 50 chars): '{question[:50]}...'")
|
| 356 |
-
|
| 357 |
try:
|
| 358 |
-
self._ensure_agent_initialized()
|
| 359 |
-
if self.agent_instance is None:
|
|
|
|
| 360 |
raise RuntimeError("QuestionAnsweringAgent was not initialized.")
|
| 361 |
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
|
| 366 |
return final_answer, reasoning_trace
|
| 367 |
except Exception as e:
|
| 368 |
error_msg = f"Error running ChuckAgent: {type(e).__name__} - {str(e)}"
|
|
|
|
| 369 |
logger.error(error_msg, exc_info=True)
|
| 370 |
-
# Return a tuple even in case of error, as expected by the caller
|
| 371 |
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
| 372 |
|
| 373 |
-
async def
|
| 374 |
-
"
|
| 375 |
-
logger.info("ChuckAgent shutdown
|
| 376 |
if self.http_session and not self.http_session.closed:
|
| 377 |
await self.http_session.close()
|
|
|
|
| 378 |
logger.info("Closed ChuckAgent's aiohttp.ClientSession.")
|
| 379 |
-
self.http_session = None
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
|
|
|
| 386 |
|
| 387 |
# --- Orchestration Functions ---
|
| 388 |
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 389 |
-
"
|
| 390 |
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
| 391 |
logger.info(f"Fetching questions from: {questions_url}")
|
| 392 |
try:
|
|
@@ -397,116 +455,93 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 397 |
logger.warning(f"Fetched questions empty or invalid format: {questions_data}")
|
| 398 |
raise ValueError("Fetched questions list is empty or not a list.")
|
| 399 |
logger.info(f"Fetched {len(questions_data)} questions.")
|
|
|
|
| 400 |
return questions_data
|
| 401 |
except requests.exceptions.RequestException as e:
|
|
|
|
| 402 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 403 |
raise ConnectionError(f"Error fetching questions: {e}")
|
| 404 |
except requests.exceptions.JSONDecodeError as e:
|
|
|
|
| 405 |
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 406 |
raise ValueError(f"Error decoding server response for questions: {e}")
|
| 407 |
|
| 408 |
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 409 |
-
"
|
| 410 |
answers_payload = []
|
| 411 |
results_log_data = []
|
| 412 |
-
logger.info(f"Running agent on {len(questions_data)} questions...")
|
| 413 |
-
|
| 414 |
for i, item in enumerate(questions_data):
|
| 415 |
task_id = item.get("task_id")
|
| 416 |
question_text = item.get("question")
|
| 417 |
-
|
| 418 |
if not task_id or question_text is None:
|
| 419 |
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 420 |
continue
|
| 421 |
-
|
| 422 |
-
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}, Question: '{question_text[:50]}...'")
|
| 423 |
try:
|
| 424 |
-
model_ans, reasoning = agent(question_text)
|
| 425 |
-
|
| 426 |
payload_item = {"task_id": task_id, "model_answer": model_ans}
|
| 427 |
-
if reasoning:
|
| 428 |
payload_item["reasoning_trace"] = reasoning
|
| 429 |
answers_payload.append(payload_item)
|
| 430 |
-
|
| 431 |
results_log_data.append({
|
| 432 |
-
"Task ID": task_id,
|
| 433 |
-
"
|
| 434 |
-
"Submitted Answer": model_ans,
|
| 435 |
-
"Reasoning Trace": reasoning
|
| 436 |
})
|
| 437 |
except Exception as e:
|
|
|
|
| 438 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 439 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
| 440 |
answers_payload.append({"task_id": task_id, "model_answer": error_answer, "reasoning_trace": str(e)})
|
| 441 |
results_log_data.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
|
| 442 |
-
|
| 443 |
-
if not answers_payload:
|
| 444 |
-
logger.warning("Agent did not produce any answers.")
|
| 445 |
-
# Still return empty lists rather than raising an error here, let the caller decide.
|
| 446 |
return answers_payload, results_log_data
|
| 447 |
|
| 448 |
def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
|
| 449 |
-
"
|
| 450 |
if not answers_payload:
|
| 451 |
logger.warning("No answers to submit.")
|
| 452 |
return "Agent did not produce any answers to submit."
|
| 453 |
-
|
| 454 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 455 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 456 |
-
|
| 457 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}' to {submit_url}...")
|
| 458 |
-
# logger.debug(f"Submission payload: {json.dumps(submission_data, indent=2)}") # Be careful logging full payload if sensitive
|
| 459 |
-
|
| 460 |
try:
|
| 461 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 462 |
response.raise_for_status()
|
| 463 |
result_data = response.json()
|
| 464 |
final_status = (
|
| 465 |
-
f"Submission Successful!\n"
|
| 466 |
-
f"
|
| 467 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 468 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 469 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 470 |
)
|
| 471 |
logger.info(f"Submission successful for user '{username}'. Score: {result_data.get('score', 'N/A')}%")
|
| 472 |
except requests.exceptions.HTTPError as e:
|
| 473 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 474 |
try:
|
| 475 |
-
error_json = e.response.json()
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
error_detail += f" Raw Response: {e.response.text[:500]}" # Log only a snippet of raw response
|
| 479 |
-
final_status = f"Submission Failed: {error_detail}"
|
| 480 |
-
logger.error(final_status)
|
| 481 |
except requests.exceptions.Timeout:
|
| 482 |
-
final_status = "Submission Failed: The request timed out."
|
| 483 |
-
logger.error(final_status)
|
| 484 |
except requests.exceptions.RequestException as e:
|
| 485 |
-
final_status = f"Submission Failed: Network error - {e}"
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
logger.error(final_status, exc_info=True)
|
| 490 |
return final_status
|
| 491 |
|
| 492 |
# --- Gradio Interface and Main Execution Logic ---
|
| 493 |
-
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 494 |
|
|
|
|
| 495 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 496 |
-
"""
|
| 497 |
-
Orchestrates fetching questions, running the agent, submitting answers,
|
| 498 |
-
and handling Gradio interaction.
|
| 499 |
-
The `*args` is present due to a previous Gradio issue with `gr.LoginButton()` potentially sending
|
| 500 |
-
extra arguments. It's safer to keep it to catch them if they reappear.
|
| 501 |
-
"""
|
| 502 |
global GLOBAL_CHUCK_AGENT
|
|
|
|
| 503 |
logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
| 504 |
|
| 505 |
-
# Handle potential inconsistencies with Gradio's profile argument passing
|
| 506 |
effective_profile: Optional[gr.OAuthProfile] = None
|
| 507 |
if isinstance(profile, gr.OAuthProfile):
|
| 508 |
effective_profile = profile
|
| 509 |
-
elif args:
|
| 510 |
logger.warning(f"Profile not directly passed or None. Checking *args: {args}")
|
| 511 |
for arg_val in args:
|
| 512 |
if isinstance(arg_val, gr.OAuthProfile):
|
|
@@ -516,111 +551,129 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 516 |
|
| 517 |
if not effective_profile:
|
| 518 |
logger.warning("User not logged in or profile not correctly passed for evaluation.")
|
|
|
|
| 519 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 520 |
|
| 521 |
username = effective_profile.username
|
| 522 |
logger.info(f"User logged in: {username}")
|
|
|
|
| 523 |
|
| 524 |
-
_, agent_code_url = get_space_id_agent_code_url()
|
| 525 |
-
results_log_data: List[Dict[str, Any]] = []
|
| 526 |
|
| 527 |
try:
|
| 528 |
-
|
| 529 |
if GLOBAL_CHUCK_AGENT is None:
|
|
|
|
| 530 |
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance.")
|
| 531 |
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
|
|
|
|
|
|
|
|
|
| 532 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 533 |
|
| 534 |
-
|
| 535 |
-
# This call might raise an exception if QuestionAnsweringAgent init fails (e.g., smolagents issue, API key issue)
|
| 536 |
agent_instance._ensure_agent_initialized()
|
|
|
|
| 537 |
|
| 538 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 539 |
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
|
| 540 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 541 |
|
| 542 |
-
except EnvironmentError as e:
|
|
|
|
| 543 |
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
|
| 544 |
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
|
| 545 |
-
except (ConnectionError, ValueError) as e:
|
|
|
|
| 546 |
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
|
| 547 |
submission_status = str(e)
|
| 548 |
-
except RuntimeError as e:
|
|
|
|
| 549 |
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
|
| 550 |
submission_status = f"Runtime Error: {e}"
|
| 551 |
-
except Exception as e:
|
|
|
|
| 552 |
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
|
| 553 |
submission_status = f"An unexpected error occurred: {e}"
|
| 554 |
-
|
| 555 |
-
if not results_log_data: # Ensure it's at least an empty list for DataFrame
|
| 556 |
results_log_data = [{"Task ID": "N/A", "Question": "N/A", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 557 |
|
| 558 |
-
|
| 559 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
|
|
|
| 560 |
return submission_status, results_df
|
| 561 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
* **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
|
| 586 |
-
* **Gradio Version**: This app is tested with `gradio>=4.0`. Check `requirements.txt`.
|
| 587 |
-
* **`smolagents` Issue**: The primary issue you encountered (`SyntaxError: f-string: unmatched '('`) is likely within the `smolagents` library itself. Please ensure you have tried upgrading or reinstalling it (`pip install --upgrade smolagents`). A workaround for a *different* potential `TypeError` during `CodeAgent` initialization is active in this script but won't fix the `SyntaxError`.
|
| 588 |
-
---
|
| 589 |
-
**Disclaimer**: Processing all questions can take some time. The interface will update once the entire process is complete. For a production system, consider asynchronous operations or background tasks for a smoother user experience.
|
| 590 |
-
"""
|
| 591 |
-
)
|
| 592 |
-
|
| 593 |
-
login_button = gr.LoginButton()
|
| 594 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 595 |
-
|
| 596 |
-
with gr.Column():
|
| 597 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
|
| 598 |
-
# FIX: Removed max_rows from gr.DataFrame
|
| 599 |
-
results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True)
|
| 600 |
|
| 601 |
-
run_button.click(
|
| 602 |
-
fn=run_and_submit_all_evaluation,
|
| 603 |
-
inputs=[login_button],
|
| 604 |
-
outputs=[status_output, results_table]
|
| 605 |
-
)
|
| 606 |
|
| 607 |
# --- Application Startup & Shutdown Handling ---
|
| 608 |
if __name__ == "__main__":
|
| 609 |
-
print("\n" + "="*15 + " Application Startup " + "="*15)
|
| 610 |
|
| 611 |
-
# Log essential startup info
|
| 612 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 613 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 614 |
|
| 615 |
-
print(f"Python Version: {'.'.join(map(str, asyncio.sys.version_info[:3]))}")
|
| 616 |
-
print(f"Gradio Version: {gr.__version__}")
|
| 617 |
-
# Consider logging smolagents version if import is successful
|
| 618 |
try:
|
| 619 |
import smolagents
|
| 620 |
print(f"smolagents Version: {smolagents.__version__ if hasattr(smolagents, '__version__') else 'unknown'}")
|
| 621 |
except ImportError:
|
| 622 |
-
print("smolagents could not be imported (version unknown). This is expected if the
|
| 623 |
-
|
| 624 |
|
| 625 |
if space_host_startup:
|
| 626 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -641,32 +694,32 @@ if __name__ == "__main__":
|
|
| 641 |
|
| 642 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 643 |
print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
|
| 644 |
-
print("If you encounter
|
| 645 |
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
if loop_to_use:
|
| 660 |
try:
|
| 661 |
-
#
|
| 662 |
-
|
| 663 |
-
loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
|
| 664 |
logger.info("ChuckAgent shutdown process completed.")
|
| 665 |
except Exception as e_shutdown:
|
|
|
|
| 666 |
logger.error(f"Error during ChuckAgent final shutdown: {e_shutdown}", exc_info=True)
|
| 667 |
else:
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
print("="*15 + " Application Shutdown " + "="*15)
|
| 672 |
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
print("DEBUG: app.py execution started (top of file)")
|
| 2 |
import os
|
| 3 |
+
print("DEBUG: os imported")
|
| 4 |
import gradio as gr
|
| 5 |
+
print("DEBUG: gradio imported")
|
| 6 |
import requests
|
| 7 |
+
print("DEBUG: requests imported")
|
| 8 |
import pandas as pd
|
| 9 |
+
print("DEBUG: pandas imported")
|
| 10 |
import asyncio
|
| 11 |
+
print("DEBUG: asyncio imported")
|
| 12 |
import re
|
| 13 |
+
print("DEBUG: re imported")
|
| 14 |
import json
|
| 15 |
+
print("DEBUG: json imported")
|
| 16 |
import logging
|
| 17 |
+
print("DEBUG: logging imported")
|
| 18 |
import operator # Used by CalculatorTool (if you re-add it)
|
| 19 |
+
print("DEBUG: operator imported")
|
| 20 |
import aiohttp
|
| 21 |
+
print("DEBUG: aiohttp imported")
|
| 22 |
from typing import Optional, Dict, Any, List, Tuple # Added Tuple
|
| 23 |
+
print("DEBUG: typing imported")
|
| 24 |
|
| 25 |
# Import necessary components from smolagents
|
| 26 |
try:
|
| 27 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 28 |
+
print("DEBUG: smolagents components (CodeAgent, Tool, OpenAIServerModel) imported successfully.")
|
| 29 |
except ImportError as e: # Catch the specific error for better logging
|
| 30 |
+
print(f"DEBUG: Failed to import smolagents. Error: {e}")
|
| 31 |
logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
|
| 32 |
# Dummy classes for script parsing if smolagents is not installed or fails to import
|
| 33 |
# This allows the rest of the script to be parsed, but it won't run correctly.
|
| 34 |
class CodeAgent:
|
| 35 |
def __init__(self, *args, **kwargs):
|
| 36 |
+
print("DEBUG: Dummy CodeAgent initialized because smolagents failed to import.")
|
| 37 |
logging.error("Dummy CodeAgent initialized because smolagents failed to import.")
|
| 38 |
def run(self, *args, **kwargs):
|
| 39 |
+
print("DEBUG: Dummy CodeAgent run called.")
|
| 40 |
logging.error("Dummy CodeAgent run called.")
|
| 41 |
return "Error: smolagents not loaded."
|
| 42 |
pass
|
| 43 |
|
| 44 |
class Tool:
|
| 45 |
def __init__(self, *args, **kwargs):
|
| 46 |
+
print("DEBUG: Dummy Tool initialized because smolagents failed to import.")
|
| 47 |
logging.error("Dummy Tool initialized because smolagents failed to import.")
|
| 48 |
pass
|
| 49 |
|
| 50 |
class OpenAIServerModel:
|
| 51 |
def __init__(self, *args, **kwargs):
|
| 52 |
+
print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 53 |
logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 54 |
pass
|
| 55 |
|
| 56 |
from datetime import datetime
|
| 57 |
+
print("DEBUG: datetime imported")
|
| 58 |
|
| 59 |
# --- Configuration ---
|
| 60 |
+
print("DEBUG: Defining AppConfig.")
|
| 61 |
class AppConfig:
|
| 62 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 63 |
QUESTIONS_URL_PATH = "/questions"
|
|
|
|
| 103 |
"""
|
| 104 |
|
| 105 |
CONFIG = AppConfig()
|
| 106 |
+
print("DEBUG: AppConfig defined and CONFIG instance created.")
|
| 107 |
|
| 108 |
# --- Logging Setup ---
|
| 109 |
logging.basicConfig(
|
| 110 |
level=logging.INFO,
|
| 111 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 112 |
logger = logging.getLogger(__name__)
|
| 113 |
+
print("DEBUG: Logging configured.")
|
| 114 |
|
| 115 |
# --- Utility Functions ---
|
| 116 |
def ensure_dir_exists(directory_path: str):
|
| 117 |
"""Creates a directory if it doesn't already exist."""
|
| 118 |
+
print(f"DEBUG: Ensuring directory exists: {directory_path}")
|
| 119 |
os.makedirs(directory_path, exist_ok=True)
|
| 120 |
|
| 121 |
ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
|
|
|
| 127 |
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 128 |
else:
|
| 129 |
agent_code_url = "Agent code URL not found (SPACE_ID not set)"
|
| 130 |
+
# print(f"DEBUG: get_space_id_agent_code_url() -> space_id: {space_id}, url: {agent_code_url}")
|
| 131 |
return space_id, agent_code_url
|
| 132 |
|
| 133 |
+
print("DEBUG: Utility functions defined.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
# --- Tool Definitions ---
|
| 136 |
+
print("DEBUG: Defining GoogleSearchTool.")
|
| 137 |
class GoogleSearchTool(Tool):
|
| 138 |
name = "web_search" # This is the name the LLM will use to call the tool
|
| 139 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 140 |
inputs = {
|
| 141 |
"query": {"type": "string", "description": "The search query to execute."},
|
| 142 |
+
"provider": {
|
| 143 |
+
"type": "string",
|
| 144 |
+
"description": "The search provider. MUST be 'serpapi'.",
|
| 145 |
+
"default": "serpapi",
|
| 146 |
+
"nullable": True # <<< FIX: Added nullable: True
|
| 147 |
+
}
|
| 148 |
}
|
| 149 |
output_type = "string"
|
| 150 |
is_async = True # Important for smolagents to know this tool's forward method is async
|
|
|
|
| 152 |
def __init__(self, session: aiohttp.ClientSession):
|
| 153 |
super().__init__()
|
| 154 |
self._session = session # Use the session passed from ChuckAgent
|
| 155 |
+
print("DEBUG: GoogleSearchTool instance created.")
|
| 156 |
|
| 157 |
async def forward(self, query: str, provider: str = "serpapi") -> str:
|
| 158 |
+
print(f"DEBUG: GoogleSearchTool.forward called with query: '{query}', provider: '{provider}'")
|
| 159 |
+
# The 'provider' parameter in the 'inputs' dictionary now has "default": "serpapi" and "nullable": True.
|
| 160 |
+
# smol-agents should use the default if the LLM doesn't specify 'provider'.
|
| 161 |
+
# If the LLM *does* specify 'provider', it should be "serpapi" as per the system prompt.
|
| 162 |
+
# This explicit check remains as a safeguard.
|
| 163 |
+
if provider != "serpapi":
|
| 164 |
+
logger.warning(f"GoogleSearchTool called with an unexpected provider: '{provider}'. The system prompt and tool definition instruct the LLM to use 'serpapi'.")
|
| 165 |
+
return "Error: Invalid search provider. Only 'serpapi' is supported for the web_search tool as per current agent configuration."
|
| 166 |
|
|
|
|
| 167 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 168 |
if not serper_api_key:
|
| 169 |
logger.error("SERPER_API_KEY not found in environment variables.")
|
| 170 |
+
print("DEBUG: ERROR - SERPER_API_KEY not found.")
|
| 171 |
return "Error: Serper API key not found in environment."
|
| 172 |
|
| 173 |
url = "https://google.serper.dev/search"
|
|
|
|
| 175 |
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
|
| 176 |
|
| 177 |
try:
|
|
|
|
| 178 |
async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
|
| 179 |
+
response.raise_for_status()
|
| 180 |
data = await response.json()
|
| 181 |
+
print(f"DEBUG: GoogleSearchTool.forward received data for query '{query}'.")
|
| 182 |
return self._format_results(data)
|
| 183 |
except asyncio.TimeoutError:
|
| 184 |
logger.error(f"Timeout performing search for '{query}'")
|
| 185 |
+
print(f"DEBUG: ERROR - Timeout in GoogleSearchTool for query '{query}'.")
|
| 186 |
return f"Error: Timeout during web search for '{query}'."
|
| 187 |
except aiohttp.ClientResponseError as e:
|
| 188 |
logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
|
| 189 |
+
print(f"DEBUG: ERROR - HTTP Error {e.status} in GoogleSearchTool for query '{query}'.")
|
| 190 |
return f"Error performing search (HTTP {e.status}): {e.message}"
|
| 191 |
+
except aiohttp.ClientError as e:
|
| 192 |
logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
|
| 193 |
+
print(f"DEBUG: ERROR - ClientError in GoogleSearchTool for query '{query}': {str(e)}.")
|
| 194 |
return f"Error performing search (client error): {str(e)}"
|
| 195 |
except Exception as e:
|
| 196 |
logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
|
| 197 |
+
print(f"DEBUG: ERROR - Unexpected error in GoogleSearchTool for query '{query}': {str(e)}.")
|
| 198 |
return f"Error performing search: An unexpected error occurred."
|
| 199 |
|
| 200 |
def _format_results(self, data: Dict[str, Any]) -> str:
|
|
|
|
| 201 |
results = []
|
| 202 |
if 'organic' in data and data['organic']:
|
| 203 |
for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
|
| 204 |
title = result.get('title', 'N/A')
|
| 205 |
snippet = result.get('snippet', 'N/A')
|
|
|
|
| 206 |
results.append(f"Title: {title}\nSnippet: {snippet}\n---")
|
| 207 |
+
if not results and 'knowledgeGraph' in data:
|
|
|
|
| 208 |
kg = data['knowledgeGraph']
|
| 209 |
title = kg.get('title', '')
|
| 210 |
description = kg.get('description', '')
|
| 211 |
+
if title or description:
|
| 212 |
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
|
|
|
| 213 |
formatted_output = "\n".join(results) if results else "No relevant search results found."
|
| 214 |
+
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 215 |
|
| 216 |
# --- Agent Definition ---
|
| 217 |
+
print("DEBUG: Defining QuestionAnsweringAgent.")
|
| 218 |
class QuestionAnsweringAgent(CodeAgent):
|
| 219 |
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
|
| 220 |
+
print(f"DEBUG: QuestionAnsweringAgent.__init__ called. http_session: {http_session}, model: {model}")
|
| 221 |
tools = [
|
| 222 |
+
GoogleSearchTool(session=http_session),
|
|
|
|
| 223 |
]
|
| 224 |
+
print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
|
| 225 |
|
| 226 |
effective_model = model
|
| 227 |
if effective_model is None:
|
| 228 |
+
print("DEBUG: QuestionAnsweringAgent effective_model is None, creating default OpenAIServerModel.")
|
| 229 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 230 |
if not openai_api_key:
|
| 231 |
+
print("DEBUG: ERROR - OPENAI_API_KEY not found for QuestionAnsweringAgent.")
|
| 232 |
logger.critical("OPENAI_API_KEY not found. Cannot initialize OpenAIServerModel.")
|
| 233 |
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 234 |
effective_model = OpenAIServerModel(
|
| 235 |
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 236 |
api_key=openai_api_key
|
| 237 |
)
|
| 238 |
+
print(f"DEBUG: QuestionAnsweringAgent default OpenAIServerModel created with model_id: {CONFIG.OPENAI_MODEL_ID}")
|
| 239 |
|
|
|
|
|
|
|
|
|
|
| 240 |
minimal_super_args = {
|
| 241 |
"model": effective_model,
|
| 242 |
"tools": tools,
|
| 243 |
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
|
|
|
|
|
|
| 244 |
}
|
| 245 |
+
print(f"DEBUG: QuestionAnsweringAgent minimal_super_args for super().__init__: {minimal_super_args}")
|
| 246 |
try:
|
| 247 |
super().__init__(**minimal_super_args)
|
| 248 |
+
print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
|
| 249 |
|
|
|
|
| 250 |
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
|
| 251 |
+
print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
|
| 252 |
|
|
|
|
|
|
|
| 253 |
if hasattr(self, 'verbosity_level'):
|
| 254 |
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
|
| 255 |
+
print(f"DEBUG: QuestionAnsweringAgent set self.verbosity_level to: {self.verbosity_level}")
|
| 256 |
else:
|
| 257 |
+
print("DEBUG: WARNING - QuestionAnsweringAgent could not set 'verbosity_level' as an attribute after init.")
|
| 258 |
logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
|
| 259 |
|
| 260 |
if hasattr(self, 'additional_authorized_imports'):
|
| 261 |
+
self.additional_authorized_imports = ["PIL"]
|
| 262 |
+
print(f"DEBUG: QuestionAnsweringAgent set self.additional_authorized_imports to: {self.additional_authorized_imports}")
|
| 263 |
else:
|
| 264 |
+
print("DEBUG: WARNING - QuestionAnsweringAgent could not set 'additional_authorized_imports' as an attribute after init.")
|
| 265 |
logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
|
| 266 |
|
|
|
|
| 267 |
if not hasattr(self, 'code_writer') or self.code_writer is None:
|
| 268 |
+
print("DEBUG: WARNING - QuestionAnsweringAgent self.code_writer might not be initialized due to the __init__ workaround.")
|
| 269 |
logger.warning("self.code_writer might not be initialized due to the __init__ workaround. Agent may fail to generate or execute code.")
|
| 270 |
|
| 271 |
except TypeError as e:
|
| 272 |
+
print(f"DEBUG: ERROR - QuestionAnsweringAgent WORKAROUND FAILED: TypeError during minimal super().__init__: {e}")
|
| 273 |
logger.error(
|
| 274 |
f"WORKAROUND FAILED: Still encountered TypeError during minimal super().__init__ for QuestionAnsweringAgent: {e}. "
|
| 275 |
"This likely means the __init__ signature of smolagents.CodeAgent or its parent MultiStepAgent "
|
| 276 |
"is incompatible with this workaround or has changed.",
|
| 277 |
exc_info=True
|
| 278 |
)
|
| 279 |
+
raise
|
| 280 |
+
except Exception as e: # This will catch other exceptions like the AssertionError from smolagents
|
| 281 |
+
print(f"DEBUG: ERROR - QuestionAnsweringAgent Unexpected error during __init__ (possibly from tool validation): {type(e).__name__} - {e}")
|
| 282 |
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
|
| 283 |
raise
|
| 284 |
+
print(f"DEBUG: QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID} and tools.")
|
|
|
|
|
|
|
| 285 |
|
| 286 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
| 287 |
+
print(f"DEBUG: QuestionAnsweringAgent.process_question called for: '{question_text[:100]}...'")
|
| 288 |
reasoning_trace = "Agent execution started."
|
| 289 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 290 |
try:
|
| 291 |
+
raw_output_obj = self.run(question_text)
|
| 292 |
+
print(f"DEBUG: QuestionAnsweringAgent.run() output type: {type(raw_output_obj)}")
|
| 293 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 295 |
full_agent_response = str(raw_output_obj.log_string())
|
| 296 |
+
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 297 |
full_agent_response = str(raw_output_obj.text)
|
| 298 |
+
elif isinstance(raw_output_obj, str):
|
| 299 |
full_agent_response = raw_output_obj
|
| 300 |
+
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 301 |
full_agent_response = str(raw_output_obj.result)
|
| 302 |
+
else:
|
| 303 |
full_agent_response = str(raw_output_obj)
|
| 304 |
logger.warning(f"Raw output from agent.run() was of type {type(raw_output_obj)}. Used generic str() conversion.")
|
| 305 |
+
|
| 306 |
+
print(f"DEBUG: QuestionAnsweringAgent full_agent_response (first 200 chars): {full_agent_response[:200]}")
|
| 307 |
+
reasoning_trace = full_agent_response
|
|
|
|
|
|
|
| 308 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 309 |
if match:
|
| 310 |
final_answer_for_submission = match.group(1).strip()
|
| 311 |
+
print(f"DEBUG: QuestionAnsweringAgent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 312 |
else:
|
| 313 |
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
| 314 |
+
print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's response.")
|
| 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.")
|
| 319 |
+
print("DEBUG: WARNING - QuestionAnsweringAgent extracted final answer is empty.")
|
| 320 |
final_answer_for_submission = "Could not determine answer."
|
| 321 |
|
| 322 |
+
except TypeError as te:
|
| 323 |
+
print(f"DEBUG: ERROR - TypeError in QuestionAnsweringAgent.process_question: {str(te)}")
|
| 324 |
logger.error(f"TypeError during agent processing, possibly due to __init__ workaround: {str(te)}", exc_info=True)
|
| 325 |
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 326 |
reasoning_trace += f"\nTypeError encountered during processing: {str(te)}"
|
| 327 |
except Exception as e:
|
| 328 |
+
print(f"DEBUG: ERROR - Exception in QuestionAnsweringAgent.process_question: {type(e).__name__} - {str(e)}")
|
| 329 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {type(e).__name__} - {str(e)}", exc_info=True)
|
| 330 |
final_answer_for_submission = f"Error in agent processing: {str(e)}"
|
| 331 |
reasoning_trace += f"\nError encountered: {str(e)}"
|
|
|
|
| 332 |
return final_answer_for_submission, reasoning_trace
|
| 333 |
|
| 334 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 335 |
+
print("DEBUG: Defining ChuckAgent.")
|
| 336 |
class ChuckAgent:
|
|
|
|
| 337 |
def __init__(self):
|
| 338 |
+
print("DEBUG: ChuckAgent.__init__ called.")
|
| 339 |
logger.info("ChuckAgent initialization started.")
|
|
|
|
| 340 |
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
| 341 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 342 |
if missing_vars:
|
| 343 |
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}. Please set them in Space Secrets."
|
| 344 |
+
print(f"DEBUG: ERROR - ChuckAgent missing env vars: {error_msg}")
|
| 345 |
logger.critical(error_msg)
|
| 346 |
raise EnvironmentError(error_msg)
|
| 347 |
+
print("DEBUG: ChuckAgent environment variables checked.")
|
| 348 |
|
| 349 |
+
try:
|
| 350 |
+
# Try to get the currently running event loop (e.g., from Gradio/Uvicorn)
|
| 351 |
+
self.loop = asyncio.get_running_loop()
|
| 352 |
+
print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
|
| 353 |
+
except RuntimeError: # No current event loop.
|
| 354 |
+
# This case should be less common if Gradio is running, but as a fallback:
|
| 355 |
+
print("DEBUG: ChuckAgent - No current running event loop, creating a new one for this thread.")
|
| 356 |
+
self.loop = asyncio.new_event_loop()
|
| 357 |
+
asyncio.set_event_loop(self.loop) # Set it for the current OS thread.
|
| 358 |
+
|
| 359 |
+
print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
|
| 360 |
|
| 361 |
+
if self.loop.is_running():
|
| 362 |
+
self.http_session = asyncio.run_coroutine_threadsafe(self._get_or_create_session(), self.loop).result(timeout=10)
|
| 363 |
+
else: # If loop isn't running (e.g. new_event_loop that wasn't started), run it to create session
|
| 364 |
+
self.http_session = self.loop.run_until_complete(self._get_or_create_session())
|
| 365 |
+
|
| 366 |
+
print(f"DEBUG: ChuckAgent http_session created: {self.http_session}")
|
| 367 |
|
|
|
|
|
|
|
|
|
|
| 368 |
self.agent_instance: Optional[QuestionAnsweringAgent] = None
|
| 369 |
logger.info("ChuckAgent basic initialization complete. Actual QuestionAnsweringAgent will be created on first use.")
|
| 370 |
+
print("DEBUG: ChuckAgent basic initialization complete.")
|
| 371 |
|
| 372 |
async def _get_or_create_session(self) -> aiohttp.ClientSession:
|
| 373 |
+
print("DEBUG: ChuckAgent._get_or_create_session called.")
|
| 374 |
logger.info("Creating aiohttp.ClientSession for ChuckAgent.")
|
| 375 |
return aiohttp.ClientSession()
|
| 376 |
|
| 377 |
def _ensure_agent_initialized(self):
|
| 378 |
+
print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
|
| 379 |
if self.agent_instance is None:
|
| 380 |
+
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
|
| 381 |
logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
|
| 382 |
try:
|
|
|
|
| 383 |
self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
|
| 384 |
+
print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
|
| 385 |
logger.info("QuestionAnsweringAgent initialized successfully.")
|
| 386 |
+
except Exception as e:
|
| 387 |
+
print(f"DEBUG: ERROR - ChuckAgent failed to initialize QuestionAnsweringAgent: {type(e).__name__} - {e}")
|
| 388 |
logger.error(f"Failed to initialize QuestionAnsweringAgent: {e}", exc_info=True)
|
|
|
|
| 389 |
raise
|
| 390 |
+
else:
|
| 391 |
+
print("DEBUG: ChuckAgent - QuestionAnsweringAgent already initialized.")
|
| 392 |
|
| 393 |
|
| 394 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 395 |
+
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...'")
|
|
|
|
|
|
|
| 396 |
try:
|
| 397 |
+
self._ensure_agent_initialized()
|
| 398 |
+
if self.agent_instance is None:
|
| 399 |
+
print("DEBUG: ERROR - ChuckAgent.__call__ QuestionAnsweringAgent was not initialized.")
|
| 400 |
raise RuntimeError("QuestionAnsweringAgent was not initialized.")
|
| 401 |
|
| 402 |
+
print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
|
| 403 |
+
if not self.loop.is_running():
|
| 404 |
+
print(f"DEBUG: WARNING - ChuckAgent event loop {self.loop} is not running. Attempting to run process_question directly.")
|
| 405 |
+
final_answer, reasoning_trace = self.loop.run_until_complete(self.agent_instance.process_question(question))
|
| 406 |
+
else:
|
| 407 |
+
future = asyncio.run_coroutine_threadsafe(self.agent_instance.process_question(question), self.loop)
|
| 408 |
+
print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
|
| 409 |
+
final_answer, reasoning_trace = future.result(timeout=180) # Increased timeout
|
| 410 |
+
|
| 411 |
+
print(f"DEBUG: ChuckAgent future.result() obtained for question: '{question[:50]}...'. Answer: '{final_answer[:50]}...'")
|
| 412 |
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
|
| 413 |
return final_answer, reasoning_trace
|
| 414 |
except Exception as e:
|
| 415 |
error_msg = f"Error running ChuckAgent: {type(e).__name__} - {str(e)}"
|
| 416 |
+
print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
|
| 417 |
logger.error(error_msg, exc_info=True)
|
|
|
|
| 418 |
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
| 419 |
|
| 420 |
+
async def shutdown_async(self):
|
| 421 |
+
print("DEBUG: ChuckAgent.shutdown_async called.")
|
| 422 |
+
logger.info("ChuckAgent async shutdown initiated.")
|
| 423 |
if self.http_session and not self.http_session.closed:
|
| 424 |
await self.http_session.close()
|
| 425 |
+
print("DEBUG: ChuckAgent closed its aiohttp.ClientSession during async shutdown.")
|
| 426 |
logger.info("Closed ChuckAgent's aiohttp.ClientSession.")
|
| 427 |
+
self.http_session = None
|
| 428 |
+
logger.info("ChuckAgent async shutdown complete.")
|
| 429 |
+
print("DEBUG: ChuckAgent async shutdown complete.")
|
| 430 |
+
|
| 431 |
+
def close(self):
|
| 432 |
+
print("DEBUG: ChuckAgent.close called.")
|
| 433 |
+
if self.loop and self.loop.is_running() and self.http_session:
|
| 434 |
+
print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
|
| 435 |
+
asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop).result(timeout=10)
|
| 436 |
+
elif self.loop and not self.loop.is_running() and self.http_session :
|
| 437 |
+
print("DEBUG: ChuckAgent.close - loop is not running, using run_until_complete for shutdown_async.")
|
| 438 |
+
self.loop.run_until_complete(self.shutdown_async())
|
| 439 |
+
else:
|
| 440 |
+
print("DEBUG: ChuckAgent.close - No running loop or http_session to close.")
|
| 441 |
+
print("DEBUG: ChuckAgent.close finished.")
|
| 442 |
|
| 443 |
+
print("DEBUG: ChuckAgent class defined.")
|
| 444 |
|
| 445 |
# --- Orchestration Functions ---
|
| 446 |
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 447 |
+
print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
|
| 448 |
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
| 449 |
logger.info(f"Fetching questions from: {questions_url}")
|
| 450 |
try:
|
|
|
|
| 455 |
logger.warning(f"Fetched questions empty or invalid format: {questions_data}")
|
| 456 |
raise ValueError("Fetched questions list is empty or not a list.")
|
| 457 |
logger.info(f"Fetched {len(questions_data)} questions.")
|
| 458 |
+
print(f"DEBUG: Fetched {len(questions_data)} questions.")
|
| 459 |
return questions_data
|
| 460 |
except requests.exceptions.RequestException as e:
|
| 461 |
+
print(f"DEBUG: ERROR - Error fetching questions: {e}")
|
| 462 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 463 |
raise ConnectionError(f"Error fetching questions: {e}")
|
| 464 |
except requests.exceptions.JSONDecodeError as e:
|
| 465 |
+
print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
|
| 466 |
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 467 |
raise ValueError(f"Error decoding server response for questions: {e}")
|
| 468 |
|
| 469 |
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 470 |
+
print(f"DEBUG: process_all_questions called with {len(questions_data)} questions.")
|
| 471 |
answers_payload = []
|
| 472 |
results_log_data = []
|
|
|
|
|
|
|
| 473 |
for i, item in enumerate(questions_data):
|
| 474 |
task_id = item.get("task_id")
|
| 475 |
question_text = item.get("question")
|
|
|
|
| 476 |
if not task_id or question_text is None:
|
| 477 |
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 478 |
continue
|
| 479 |
+
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
|
|
|
| 480 |
try:
|
| 481 |
+
model_ans, reasoning = agent(question_text)
|
|
|
|
| 482 |
payload_item = {"task_id": task_id, "model_answer": model_ans}
|
| 483 |
+
if reasoning:
|
| 484 |
payload_item["reasoning_trace"] = reasoning
|
| 485 |
answers_payload.append(payload_item)
|
|
|
|
| 486 |
results_log_data.append({
|
| 487 |
+
"Task ID": task_id, "Question": question_text,
|
| 488 |
+
"Submitted Answer": model_ans, "Reasoning Trace": reasoning
|
|
|
|
|
|
|
| 489 |
})
|
| 490 |
except Exception as e:
|
| 491 |
+
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
|
| 492 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 493 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
| 494 |
answers_payload.append({"task_id": task_id, "model_answer": error_answer, "reasoning_trace": str(e)})
|
| 495 |
results_log_data.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
|
| 496 |
+
print(f"DEBUG: process_all_questions finished. Produced {len(answers_payload)} answers.")
|
|
|
|
|
|
|
|
|
|
| 497 |
return answers_payload, results_log_data
|
| 498 |
|
| 499 |
def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
|
| 500 |
+
print(f"DEBUG: submit_answers called for user '{username}' with {len(answers_payload)} answers.")
|
| 501 |
if not answers_payload:
|
| 502 |
logger.warning("No answers to submit.")
|
| 503 |
return "Agent did not produce any answers to submit."
|
|
|
|
| 504 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 505 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
|
|
|
| 506 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}' to {submit_url}...")
|
|
|
|
|
|
|
| 507 |
try:
|
| 508 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 509 |
response.raise_for_status()
|
| 510 |
result_data = response.json()
|
| 511 |
final_status = (
|
| 512 |
+
f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
|
| 513 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% ({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
|
|
|
|
|
|
| 514 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 515 |
)
|
| 516 |
logger.info(f"Submission successful for user '{username}'. Score: {result_data.get('score', 'N/A')}%")
|
| 517 |
except requests.exceptions.HTTPError as e:
|
| 518 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 519 |
try:
|
| 520 |
+
error_json = e.response.json(); error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 521 |
+
except requests.exceptions.JSONDecodeError: error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 522 |
+
final_status = f"Submission Failed: {error_detail}"; logger.error(final_status)
|
|
|
|
|
|
|
|
|
|
| 523 |
except requests.exceptions.Timeout:
|
| 524 |
+
final_status = "Submission Failed: The request timed out."; logger.error(final_status)
|
|
|
|
| 525 |
except requests.exceptions.RequestException as e:
|
| 526 |
+
final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
|
| 527 |
+
except Exception as e:
|
| 528 |
+
final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
|
| 529 |
+
print(f"DEBUG: submit_answers final_status: {final_status}")
|
|
|
|
| 530 |
return final_status
|
| 531 |
|
| 532 |
# --- Gradio Interface and Main Execution Logic ---
|
| 533 |
+
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 534 |
|
| 535 |
+
print("DEBUG: Defining run_and_submit_all_evaluation function.")
|
| 536 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
global GLOBAL_CHUCK_AGENT
|
| 538 |
+
print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
| 539 |
logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
| 540 |
|
|
|
|
| 541 |
effective_profile: Optional[gr.OAuthProfile] = None
|
| 542 |
if isinstance(profile, gr.OAuthProfile):
|
| 543 |
effective_profile = profile
|
| 544 |
+
elif args:
|
| 545 |
logger.warning(f"Profile not directly passed or None. Checking *args: {args}")
|
| 546 |
for arg_val in args:
|
| 547 |
if isinstance(arg_val, gr.OAuthProfile):
|
|
|
|
| 551 |
|
| 552 |
if not effective_profile:
|
| 553 |
logger.warning("User not logged in or profile not correctly passed for evaluation.")
|
| 554 |
+
print("DEBUG: ERROR - User not logged in or profile not correctly passed for evaluation.")
|
| 555 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 556 |
|
| 557 |
username = effective_profile.username
|
| 558 |
logger.info(f"User logged in: {username}")
|
| 559 |
+
print(f"DEBUG: User logged in: {username}")
|
| 560 |
|
| 561 |
+
_, agent_code_url = get_space_id_agent_code_url()
|
| 562 |
+
results_log_data: List[Dict[str, Any]] = []
|
| 563 |
|
| 564 |
try:
|
| 565 |
+
print("DEBUG: run_and_submit_all_evaluation - Attempting to initialize/get GLOBAL_CHUCK_AGENT.")
|
| 566 |
if GLOBAL_CHUCK_AGENT is None:
|
| 567 |
+
print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance.")
|
| 568 |
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance.")
|
| 569 |
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 570 |
+
print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
|
| 571 |
+
else:
|
| 572 |
+
print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
|
| 573 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 574 |
|
| 575 |
+
print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
|
|
|
|
| 576 |
agent_instance._ensure_agent_initialized()
|
| 577 |
+
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
| 578 |
|
| 579 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 580 |
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
|
| 581 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 582 |
|
| 583 |
+
except EnvironmentError as e:
|
| 584 |
+
print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
|
| 585 |
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
|
| 586 |
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
|
| 587 |
+
except (ConnectionError, ValueError) as e:
|
| 588 |
+
print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
|
| 589 |
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
|
| 590 |
submission_status = str(e)
|
| 591 |
+
except RuntimeError as e:
|
| 592 |
+
print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
|
| 593 |
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
|
| 594 |
submission_status = f"Runtime Error: {e}"
|
| 595 |
+
except Exception as e:
|
| 596 |
+
print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
|
| 597 |
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
|
| 598 |
submission_status = f"An unexpected error occurred: {e}"
|
| 599 |
+
if not results_log_data:
|
|
|
|
| 600 |
results_log_data = [{"Task ID": "N/A", "Question": "N/A", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 601 |
|
|
|
|
| 602 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 603 |
+
print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
|
| 604 |
return submission_status, results_df
|
| 605 |
|
| 606 |
+
print("DEBUG: Building Gradio interface.")
|
| 607 |
+
try:
|
| 608 |
+
with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
|
| 609 |
+
print("DEBUG: gr.Blocks context entered.")
|
| 610 |
+
gr.Markdown("# Chuck's Agent Evaluation Runner")
|
| 611 |
+
gr.Markdown(
|
| 612 |
+
"""
|
| 613 |
+
**Instructions:**
|
| 614 |
+
1. This interface allows you to evaluate your AI agent against a predefined set of questions.
|
| 615 |
+
2. **Log in** to your Hugging Face account using the button below. Your HF username is used for submitting results.
|
| 616 |
+
3. Click '**Run Evaluation & Submit All Answers**'. This will:
|
| 617 |
+
a. Fetch questions from the evaluation server.
|
| 618 |
+
b. Run your configured agent (defined in `app.py`) on each question.
|
| 619 |
+
c. Submit the answers back to the server.
|
| 620 |
+
d. Display the overall status and a table of questions, your agent's answers, and reasoning.
|
| 621 |
+
"""
|
| 622 |
+
)
|
| 623 |
+
gr.Markdown(
|
| 624 |
+
f"""
|
| 625 |
+
---
|
| 626 |
+
**Technical Notes & Configuration:**
|
| 627 |
+
* **Agent Backend**: `smolagents` framework.
|
| 628 |
+
* **OpenAI Model**: `{CONFIG.OPENAI_MODEL_ID}`.
|
| 629 |
+
* **Web Search**: Serper API (`google.serper.dev`).
|
| 630 |
+
* **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
|
| 631 |
+
* **Gradio Version**: This app is tested with `gradio>=4.0`. Check `requirements.txt`.
|
| 632 |
+
* **`smolagents` Issue**: If you see import errors for `smolagents` or `SyntaxError: f-string: unmatched '('`, it's likely an issue within the `smolagents` library itself. Please ensure you have tried upgrading or reinstalling it in your Space's `requirements.txt` (e.g., `smolagents>=0.1.0`). A workaround for a *different* potential `TypeError` during `CodeAgent` initialization is active in this script but won't fix `smolagents` internal syntax errors.
|
| 633 |
+
---
|
| 634 |
+
**Disclaimer**: Processing all questions can take some time. The interface will update once the entire process is complete. For a production system, consider asynchronous operations or background tasks for a smoother user experience.
|
| 635 |
+
"""
|
| 636 |
+
)
|
| 637 |
+
print("DEBUG: Gradio Markdown elements created.")
|
| 638 |
|
| 639 |
+
login_button = gr.LoginButton()
|
| 640 |
+
print("DEBUG: Gradio LoginButton created.")
|
| 641 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 642 |
+
print("DEBUG: Gradio Run Button created.")
|
| 643 |
+
|
| 644 |
+
with gr.Column():
|
| 645 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
|
| 646 |
+
results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True) # max_rows removed
|
| 647 |
+
print("DEBUG: Gradio output elements (Textbox, DataFrame) created.")
|
| 648 |
+
|
| 649 |
+
run_button.click(
|
| 650 |
+
fn=run_and_submit_all_evaluation,
|
| 651 |
+
inputs=[login_button],
|
| 652 |
+
outputs=[status_output, results_table]
|
| 653 |
+
)
|
| 654 |
+
print("DEBUG: Gradio run_button.click event handler set.")
|
| 655 |
+
print("DEBUG: Gradio interface definition complete.")
|
| 656 |
+
except Exception as e:
|
| 657 |
+
print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
|
| 658 |
+
logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
|
| 659 |
+
# Fallback or exit if UI definition fails critically
|
| 660 |
+
demo = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 661 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 662 |
|
| 663 |
# --- Application Startup & Shutdown Handling ---
|
| 664 |
if __name__ == "__main__":
|
| 665 |
+
print("\n" + "="*15 + " Application Startup " + "="*15)
|
| 666 |
|
|
|
|
| 667 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 668 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 669 |
|
| 670 |
+
print(f"Python Version: {'.'.join(map(str, asyncio.sys.version_info[:3]))}")
|
| 671 |
+
print(f"Gradio Version: {gr.__version__}")
|
|
|
|
| 672 |
try:
|
| 673 |
import smolagents
|
| 674 |
print(f"smolagents Version: {smolagents.__version__ if hasattr(smolagents, '__version__') else 'unknown'}")
|
| 675 |
except ImportError:
|
| 676 |
+
print("smolagents could not be imported (version unknown). This is expected if the library has issues.")
|
|
|
|
| 677 |
|
| 678 |
if space_host_startup:
|
| 679 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 694 |
|
| 695 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 696 |
print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
|
| 697 |
+
print("If you encounter smolagents import errors, please check its installation and version in requirements.txt.")
|
| 698 |
|
| 699 |
+
if demo is not None: # Only launch if UI definition was successful
|
| 700 |
+
try:
|
| 701 |
+
demo.launch(debug=True, share=False)
|
| 702 |
+
except Exception as e:
|
| 703 |
+
print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
|
| 704 |
+
logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
|
| 705 |
+
finally:
|
| 706 |
+
print("DEBUG: Gradio demo.launch() finished or was interrupted.")
|
| 707 |
+
logger.info("Gradio demo has been closed or failed to launch.")
|
| 708 |
+
if GLOBAL_CHUCK_AGENT:
|
| 709 |
+
print("DEBUG: Attempting to shutdown GLOBAL_CHUCK_AGENT.")
|
| 710 |
+
logger.info("Attempting to shutdown ChuckAgent and close its HTTP session...")
|
|
|
|
|
|
|
| 711 |
try:
|
| 712 |
+
GLOBAL_CHUCK_AGENT.close() # Use the synchronous close method
|
| 713 |
+
print("DEBUG: GLOBAL_CHUCK_AGENT.close() called.")
|
|
|
|
| 714 |
logger.info("ChuckAgent shutdown process completed.")
|
| 715 |
except Exception as e_shutdown:
|
| 716 |
+
print(f"DEBUG: ERROR during GLOBAL_CHUCK_AGENT.close(): {e_shutdown}")
|
| 717 |
logger.error(f"Error during ChuckAgent final shutdown: {e_shutdown}", exc_info=True)
|
| 718 |
else:
|
| 719 |
+
print("DEBUG: No GLOBAL_CHUCK_AGENT instance to shutdown.")
|
| 720 |
+
else:
|
| 721 |
+
print("DEBUG: ERROR - Gradio demo object is None, cannot launch. Check for errors during UI definition.")
|
|
|
|
| 722 |
|
| 723 |
+
print("\n" + "="*15 + " Application Shutdown " + "="*15)
|
| 724 |
+
else:
|
| 725 |
+
print("DEBUG: Script is being imported, not run as main.")
|