Update app.py
Browse files
app.py
CHANGED
|
@@ -6,40 +6,25 @@ import asyncio
|
|
| 6 |
import re
|
| 7 |
import json
|
| 8 |
import logging
|
| 9 |
-
import operator
|
| 10 |
import aiohttp
|
| 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__)
|
| 18 |
-
|
| 19 |
# Import necessary components from smolagents
|
| 20 |
try:
|
| 21 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
class
|
| 30 |
-
|
|
|
|
| 31 |
class OpenAIServerModel:
|
| 32 |
-
|
| 33 |
-
logging.warning("Using DUMMY OpenAIServerModel due to smolagents import failure.")
|
| 34 |
-
pass
|
| 35 |
-
class CodeWriter:
|
| 36 |
-
def __init__(self, *args, **kwargs):
|
| 37 |
-
logging.warning("Using DUMMY CodeWriter due to smolagents.code_writer import failure.")
|
| 38 |
-
pass
|
| 39 |
-
class LocalPythonExecutor: # Dummy if import fails
|
| 40 |
-
def __init__(self, *args, **kwargs):
|
| 41 |
-
logging.warning("Using DUMMY LocalPythonExecutor due to smolagents.execution import failure.")
|
| 42 |
-
pass
|
| 43 |
|
| 44 |
from datetime import datetime
|
| 45 |
|
|
@@ -49,11 +34,11 @@ class AppConfig:
|
|
| 49 |
QUESTIONS_URL_PATH = "/questions"
|
| 50 |
SUBMIT_URL_PATH = "/submit"
|
| 51 |
SCREENSHOTS_DIR = "screenshots"
|
| 52 |
-
OPENAI_MODEL_ID = "gpt-4o"
|
| 53 |
SERPER_API_NUM_RESULTS = 3
|
| 54 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 55 |
-
AGENT_MAX_STEPS =
|
| 56 |
-
AGENT_VERBOSITY_LEVEL = 2
|
| 57 |
|
| 58 |
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.
|
| 59 |
You have access to a specific set of Python tools. You MUST use these exact function names as provided when you decide to use a tool.
|
|
@@ -72,23 +57,35 @@ Follow this process for every question:
|
|
| 72 |
# Your Python code to call ONE tool.
|
| 73 |
# REMEMBER: Use `await` for `web_search` and `image_retriever`.
|
| 74 |
# ALWAYS print the result of the tool call.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
```<end_code>
|
| 76 |
4. OBSERVATION: [The system will insert the printed output of your tool call here.]
|
| 77 |
5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, what is your next step? (e.g., use another tool, refine a previous tool call, or formulate the answer). If you need to use another tool, go back to step 2.
|
| 78 |
6. If you have the information, formulate the final answer according to the formatting rules.
|
| 79 |
|
| 80 |
-
CRITICAL: Your *entire response* for each turn must culminate in the final answer using this exact template on a new line:
|
| 81 |
FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
|
| 82 |
|
| 83 |
Formatting rules for the value in FINAL ANSWER:
|
| 84 |
- If the question asks for a number: Provide only the number itself (e.g., 42). Do not use commas for thousands separation (e.g., use 1234 not 1,234). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
|
| 85 |
-
- If the question asks for a string: Provide the most concise string possible. Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like "NYC" for "New York City") unless the question implies it. Write out numerical digits as words (e.g., "two" instead of 2) unless numerical digits are requested.
|
| 86 |
-
- If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., item one,item two,three). NO space after the comma unless it's part of the item itself.
|
| 87 |
- If the answer is a calculation result, provide just the number.
|
| 88 |
"""
|
| 89 |
|
| 90 |
CONFIG = AppConfig()
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
# --- Utility Functions ---
|
| 93 |
def ensure_dir_exists(directory_path: str):
|
| 94 |
os.makedirs(directory_path, exist_ok=True)
|
|
@@ -114,11 +111,11 @@ async def close_shared_http_session():
|
|
| 114 |
|
| 115 |
# --- Tool Definitions ---
|
| 116 |
class ImageRetrievalTool(Tool):
|
| 117 |
-
name = "image_retriever"
|
| 118 |
description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
|
| 119 |
inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
|
| 120 |
output_type = "string"
|
| 121 |
-
is_async = True
|
| 122 |
|
| 123 |
def __init__(self, session: aiohttp.ClientSession):
|
| 124 |
super().__init__()
|
|
@@ -149,7 +146,7 @@ class ImageRetrievalTool(Tool):
|
|
| 149 |
return f"Error retrieving image: {str(e)}"
|
| 150 |
|
| 151 |
class WebSearchTool(Tool):
|
| 152 |
-
name = "web_search"
|
| 153 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 154 |
inputs = {"query": {"type": "string", "description": "The search query to execute."}}
|
| 155 |
output_type = "string"
|
|
@@ -202,7 +199,7 @@ class WebSearchTool(Tool):
|
|
| 202 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 203 |
|
| 204 |
class CalculatorTool(Tool):
|
| 205 |
-
name = "calculator"
|
| 206 |
description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
|
| 207 |
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
|
| 208 |
output_type = "string"
|
|
@@ -217,13 +214,13 @@ class CalculatorTool(Tool):
|
|
| 217 |
}
|
| 218 |
self.allowed_chars = "0123456789+-*/^(). "
|
| 219 |
|
| 220 |
-
async def forward(self, expression: str) -> str:
|
| 221 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 222 |
try:
|
| 223 |
safe_expr = "".join(c for c in expression if c in self.allowed_chars)
|
| 224 |
if not safe_expr:
|
| 225 |
return "Error: Empty or invalid expression for calculator."
|
| 226 |
-
result = eval(safe_expr, {"__builtins__": {}}, self.operations)
|
| 227 |
return f"Calculation result: {safe_expr} = {float(result)}"
|
| 228 |
except Exception as e:
|
| 229 |
logger.error(f"Error evaluating expression '{expression}': {str(e)}")
|
|
@@ -232,83 +229,81 @@ class CalculatorTool(Tool):
|
|
| 232 |
# --- Agent Definition ---
|
| 233 |
class QuestionAnsweringAgent(CodeAgent):
|
| 234 |
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
|
| 235 |
-
|
| 236 |
-
logger.error("Cannot initialize QuestionAnsweringAgent: smolagents components failed to import earlier.")
|
| 237 |
-
raise ImportError("smolagents components not available for QuestionAnsweringAgent.")
|
| 238 |
-
|
| 239 |
-
tools_list = [
|
| 240 |
WebSearchTool(session=http_session),
|
| 241 |
CalculatorTool(),
|
| 242 |
ImageRetrievalTool(session=http_session)
|
| 243 |
]
|
| 244 |
-
|
| 245 |
effective_model = model
|
| 246 |
if effective_model is None:
|
| 247 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 248 |
if not openai_api_key:
|
| 249 |
-
raise EnvironmentError(
|
| 250 |
-
|
|
|
|
| 251 |
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 252 |
-
api_key=openai_api_key
|
| 253 |
)
|
| 254 |
|
| 255 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
try:
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
|
| 272 |
-
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
|
| 273 |
-
|
| 274 |
-
# Step 3: Manually initialize CodeAgent's `code_writer`.
|
| 275 |
-
if SMOLAGENTS_IMPORTED_SUCCESSFULLY:
|
| 276 |
-
self.code_writer = CodeWriter(
|
| 277 |
-
model=self.model,
|
| 278 |
-
tools=self.tools,
|
| 279 |
-
system_prompt=self.system_prompt,
|
| 280 |
-
additional_authorized_imports=self.additional_authorized_imports # Use the one set by Agent base
|
| 281 |
-
)
|
| 282 |
-
logger.info("Manually initialized self.code_writer for CodeAgent.")
|
| 283 |
else:
|
| 284 |
-
logger.
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
if
|
| 288 |
-
self.
|
| 289 |
-
logger.info(
|
|
|
|
| 290 |
else:
|
| 291 |
-
logger.
|
|
|
|
| 292 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
|
| 294 |
except TypeError as e:
|
| 295 |
-
logger.error(
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
raise e_init
|
| 300 |
-
|
| 301 |
-
logger.info(f"QuestionAnsweringAgent initialized (with workaround) with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 302 |
|
|
|
|
| 303 |
|
| 304 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
| 305 |
reasoning_trace = "Agent execution started."
|
| 306 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 307 |
try:
|
| 308 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 309 |
-
|
| 310 |
-
raw_output_obj = self.run(question_text)
|
| 311 |
-
|
| 312 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 313 |
full_agent_response = str(raw_output_obj.log_string())
|
| 314 |
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
|
@@ -317,19 +312,21 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 317 |
full_agent_response = raw_output_obj
|
| 318 |
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 319 |
full_agent_response = str(raw_output_obj.result)
|
| 320 |
-
else:
|
| 321 |
full_agent_response = str(raw_output_obj)
|
| 322 |
-
|
| 323 |
reasoning_trace = full_agent_response
|
| 324 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 325 |
|
| 326 |
-
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response,
|
|
|
|
| 327 |
if match:
|
| 328 |
final_answer_for_submission = match.group(1).strip()
|
| 329 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 330 |
else:
|
| 331 |
-
logger.warning(
|
| 332 |
-
|
|
|
|
| 333 |
|
| 334 |
if not final_answer_for_submission:
|
| 335 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
|
@@ -340,25 +337,23 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 340 |
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 341 |
reasoning_trace += f"\nTypeError encountered: {str(te)}"
|
| 342 |
except Exception as e:
|
| 343 |
-
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}",
|
|
|
|
| 344 |
final_answer_for_submission = f"Error in agent processing: {str(e)}"
|
| 345 |
reasoning_trace += f"\nError encountered: {str(e)}"
|
| 346 |
-
|
| 347 |
return final_answer_for_submission, reasoning_trace
|
| 348 |
|
| 349 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 350 |
class ChuckAgent:
|
| 351 |
def __init__(self):
|
| 352 |
-
if not SMOLAGENTS_IMPORTED_SUCCESSFULLY:
|
| 353 |
-
raise ImportError("smolagents components not available, ChuckAgent cannot be initialized.")
|
| 354 |
-
|
| 355 |
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
| 356 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 357 |
if missing_vars:
|
| 358 |
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
|
| 359 |
logger.critical(error_msg)
|
| 360 |
raise EnvironmentError(error_msg)
|
| 361 |
-
|
| 362 |
logger.info("ChuckAgent initialization started")
|
| 363 |
try:
|
| 364 |
self.loop = asyncio.get_running_loop()
|
|
@@ -367,24 +362,21 @@ class ChuckAgent:
|
|
| 367 |
asyncio.set_event_loop(self.loop)
|
| 368 |
|
| 369 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
except Exception as agent_init_error:
|
| 373 |
-
logger.error(f"Failed to initialize QuestionAnsweringAgent within ChuckAgent: {agent_init_error}", exc_info=True)
|
| 374 |
-
self.loop.run_until_complete(close_shared_http_session())
|
| 375 |
-
raise
|
| 376 |
-
|
| 377 |
logger.info("ChuckAgent fully initialized")
|
| 378 |
-
|
| 379 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 380 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
| 381 |
try:
|
| 382 |
if asyncio.get_event_loop() is not self.loop:
|
| 383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
-
final_answer, reasoning_trace = self.loop.run_until_complete(
|
| 386 |
-
self.agent.process_question(question)
|
| 387 |
-
)
|
| 388 |
logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
|
| 389 |
return final_answer, reasoning_trace
|
| 390 |
except Exception as e:
|
|
@@ -398,7 +390,6 @@ class ChuckAgent:
|
|
| 398 |
logger.info("ChuckAgent shutdown complete.")
|
| 399 |
|
| 400 |
# --- Core Evaluation Logic ---
|
| 401 |
-
# (This section remains unchanged)
|
| 402 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 403 |
space_id = os.getenv("SPACE_ID")
|
| 404 |
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)"
|
|
@@ -420,10 +411,13 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 420 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 421 |
raise ConnectionError(f"Error fetching questions: {e}") from e
|
| 422 |
except (requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 423 |
-
logger.error(
|
|
|
|
|
|
|
| 424 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 425 |
|
| 426 |
-
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[
|
|
|
|
| 427 |
answers_payload = []
|
| 428 |
results_log = []
|
| 429 |
logger.info(f"Running agent on {len(questions_data)} questions...")
|
|
@@ -432,9 +426,9 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 432 |
task_id = item.get("task_id")
|
| 433 |
question_text = item.get("question")
|
| 434 |
if not task_id or question_text is None:
|
| 435 |
-
logger.warning(f"Skipping item {i+1} with missing data: {item}")
|
| 436 |
continue
|
| 437 |
-
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 438 |
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 439 |
try:
|
| 440 |
model_ans, reasoning = agent(question_text)
|
|
@@ -442,27 +436,29 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 442 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 443 |
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 444 |
reasoning = str(e)
|
| 445 |
-
|
| 446 |
-
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 447 |
-
if reasoning:
|
| 448 |
payload_item["reasoning_trace"] = reasoning
|
| 449 |
answers_payload.append(payload_item)
|
| 450 |
-
|
| 451 |
results_log.append({
|
| 452 |
-
"Task ID": task_id,
|
| 453 |
-
"Question": question_text,
|
| 454 |
-
"Submitted Answer": model_ans,
|
| 455 |
"Reasoning Trace": reasoning
|
| 456 |
})
|
| 457 |
return answers_payload, results_log
|
| 458 |
|
| 459 |
-
def submit_answers(base_api_url: str, username: str, agent_code_url: str,
|
|
|
|
| 460 |
if not answers_payload:
|
| 461 |
logger.warning("Agent did not produce any answers to submit.")
|
| 462 |
return "Agent did not produce any answers to submit."
|
| 463 |
|
| 464 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 465 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code_url,
|
|
|
|
| 466 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 467 |
try:
|
| 468 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
@@ -491,7 +487,7 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 491 |
return f"Submission Failed: Network error - {e}"
|
| 492 |
except Exception as e:
|
| 493 |
logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
|
| 494 |
-
return f"An unexpected error occurred
|
| 495 |
|
| 496 |
# --- Gradio Interface Main Function ---
|
| 497 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
|
@@ -512,9 +508,9 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 512 |
logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
|
| 513 |
break
|
| 514 |
if not found_profile_in_args and profile is None:
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
|
| 519 |
|
| 520 |
if not profile:
|
|
@@ -530,15 +526,12 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 530 |
|
| 531 |
try:
|
| 532 |
if GLOBAL_CHUCK_AGENT is None:
|
| 533 |
-
|
| 534 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 535 |
-
except
|
| 536 |
-
logger.critical(f"Agent instantiation failed due to
|
| 537 |
-
return f"Agent Initialization Error: Failed to import smolagents. Check Space logs for build errors.", pd.DataFrame()
|
| 538 |
-
except EnvironmentError as e:
|
| 539 |
-
logger.critical(f"Agent instantiation failed due to missing env vars: {e}", exc_info=True)
|
| 540 |
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 541 |
-
except Exception as e:
|
| 542 |
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 543 |
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 544 |
|
|
@@ -551,7 +544,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 551 |
except Exception as e:
|
| 552 |
logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
|
| 553 |
submission_status = f"An unexpected error occurred: {e}"
|
| 554 |
-
|
| 555 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 556 |
return submission_status, results_df
|
| 557 |
|
|
@@ -568,17 +561,17 @@ with gr.Blocks() as demo:
|
|
| 568 |
)
|
| 569 |
gr.Markdown(
|
| 570 |
"""
|
| 571 |
-
**Disclaimers:** Once clicking on the "submit" button, it can take quite some time for the agent to
|
| 572 |
"""
|
| 573 |
)
|
| 574 |
gr.Markdown(
|
| 575 |
-
|
| 576 |
---
|
| 577 |
**Technical Notes:**
|
| 578 |
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 579 |
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 580 |
-
* `requirements.txt` should specify a compatible `gradio` version
|
| 581 |
-
*
|
| 582 |
"""
|
| 583 |
)
|
| 584 |
|
|
@@ -595,7 +588,7 @@ with gr.Blocks() as demo:
|
|
| 595 |
|
| 596 |
# --- Application Startup & Shutdown Handling ---
|
| 597 |
if __name__ == "__main__":
|
| 598 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 599 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 600 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 601 |
|
|
@@ -611,34 +604,5 @@ if __name__ == "__main__":
|
|
| 611 |
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 612 |
else:
|
| 613 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 614 |
-
|
| 615 |
-
print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
|
| 616 |
-
print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
|
| 617 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 618 |
-
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 619 |
-
|
| 620 |
-
try:
|
| 621 |
-
demo.launch(debug=True, share=False)
|
| 622 |
-
finally:
|
| 623 |
-
loop_to_use = None
|
| 624 |
-
if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
|
| 625 |
-
loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
|
| 626 |
-
elif SHARED_HTTP_SESSION:
|
| 627 |
-
loop_to_use = SHARED_HTTP_SESSION.loop
|
| 628 |
-
|
| 629 |
-
if loop_to_use and loop_to_use.is_running():
|
| 630 |
-
logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
|
| 631 |
-
try:
|
| 632 |
-
current_loop = asyncio.get_event_loop_policy().get_event_loop()
|
| 633 |
-
if current_loop is not loop_to_use and not loop_to_use.is_closed():
|
| 634 |
-
asyncio.set_event_loop(loop_to_use)
|
| 635 |
-
|
| 636 |
-
if GLOBAL_CHUCK_AGENT:
|
| 637 |
-
loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
|
| 638 |
-
elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
|
| 639 |
-
loop_to_use.run_until_complete(close_shared_http_session())
|
| 640 |
-
except Exception as e:
|
| 641 |
-
logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
|
| 642 |
-
else:
|
| 643 |
-
logger.info("No active HTTP session or running loop to close in finally block.")
|
| 644 |
|
|
|
|
|
|
| 6 |
import re
|
| 7 |
import json
|
| 8 |
import logging
|
| 9 |
+
import operator # Used by CalculatorTool
|
| 10 |
import aiohttp
|
| 11 |
from typing import Optional, Dict, Any, List, Tuple
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# Import necessary components from smolagents
|
| 14 |
try:
|
| 15 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 16 |
+
except ImportError:
|
| 17 |
+
logging.error("Failed to import smolagents. Please ensure it is installed.")
|
| 18 |
+
|
| 19 |
+
# Dummy classes for script parsing if smolagents is not installed
|
| 20 |
+
class CodeAgent:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
class Tool:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
class OpenAIServerModel:
|
| 27 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
from datetime import datetime
|
| 30 |
|
|
|
|
| 34 |
QUESTIONS_URL_PATH = "/questions"
|
| 35 |
SUBMIT_URL_PATH = "/submit"
|
| 36 |
SCREENSHOTS_DIR = "screenshots"
|
| 37 |
+
OPENAI_MODEL_ID = "gpt-4o"
|
| 38 |
SERPER_API_NUM_RESULTS = 3
|
| 39 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 40 |
+
AGENT_MAX_STEPS = 10
|
| 41 |
+
AGENT_VERBOSITY_LEVEL = 2 # Will attempt to set this via workaround
|
| 42 |
|
| 43 |
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.
|
| 44 |
You have access to a specific set of Python tools. You MUST use these exact function names as provided when you decide to use a tool.
|
|
|
|
| 57 |
# Your Python code to call ONE tool.
|
| 58 |
# REMEMBER: Use `await` for `web_search` and `image_retriever`.
|
| 59 |
# ALWAYS print the result of the tool call.
|
| 60 |
+
# Example for web_search:
|
| 61 |
+
# search_result = await web_search(query="some specific query")
|
| 62 |
+
# print(search_result)
|
| 63 |
+
# Example for calculator:
|
| 64 |
+
# calc_result = calculator(expression="1+1")
|
| 65 |
+
# print(calc_result)
|
| 66 |
```<end_code>
|
| 67 |
4. OBSERVATION: [The system will insert the printed output of your tool call here.]
|
| 68 |
5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, what is your next step? (e.g., use another tool, refine a previous tool call, or formulate the answer). If you need to use another tool, go back to step 2.
|
| 69 |
6. If you have the information, formulate the final answer according to the formatting rules.
|
| 70 |
|
| 71 |
+
CRITICAL: Your *entire response* to the user for each turn must culminate in the final answer using this exact template on a new line:
|
| 72 |
FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
|
| 73 |
|
| 74 |
Formatting rules for the value in FINAL ANSWER:
|
| 75 |
- If the question asks for a number: Provide only the number itself (e.g., 42). Do not use commas for thousands separation (e.g., use 1234 not 1,234). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
|
| 76 |
+
- If the question asks for a string: Provide the most concise string possible. Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like \"NYC\" for \"New York City\") unless the question implies it. Write out numerical digits as words (e.g., \"two\" instead of 2) unless numerical digits are requested.
|
| 77 |
+
- If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., item one,item two,three). NO space after the comma unless it\'s part of the item itself.
|
| 78 |
- If the answer is a calculation result, provide just the number.
|
| 79 |
"""
|
| 80 |
|
| 81 |
CONFIG = AppConfig()
|
| 82 |
|
| 83 |
+
# --- Logging Setup ---
|
| 84 |
+
logging.basicConfig(
|
| 85 |
+
level=logging.INFO,
|
| 86 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 87 |
+
logger = logging.getLogger(__name__)
|
| 88 |
+
|
| 89 |
# --- Utility Functions ---
|
| 90 |
def ensure_dir_exists(directory_path: str):
|
| 91 |
os.makedirs(directory_path, exist_ok=True)
|
|
|
|
| 111 |
|
| 112 |
# --- Tool Definitions ---
|
| 113 |
class ImageRetrievalTool(Tool):
|
| 114 |
+
name = "image_retriever"
|
| 115 |
description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
|
| 116 |
inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
|
| 117 |
output_type = "string"
|
| 118 |
+
is_async = True
|
| 119 |
|
| 120 |
def __init__(self, session: aiohttp.ClientSession):
|
| 121 |
super().__init__()
|
|
|
|
| 146 |
return f"Error retrieving image: {str(e)}"
|
| 147 |
|
| 148 |
class WebSearchTool(Tool):
|
| 149 |
+
name = "web_search"
|
| 150 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 151 |
inputs = {"query": {"type": "string", "description": "The search query to execute."}}
|
| 152 |
output_type = "string"
|
|
|
|
| 199 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 200 |
|
| 201 |
class CalculatorTool(Tool):
|
| 202 |
+
name = "calculator"
|
| 203 |
description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
|
| 204 |
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
|
| 205 |
output_type = "string"
|
|
|
|
| 214 |
}
|
| 215 |
self.allowed_chars = "0123456789+-*/^(). "
|
| 216 |
|
| 217 |
+
async def forward(self, expression: str) -> str:
|
| 218 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 219 |
try:
|
| 220 |
safe_expr = "".join(c for c in expression if c in self.allowed_chars)
|
| 221 |
if not safe_expr:
|
| 222 |
return "Error: Empty or invalid expression for calculator."
|
| 223 |
+
result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
|
| 224 |
return f"Calculation result: {safe_expr} = {float(result)}"
|
| 225 |
except Exception as e:
|
| 226 |
logger.error(f"Error evaluating expression '{expression}': {str(e)}")
|
|
|
|
| 229 |
# --- Agent Definition ---
|
| 230 |
class QuestionAnsweringAgent(CodeAgent):
|
| 231 |
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
|
| 232 |
+
tools = [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
WebSearchTool(session=http_session),
|
| 234 |
CalculatorTool(),
|
| 235 |
ImageRetrievalTool(session=http_session)
|
| 236 |
]
|
| 237 |
+
|
| 238 |
effective_model = model
|
| 239 |
if effective_model is None:
|
| 240 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 241 |
if not openai_api_key:
|
| 242 |
+
raise EnvironmentError(
|
| 243 |
+
"OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 244 |
+
effective_model = OpenAIServerModel(
|
| 245 |
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 246 |
+
api_key=openai_api_key
|
| 247 |
)
|
| 248 |
|
| 249 |
+
# REINSTATED WORKAROUND for MultiStepAgent TypeError
|
| 250 |
+
# Call super() with only arguments known/likely for MultiStepAgent
|
| 251 |
+
minimal_super_args = {
|
| 252 |
+
"model": effective_model,
|
| 253 |
+
"tools": tools,
|
| 254 |
+
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
| 255 |
+
# "code_writer": None, # If CodeAgent expects a code_writer to be passed to MultiStepAgent explicitly
|
| 256 |
+
}
|
| 257 |
try:
|
| 258 |
+
super().__init__(**minimal_super_args)
|
| 259 |
+
logger.info(
|
| 260 |
+
"QuestionAnsweringAgent (CodeAgent) super().__init__ called with MINIMAL args (workaround active).")
|
| 261 |
+
|
| 262 |
+
# Explicitly set CodeAgent-specific attributes after init.
|
| 263 |
+
# This relies on CodeAgent using these instance attributes.
|
| 264 |
+
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
|
| 265 |
+
logger.info(f"Explicitly set self.system_prompt for CodeAgent.")
|
| 266 |
+
|
| 267 |
+
# These might be read-only or set internally in a way this doesn't override.
|
| 268 |
+
# We log a warning if the attribute doesn't exist to be set.
|
| 269 |
+
if hasattr(self, 'verbosity_level'):
|
| 270 |
+
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
|
| 271 |
+
logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
else:
|
| 273 |
+
logger.warning(
|
| 274 |
+
"Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
|
| 275 |
+
|
| 276 |
+
if hasattr(self, 'additional_authorized_imports'):
|
| 277 |
+
self.additional_authorized_imports = ["PIL"] # Make sure PIL is in requirements if needed
|
| 278 |
+
logger.info(
|
| 279 |
+
f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
|
| 280 |
else:
|
| 281 |
+
logger.warning(
|
| 282 |
+
"Could not set 'additional_authorized_imports' as an attribute after init.")
|
| 283 |
|
| 284 |
+
# The CodeWriter is crucial for CodeAgent. It's usually initialized within CodeAgent's __init__.
|
| 285 |
+
# If the minimal super call doesn't set it up, the agent might fail to generate code.
|
| 286 |
+
# This is a deeper aspect of the workaround's potential side effects.
|
| 287 |
+
if not hasattr(self, 'code_writer') or self.code_writer is None:
|
| 288 |
+
logger.warning(
|
| 289 |
+
"self.code_writer might not be initialized due to workaround. Agent may fail to generate code.")
|
| 290 |
|
| 291 |
except TypeError as e:
|
| 292 |
+
logger.error(
|
| 293 |
+
f"WORKAROUND FAILED: Still got TypeError during minimal super().__init__: {e}",
|
| 294 |
+
exc_info=True)
|
| 295 |
+
raise e
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
+
logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 298 |
|
| 299 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
| 300 |
reasoning_trace = "Agent execution started."
|
| 301 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 302 |
try:
|
| 303 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 304 |
+
|
| 305 |
+
raw_output_obj = self.run(question_text)
|
| 306 |
+
|
| 307 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 308 |
full_agent_response = str(raw_output_obj.log_string())
|
| 309 |
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
|
|
|
| 312 |
full_agent_response = raw_output_obj
|
| 313 |
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 314 |
full_agent_response = str(raw_output_obj.result)
|
| 315 |
+
else:
|
| 316 |
full_agent_response = str(raw_output_obj)
|
| 317 |
+
|
| 318 |
reasoning_trace = full_agent_response
|
| 319 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 320 |
|
| 321 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response,
|
| 322 |
+
re.IGNORECASE | re.DOTALL)
|
| 323 |
if match:
|
| 324 |
final_answer_for_submission = match.group(1).strip()
|
| 325 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 326 |
else:
|
| 327 |
+
logger.warning(
|
| 328 |
+
"Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
| 329 |
+
final_answer_for_submission = full_agent_response.strip()
|
| 330 |
|
| 331 |
if not final_answer_for_submission:
|
| 332 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
|
|
|
| 337 |
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 338 |
reasoning_trace += f"\nTypeError encountered: {str(te)}"
|
| 339 |
except Exception as e:
|
| 340 |
+
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}",
|
| 341 |
+
exc_info=True)
|
| 342 |
final_answer_for_submission = f"Error in agent processing: {str(e)}"
|
| 343 |
reasoning_trace += f"\nError encountered: {str(e)}"
|
| 344 |
+
|
| 345 |
return final_answer_for_submission, reasoning_trace
|
| 346 |
|
| 347 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 348 |
class ChuckAgent:
|
| 349 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
| 350 |
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
| 351 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 352 |
if missing_vars:
|
| 353 |
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
|
| 354 |
logger.critical(error_msg)
|
| 355 |
raise EnvironmentError(error_msg)
|
| 356 |
+
|
| 357 |
logger.info("ChuckAgent initialization started")
|
| 358 |
try:
|
| 359 |
self.loop = asyncio.get_running_loop()
|
|
|
|
| 362 |
asyncio.set_event_loop(self.loop)
|
| 363 |
|
| 364 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
| 365 |
+
self.agent = QuestionAnsweringAgent(
|
| 366 |
+
http_session=self.http_session) # This might raise if the workaround fails
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
logger.info("ChuckAgent fully initialized")
|
| 368 |
+
|
| 369 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 370 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
| 371 |
try:
|
| 372 |
if asyncio.get_event_loop() is not self.loop:
|
| 373 |
+
asyncio.set_event_loop(self.loop)
|
| 374 |
+
|
| 375 |
+
# Schedule the agent's processing within the current event loop
|
| 376 |
+
agent_task = asyncio.ensure_future(self.agent.process_question(question),
|
| 377 |
+
loop=self.loop)
|
| 378 |
+
final_answer, reasoning_trace = self.loop.run_until_complete(agent_task)
|
| 379 |
|
|
|
|
|
|
|
|
|
|
| 380 |
logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
|
| 381 |
return final_answer, reasoning_trace
|
| 382 |
except Exception as e:
|
|
|
|
| 390 |
logger.info("ChuckAgent shutdown complete.")
|
| 391 |
|
| 392 |
# --- Core Evaluation Logic ---
|
|
|
|
| 393 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 394 |
space_id = os.getenv("SPACE_ID")
|
| 395 |
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)"
|
|
|
|
| 411 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 412 |
raise ConnectionError(f"Error fetching questions: {e}") from e
|
| 413 |
except (requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 414 |
+
logger.error(
|
| 415 |
+
f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}",
|
| 416 |
+
exc_info=True)
|
| 417 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 418 |
|
| 419 |
+
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[
|
| 420 |
+
List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 421 |
answers_payload = []
|
| 422 |
results_log = []
|
| 423 |
logger.info(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 426 |
task_id = item.get("task_id")
|
| 427 |
question_text = item.get("question")
|
| 428 |
if not task_id or question_text is None:
|
| 429 |
+
logger.warning(f"Skipping item {i + 1} with missing data: {item}")
|
| 430 |
continue
|
| 431 |
+
logger.info(f"Processing task {i + 1}/{len(questions_data)}, ID: {task_id}")
|
| 432 |
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 433 |
try:
|
| 434 |
model_ans, reasoning = agent(question_text)
|
|
|
|
| 436 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 437 |
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 438 |
reasoning = str(e)
|
| 439 |
+
|
| 440 |
+
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 441 |
+
if reasoning:
|
| 442 |
payload_item["reasoning_trace"] = reasoning
|
| 443 |
answers_payload.append(payload_item)
|
| 444 |
+
|
| 445 |
results_log.append({
|
| 446 |
+
"Task ID": task_id,
|
| 447 |
+
"Question": question_text,
|
| 448 |
+
"Submitted Answer": model_ans,
|
| 449 |
"Reasoning Trace": reasoning
|
| 450 |
})
|
| 451 |
return answers_payload, results_log
|
| 452 |
|
| 453 |
+
def submit_answers(base_api_url: str, username: str, agent_code_url: str,
|
| 454 |
+
answers_payload: List[Dict[str, Any]]) -> str:
|
| 455 |
if not answers_payload:
|
| 456 |
logger.warning("Agent did not produce any answers to submit.")
|
| 457 |
return "Agent did not produce any answers to submit."
|
| 458 |
|
| 459 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 460 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code_url,
|
| 461 |
+
"answers": answers_payload}
|
| 462 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 463 |
try:
|
| 464 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 487 |
return f"Submission Failed: Network error - {e}"
|
| 488 |
except Exception as e:
|
| 489 |
logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
|
| 490 |
+
return f"An unexpected error occurred: {e}"
|
| 491 |
|
| 492 |
# --- Gradio Interface Main Function ---
|
| 493 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
|
|
|
| 508 |
logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
|
| 509 |
break
|
| 510 |
if not found_profile_in_args and profile is None:
|
| 511 |
+
logger.error("Could not identify a valid gr.OAuthProfile object.")
|
| 512 |
+
return "Login error: Could not identify user profile.", pd.DataFrame()
|
| 513 |
+
|
| 514 |
logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
|
| 515 |
|
| 516 |
if not profile:
|
|
|
|
| 526 |
|
| 527 |
try:
|
| 528 |
if GLOBAL_CHUCK_AGENT is None:
|
| 529 |
+
GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
|
| 530 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 531 |
+
except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
|
| 532 |
+
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
|
|
|
|
|
|
|
|
|
| 533 |
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 534 |
+
except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError we're fixing
|
| 535 |
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 536 |
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 537 |
|
|
|
|
| 544 |
except Exception as e:
|
| 545 |
logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
|
| 546 |
submission_status = f"An unexpected error occurred: {e}"
|
| 547 |
+
|
| 548 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 549 |
return submission_status, results_df
|
| 550 |
|
|
|
|
| 561 |
)
|
| 562 |
gr.Markdown(
|
| 563 |
"""
|
| 564 |
+
**Disclaimers:** Once clicking on the \"submit\" button, it can take quite some time ( this is the time for the agent to go through all the questions). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions in async.
|
| 565 |
"""
|
| 566 |
)
|
| 567 |
gr.Markdown(
|
| 568 |
+
f"""
|
| 569 |
---
|
| 570 |
**Technical Notes:**
|
| 571 |
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 572 |
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 573 |
+
* `requirements.txt` should specify a compatible `gradio` version (e.g., `gradio==4.29.0` or `gradio==4.44.1`).
|
| 574 |
+
* The current `smolagents` version might have an internal issue with `CodeAgent` initialization. A workaround is active.
|
| 575 |
"""
|
| 576 |
)
|
| 577 |
|
|
|
|
| 588 |
|
| 589 |
# --- Application Startup & Shutdown Handling ---
|
| 590 |
if __name__ == "__main__":
|
| 591 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 592 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 593 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 594 |
|
|
|
|
| 604 |
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 605 |
else:
|
| 606 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 607 |
|
| 608 |
+
print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
|