Update app.py
Browse files
app.py
CHANGED
|
@@ -13,12 +13,14 @@ from typing import Optional, Dict, Any, List, Tuple
|
|
| 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
|
| 18 |
# Dummy classes for script parsing if smolagents is not installed
|
| 19 |
class CodeAgent: pass
|
| 20 |
class Tool: pass
|
| 21 |
class OpenAIServerModel: pass
|
|
|
|
| 22 |
|
| 23 |
from datetime import datetime
|
| 24 |
|
|
@@ -28,20 +30,29 @@ class AppConfig:
|
|
| 28 |
QUESTIONS_URL_PATH = "/questions"
|
| 29 |
SUBMIT_URL_PATH = "/submit"
|
| 30 |
SCREENSHOTS_DIR = "screenshots"
|
| 31 |
-
OPENAI_MODEL_ID = "gpt-4o"
|
| 32 |
SERPER_API_NUM_RESULTS = 3
|
| 33 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 34 |
-
AGENT_MAX_STEPS = 10
|
| 35 |
-
AGENT_VERBOSITY_LEVEL = 2
|
| 36 |
|
| 37 |
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.
|
| 38 |
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.
|
| 39 |
When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
|
| 40 |
|
| 41 |
Available Tools:
|
| 42 |
-
1. `web_search(query: str) -> str`: Use this tool to search the internet for current information or information you do not possess. This tool is asynchronous, so your generated code MUST call it using `await`.
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
Follow this process for every question:
|
| 47 |
1. THOUGHT: Understand the user's question. Identify the core information needed.
|
|
@@ -51,18 +62,12 @@ Follow this process for every question:
|
|
| 51 |
# Your Python code to call ONE tool.
|
| 52 |
# REMEMBER: Use `await` for `web_search` and `image_retriever`.
|
| 53 |
# ALWAYS print the result of the tool call.
|
| 54 |
-
# Example for web_search:
|
| 55 |
-
# search_result = await web_search(query="some specific query")
|
| 56 |
-
# print(search_result)
|
| 57 |
-
# Example for calculator:
|
| 58 |
-
# calc_result = calculator(expression="1+1")
|
| 59 |
-
# print(calc_result)
|
| 60 |
```<end_code>
|
| 61 |
4. OBSERVATION: [The system will insert the printed output of your tool call here.]
|
| 62 |
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.
|
| 63 |
6. If you have the information, formulate the final answer according to the formatting rules.
|
| 64 |
|
| 65 |
-
CRITICAL: Your *entire response*
|
| 66 |
FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
|
| 67 |
|
| 68 |
Formatting rules for the value in FINAL ANSWER:
|
|
@@ -208,12 +213,13 @@ class CalculatorTool(Tool):
|
|
| 208 |
}
|
| 209 |
self.allowed_chars = "0123456789+-*/^(). "
|
| 210 |
|
| 211 |
-
async def forward(self, expression: str) -> str:
|
| 212 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 213 |
try:
|
| 214 |
safe_expr = "".join(c for c in expression if c in self.allowed_chars)
|
| 215 |
if not safe_expr:
|
| 216 |
return "Error: Empty or invalid expression for calculator."
|
|
|
|
| 217 |
result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
|
| 218 |
return f"Calculation result: {safe_expr} = {float(result)}"
|
| 219 |
except Exception as e:
|
|
@@ -223,7 +229,7 @@ class CalculatorTool(Tool):
|
|
| 223 |
# --- Agent Definition ---
|
| 224 |
class QuestionAnsweringAgent(CodeAgent):
|
| 225 |
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
|
| 226 |
-
|
| 227 |
WebSearchTool(session=http_session),
|
| 228 |
CalculatorTool(),
|
| 229 |
ImageRetrievalTool(session=http_session)
|
|
@@ -239,49 +245,54 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 239 |
api_key=openai_api_key
|
| 240 |
)
|
| 241 |
|
| 242 |
-
#
|
| 243 |
-
# Call super() with only arguments known/likely for MultiStepAgent
|
| 244 |
-
minimal_super_args = {
|
| 245 |
-
"model": effective_model,
|
| 246 |
-
"tools": tools,
|
| 247 |
-
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
| 248 |
-
# "code_writer": None, # If CodeAgent expects a code_writer to be passed to MultiStepAgent explicitly
|
| 249 |
-
}
|
| 250 |
try:
|
| 251 |
-
super()
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
#
|
| 255 |
-
#
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
#
|
| 275 |
-
# This is
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
except TypeError as e:
|
| 281 |
-
logger.error(f"WORKAROUND FAILED
|
| 282 |
raise e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
-
logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 285 |
|
| 286 |
|
| 287 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
|
@@ -290,36 +301,42 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 290 |
try:
|
| 291 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 292 |
|
|
|
|
| 293 |
raw_output_obj = self.run(question_text)
|
| 294 |
|
|
|
|
| 295 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 296 |
full_agent_response = str(raw_output_obj.log_string())
|
| 297 |
-
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 298 |
full_agent_response = str(raw_output_obj.text)
|
| 299 |
-
elif isinstance(raw_output_obj, str):
|
| 300 |
full_agent_response = raw_output_obj
|
| 301 |
-
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 302 |
full_agent_response = str(raw_output_obj.result)
|
| 303 |
else:
|
| 304 |
-
full_agent_response = str(raw_output_obj)
|
| 305 |
|
| 306 |
-
reasoning_trace = full_agent_response
|
| 307 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 308 |
|
|
|
|
|
|
|
| 309 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 310 |
if match:
|
| 311 |
final_answer_for_submission = match.group(1).strip()
|
| 312 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 313 |
else:
|
| 314 |
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
| 315 |
-
|
|
|
|
|
|
|
| 316 |
|
| 317 |
-
if not final_answer_for_submission:
|
| 318 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
| 319 |
final_answer_for_submission = "Could not determine answer."
|
| 320 |
|
| 321 |
-
except TypeError as te:
|
| 322 |
-
logger.error(f"TypeError during agent processing: {str(te)}", exc_info=True)
|
| 323 |
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 324 |
reasoning_trace += f"\nTypeError encountered: {str(te)}"
|
| 325 |
except Exception as e:
|
|
@@ -342,7 +359,7 @@ class ChuckAgent:
|
|
| 342 |
logger.info("ChuckAgent initialization started")
|
| 343 |
try:
|
| 344 |
self.loop = asyncio.get_running_loop()
|
| 345 |
-
except RuntimeError:
|
| 346 |
self.loop = asyncio.new_event_loop()
|
| 347 |
asyncio.set_event_loop(self.loop)
|
| 348 |
|
|
@@ -353,6 +370,7 @@ class ChuckAgent:
|
|
| 353 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 354 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
| 355 |
try:
|
|
|
|
| 356 |
if asyncio.get_event_loop() is not self.loop:
|
| 357 |
asyncio.set_event_loop(self.loop)
|
| 358 |
|
|
@@ -392,7 +410,7 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 392 |
except requests.exceptions.RequestException as e:
|
| 393 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 394 |
raise ConnectionError(f"Error fetching questions: {e}") from e
|
| 395 |
-
except (requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 396 |
logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 397 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 398 |
|
|
@@ -404,24 +422,24 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 404 |
for i, item in enumerate(questions_data):
|
| 405 |
task_id = item.get("task_id")
|
| 406 |
question_text = item.get("question")
|
| 407 |
-
if not task_id or question_text is None:
|
| 408 |
logger.warning(f"Skipping item {i+1} with missing data: {item}")
|
| 409 |
continue
|
| 410 |
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 411 |
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 412 |
try:
|
| 413 |
model_ans, reasoning = agent(question_text)
|
| 414 |
-
except Exception as e:
|
| 415 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 416 |
-
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 417 |
-
reasoning = str(e)
|
| 418 |
|
| 419 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 420 |
-
if reasoning:
|
| 421 |
payload_item["reasoning_trace"] = reasoning
|
| 422 |
answers_payload.append(payload_item)
|
| 423 |
|
| 424 |
-
results_log.append({
|
| 425 |
"Task ID": task_id,
|
| 426 |
"Question": question_text,
|
| 427 |
"Submitted Answer": model_ans,
|
|
@@ -438,8 +456,8 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 438 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 439 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 440 |
try:
|
| 441 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 442 |
-
response.raise_for_status()
|
| 443 |
result_data = response.json()
|
| 444 |
return (
|
| 445 |
f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
|
|
@@ -450,47 +468,50 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 450 |
except requests.exceptions.HTTPError as e:
|
| 451 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 452 |
try:
|
| 453 |
-
error_json = e.response.json()
|
| 454 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 455 |
-
except requests.exceptions.JSONDecodeError:
|
| 456 |
-
error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 457 |
logger.error(f"Submission Failed: {error_detail}")
|
| 458 |
return f"Submission Failed: {error_detail}"
|
| 459 |
except requests.exceptions.Timeout:
|
| 460 |
logger.error("Submission Failed: The request timed out.")
|
| 461 |
return "Submission Failed: The request timed out."
|
| 462 |
-
except requests.exceptions.RequestException as e:
|
| 463 |
logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
|
| 464 |
return f"Submission Failed: Network error - {e}"
|
| 465 |
-
except Exception as e:
|
| 466 |
logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
|
| 467 |
return f"An unexpected error occurred during submission: {e}"
|
| 468 |
|
| 469 |
# --- Gradio Interface Main Function ---
|
| 470 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 471 |
|
|
|
|
| 472 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 473 |
global GLOBAL_CHUCK_AGENT
|
| 474 |
logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
|
| 475 |
-
if args:
|
| 476 |
logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
|
| 477 |
|
|
|
|
| 478 |
if not isinstance(profile, gr.OAuthProfile) and profile is not None:
|
| 479 |
logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
|
|
|
|
| 480 |
found_profile_in_args = False
|
| 481 |
-
for arg_val in args:
|
| 482 |
if isinstance(arg_val, gr.OAuthProfile):
|
| 483 |
-
profile = arg_val
|
| 484 |
found_profile_in_args = True
|
| 485 |
logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
|
| 486 |
break
|
| 487 |
-
if not found_profile_in_args and profile is None:
|
| 488 |
logger.error("Could not identify a valid gr.OAuthProfile object.")
|
| 489 |
return "Login error: Could not identify user profile.", pd.DataFrame()
|
| 490 |
|
| 491 |
logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
|
| 492 |
|
| 493 |
-
if not profile:
|
| 494 |
logger.warning("User not logged in for evaluation.")
|
| 495 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 496 |
|
|
@@ -499,26 +520,26 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 499 |
|
| 500 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 501 |
logger.info(f"Agent code URL: {agent_code_url}")
|
| 502 |
-
results_log_data: List[Dict[str, Any]] = []
|
| 503 |
|
| 504 |
try:
|
| 505 |
if GLOBAL_CHUCK_AGENT is None:
|
| 506 |
GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
|
| 507 |
-
agent_instance = GLOBAL_CHUCK_AGENT
|
| 508 |
except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
|
| 509 |
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 510 |
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 511 |
-
except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError
|
| 512 |
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 513 |
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 514 |
|
| 515 |
try:
|
| 516 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 517 |
-
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
|
| 518 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 519 |
-
except (ConnectionError, ValueError) as e:
|
| 520 |
submission_status = str(e)
|
| 521 |
-
except Exception as e:
|
| 522 |
logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
|
| 523 |
submission_status = f"An unexpected error occurred: {e}"
|
| 524 |
|
|
@@ -538,7 +559,7 @@ with gr.Blocks() as demo:
|
|
| 538 |
)
|
| 539 |
gr.Markdown(
|
| 540 |
"""
|
| 541 |
-
**Disclaimers:** Once clicking on the "submit" button, it can take quite some time
|
| 542 |
"""
|
| 543 |
)
|
| 544 |
gr.Markdown(
|
|
@@ -547,15 +568,15 @@ with gr.Blocks() as demo:
|
|
| 547 |
**Technical Notes:**
|
| 548 |
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 549 |
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 550 |
-
*
|
| 551 |
-
*
|
| 552 |
"""
|
| 553 |
)
|
| 554 |
|
| 555 |
login_button = gr.LoginButton()
|
| 556 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 557 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
|
| 558 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 559 |
|
| 560 |
run_button.click(
|
| 561 |
fn=run_and_submit_all_evaluation,
|
|
@@ -583,31 +604,34 @@ if __name__ == "__main__":
|
|
| 583 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 584 |
|
| 585 |
print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
|
| 586 |
-
print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
|
| 587 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 588 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 589 |
|
| 590 |
try:
|
| 591 |
-
demo.launch(debug=True, share=False)
|
| 592 |
finally:
|
|
|
|
| 593 |
loop_to_use = None
|
|
|
|
| 594 |
if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
|
| 595 |
loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
|
| 596 |
-
elif SHARED_HTTP_SESSION:
|
| 597 |
loop_to_use = SHARED_HTTP_SESSION.loop
|
| 598 |
|
| 599 |
if loop_to_use and loop_to_use.is_running():
|
| 600 |
logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
|
| 601 |
try:
|
|
|
|
| 602 |
current_loop = asyncio.get_event_loop_policy().get_event_loop() # More robust way to get current loop
|
| 603 |
-
if current_loop is not loop_to_use and not loop_to_use.is_closed():
|
| 604 |
asyncio.set_event_loop(loop_to_use)
|
| 605 |
|
| 606 |
if GLOBAL_CHUCK_AGENT:
|
| 607 |
loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
|
| 608 |
-
elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
|
| 609 |
loop_to_use.run_until_complete(close_shared_http_session())
|
| 610 |
-
except Exception as e:
|
| 611 |
logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
|
| 612 |
else:
|
| 613 |
logger.info("No active HTTP session or running loop to close in finally block.")
|
|
|
|
| 13 |
# Import necessary components from smolagents
|
| 14 |
try:
|
| 15 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 16 |
+
from smolagents.code_writer import CodeWriter # CRITICAL IMPORT for the workaround
|
| 17 |
except ImportError:
|
| 18 |
+
logging.error("Failed to import smolagents or smolagents.code_writer. Ensure smolagents is correctly installed.")
|
| 19 |
# Dummy classes for script parsing if smolagents is not installed
|
| 20 |
class CodeAgent: pass
|
| 21 |
class Tool: pass
|
| 22 |
class OpenAIServerModel: pass
|
| 23 |
+
class CodeWriter: pass # Dummy for parsing
|
| 24 |
|
| 25 |
from datetime import datetime
|
| 26 |
|
|
|
|
| 30 |
QUESTIONS_URL_PATH = "/questions"
|
| 31 |
SUBMIT_URL_PATH = "/submit"
|
| 32 |
SCREENSHOTS_DIR = "screenshots"
|
| 33 |
+
OPENAI_MODEL_ID = "gpt-4o" # Using gpt-4o as per user's update
|
| 34 |
SERPER_API_NUM_RESULTS = 3
|
| 35 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 36 |
+
AGENT_MAX_STEPS = 10 # Keep as 10, logs show it reaching this often
|
| 37 |
+
AGENT_VERBOSITY_LEVEL = 2
|
| 38 |
|
| 39 |
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.
|
| 40 |
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.
|
| 41 |
When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
|
| 42 |
|
| 43 |
Available Tools:
|
| 44 |
+
1. `web_search(query: str) -> str`: Use this tool to search the internet for current information or information you do not possess. This tool is asynchronous, so your generated code MUST call it using `await`.
|
| 45 |
+
Example:
|
| 46 |
+
search_results = await web_search(query="latest news on AI")
|
| 47 |
+
print(search_results)
|
| 48 |
+
2. `calculator(expression: str) -> str`: Use this tool for any mathematical calculations. This tool is synchronous.
|
| 49 |
+
Example:
|
| 50 |
+
result = calculator(expression="((1024 / 8) + 55 - 5) * 2")
|
| 51 |
+
print(result)
|
| 52 |
+
3. `image_retriever(url: str) -> str`: Use this tool to retrieve an image from a specific URL. This tool is asynchronous and MUST be called using `await`. It returns a status message about the retrieval.
|
| 53 |
+
Example:
|
| 54 |
+
retrieval_status = await image_retriever(url="http://example.com/image.png")
|
| 55 |
+
print(retrieval_status)
|
| 56 |
|
| 57 |
Follow this process for every question:
|
| 58 |
1. THOUGHT: Understand the user's question. Identify the core information needed.
|
|
|
|
| 62 |
# Your Python code to call ONE tool.
|
| 63 |
# REMEMBER: Use `await` for `web_search` and `image_retriever`.
|
| 64 |
# ALWAYS print the result of the tool call.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
```<end_code>
|
| 66 |
4. OBSERVATION: [The system will insert the printed output of your tool call here.]
|
| 67 |
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.
|
| 68 |
6. If you have the information, formulate the final answer according to the formatting rules.
|
| 69 |
|
| 70 |
+
CRITICAL: Your *entire response* for each turn MUST culminate in the final answer using this exact template on a new line:
|
| 71 |
FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
|
| 72 |
|
| 73 |
Formatting rules for the value in FINAL ANSWER:
|
|
|
|
| 213 |
}
|
| 214 |
self.allowed_chars = "0123456789+-*/^(). "
|
| 215 |
|
| 216 |
+
async def forward(self, expression: str) -> str: # Still async for Tool compatibility, but logic is sync
|
| 217 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 218 |
try:
|
| 219 |
safe_expr = "".join(c for c in expression if c in self.allowed_chars)
|
| 220 |
if not safe_expr:
|
| 221 |
return "Error: Empty or invalid expression for calculator."
|
| 222 |
+
# Using eval safely
|
| 223 |
result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
|
| 224 |
return f"Calculation result: {safe_expr} = {float(result)}"
|
| 225 |
except Exception as e:
|
|
|
|
| 229 |
# --- Agent Definition ---
|
| 230 |
class QuestionAnsweringAgent(CodeAgent):
|
| 231 |
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
|
| 232 |
+
tools_list = [
|
| 233 |
WebSearchTool(session=http_session),
|
| 234 |
CalculatorTool(),
|
| 235 |
ImageRetrievalTool(session=http_session)
|
|
|
|
| 245 |
api_key=openai_api_key
|
| 246 |
)
|
| 247 |
|
| 248 |
+
# REVISED WORKAROUND for MultiStepAgent TypeError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
try:
|
| 250 |
+
# Step 1: Call MultiStepAgent's __init__ directly (via CodeAgent's super() carefully)
|
| 251 |
+
# We provide only arguments that MultiStepAgent directly accepts to avoid TypeError.
|
| 252 |
+
# MultiStepAgent's signature is typically (model, tools, max_steps, code_writer, verbosity_level, etc.)
|
| 253 |
+
# However, the TypeError indicates it's not accepting 'system_prompt' if passed through kwargs.
|
| 254 |
+
# The 'code_writer' is normally created by CodeAgent and passed to its super.
|
| 255 |
+
# To be safe, we initialize MultiStepAgent with its core, non-problematic args.
|
| 256 |
+
super(CodeAgent, self).__init__( # Calling parent of CodeAgent (MultiStepAgent)
|
| 257 |
+
model=effective_model,
|
| 258 |
+
tools=tools_list,
|
| 259 |
+
max_steps=CONFIG.AGENT_MAX_STEPS
|
| 260 |
+
# We will set verbosity_level on self later if CodeAgent uses it directly.
|
| 261 |
+
# code_writer will be set by CodeAgent part of the init
|
| 262 |
+
)
|
| 263 |
+
logger.info("QuestionAnsweringAgent > MultiStepAgent super().__init__ called with MINIMAL args (workaround).")
|
| 264 |
+
|
| 265 |
+
# Step 2: Now set CodeAgent's own attributes and initialize its CodeWriter
|
| 266 |
+
self.model = effective_model # Already passed to MultiStepAgent, but good to have on self.
|
| 267 |
+
self.tools = tools_list # Already passed to MultiStepAgent, but good to have on self.
|
| 268 |
+
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT # CRITICAL: for CodeWriter
|
| 269 |
+
self.additional_authorized_imports = ["PIL", "pandas"] # AUTHORIZED PANDAS
|
| 270 |
+
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL # For CodeAgent's own logging if it uses this attribute
|
| 271 |
+
# self.max_steps is handled by MultiStepAgent.
|
| 272 |
+
|
| 273 |
+
# Step 3: Manually create and assign the CodeWriter.
|
| 274 |
+
# This is the most important part of the workaround to ensure the system_prompt is used.
|
| 275 |
+
# CodeWriter is imported at the top of the file.
|
| 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
|
| 281 |
+
# CodeWriter might accept other parameters; refer to its definition if needed.
|
| 282 |
+
)
|
| 283 |
+
logger.info("Manually initialized self.code_writer for CodeAgent with system_prompt, tools, and authorized imports.")
|
| 284 |
|
| 285 |
except TypeError as e:
|
| 286 |
+
logger.error(f"WORKAROUND FAILED during __init__ (TypeError): {e}", exc_info=True)
|
| 287 |
raise e
|
| 288 |
+
except ImportError as e_imp: # Catch if CodeWriter import fails
|
| 289 |
+
logger.error(f"Failed to import CodeWriter: {e_imp}. Agent will not function correctly.", exc_info=True)
|
| 290 |
+
raise e_imp
|
| 291 |
+
except Exception as e_init: # Catch any other exception during this delicate init
|
| 292 |
+
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__ (workaround): {e_init}", exc_info=True)
|
| 293 |
+
raise e_init
|
| 294 |
|
| 295 |
+
logger.info(f"QuestionAnsweringAgent initialized (with workaround) with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 296 |
|
| 297 |
|
| 298 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
|
|
|
| 301 |
try:
|
| 302 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 303 |
|
| 304 |
+
# self.run() is synchronous for CodeAgent
|
| 305 |
raw_output_obj = self.run(question_text)
|
| 306 |
|
| 307 |
+
# Attempt to get the most complete textual output from the agent's run
|
| 308 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 309 |
full_agent_response = str(raw_output_obj.log_string())
|
| 310 |
+
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None: # AgentText often has .text
|
| 311 |
full_agent_response = str(raw_output_obj.text)
|
| 312 |
+
elif isinstance(raw_output_obj, str): # If run() itself returns a string
|
| 313 |
full_agent_response = raw_output_obj
|
| 314 |
+
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None: # Another common attribute
|
| 315 |
full_agent_response = str(raw_output_obj.result)
|
| 316 |
else:
|
| 317 |
+
full_agent_response = str(raw_output_obj) # Fallback, try to stringify directly
|
| 318 |
|
| 319 |
+
reasoning_trace = full_agent_response # Use the full response as the trace
|
| 320 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 321 |
|
| 322 |
+
# Regex to find "FINAL ANSWER:" and capture everything after it.
|
| 323 |
+
# re.DOTALL allows '.' to match newlines.
|
| 324 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 325 |
if match:
|
| 326 |
final_answer_for_submission = match.group(1).strip()
|
| 327 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 328 |
else:
|
| 329 |
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
| 330 |
+
# The full response might contain reasoning steps, not just the answer.
|
| 331 |
+
# This might need further cleaning if it's too verbose for submission.
|
| 332 |
+
final_answer_for_submission = full_agent_response.strip()
|
| 333 |
|
| 334 |
+
if not final_answer_for_submission: # If empty after stripping
|
| 335 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
| 336 |
final_answer_for_submission = "Could not determine answer."
|
| 337 |
|
| 338 |
+
except TypeError as te: # Catching the specific TypeError first
|
| 339 |
+
logger.error(f"TypeError during agent processing (likely self.run call or its output handling): {str(te)}", exc_info=True)
|
| 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:
|
|
|
|
| 359 |
logger.info("ChuckAgent initialization started")
|
| 360 |
try:
|
| 361 |
self.loop = asyncio.get_running_loop()
|
| 362 |
+
except RuntimeError: # No running loop
|
| 363 |
self.loop = asyncio.new_event_loop()
|
| 364 |
asyncio.set_event_loop(self.loop)
|
| 365 |
|
|
|
|
| 370 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 371 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
| 372 |
try:
|
| 373 |
+
# Ensure the correct event loop is set for this thread if Gradio runs in a separate one.
|
| 374 |
if asyncio.get_event_loop() is not self.loop:
|
| 375 |
asyncio.set_event_loop(self.loop)
|
| 376 |
|
|
|
|
| 410 |
except requests.exceptions.RequestException as e:
|
| 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: # Catch if response is not valid JSON
|
| 414 |
logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 415 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 416 |
|
|
|
|
| 422 |
for i, item in enumerate(questions_data):
|
| 423 |
task_id = item.get("task_id")
|
| 424 |
question_text = item.get("question")
|
| 425 |
+
if not task_id or question_text is None: # Check if question_text is None as well
|
| 426 |
logger.warning(f"Skipping item {i+1} with missing data: {item}")
|
| 427 |
continue
|
| 428 |
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 429 |
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 430 |
try:
|
| 431 |
model_ans, reasoning = agent(question_text)
|
| 432 |
+
except Exception as e: # Catch any exception from the agent call itself
|
| 433 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 434 |
+
model_ans = f"AGENT_CALL_ERROR: {e}" # More specific error for submission
|
| 435 |
+
reasoning = str(e) # Include the error in reasoning
|
| 436 |
|
| 437 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 438 |
+
if reasoning: # Ensure reasoning is not None or empty before adding
|
| 439 |
payload_item["reasoning_trace"] = reasoning
|
| 440 |
answers_payload.append(payload_item)
|
| 441 |
|
| 442 |
+
results_log.append({ # For local logging/display
|
| 443 |
"Task ID": task_id,
|
| 444 |
"Question": question_text,
|
| 445 |
"Submitted Answer": model_ans,
|
|
|
|
| 456 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 457 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 458 |
try:
|
| 459 |
+
response = requests.post(submit_url, json=submission_data, timeout=60) # Increased timeout
|
| 460 |
+
response.raise_for_status() # Will raise HTTPError for bad responses (4xx or 5xx)
|
| 461 |
result_data = response.json()
|
| 462 |
return (
|
| 463 |
f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
|
|
|
|
| 468 |
except requests.exceptions.HTTPError as e:
|
| 469 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 470 |
try:
|
| 471 |
+
error_json = e.response.json() # Try to get JSON detail from error response
|
| 472 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 473 |
+
except requests.exceptions.JSONDecodeError: # If error response isn't JSON
|
| 474 |
+
error_detail += f" Raw Response: {e.response.text[:500]}" # Show part of raw response
|
| 475 |
logger.error(f"Submission Failed: {error_detail}")
|
| 476 |
return f"Submission Failed: {error_detail}"
|
| 477 |
except requests.exceptions.Timeout:
|
| 478 |
logger.error("Submission Failed: The request timed out.")
|
| 479 |
return "Submission Failed: The request timed out."
|
| 480 |
+
except requests.exceptions.RequestException as e: # Catch other network errors
|
| 481 |
logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
|
| 482 |
return f"Submission Failed: Network error - {e}"
|
| 483 |
+
except Exception as e: # Catch any other unexpected error during submission
|
| 484 |
logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
|
| 485 |
return f"An unexpected error occurred during submission: {e}"
|
| 486 |
|
| 487 |
# --- Gradio Interface Main Function ---
|
| 488 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 489 |
|
| 490 |
+
# Gradio function signature adjustment to handle potential extra args from LoginButton
|
| 491 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 492 |
global GLOBAL_CHUCK_AGENT
|
| 493 |
logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
|
| 494 |
+
if args: # Log if any unexpected positional arguments are received
|
| 495 |
logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
|
| 496 |
|
| 497 |
+
# Ensure 'profile' is the actual OAuthProfile object
|
| 498 |
if not isinstance(profile, gr.OAuthProfile) and profile is not None:
|
| 499 |
logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
|
| 500 |
+
# Attempt to find the profile in args if it was misplaced by Gradio's event system
|
| 501 |
found_profile_in_args = False
|
| 502 |
+
for arg_val in args: # Iterate through any extra positional arguments
|
| 503 |
if isinstance(arg_val, gr.OAuthProfile):
|
| 504 |
+
profile = arg_val # Use the found profile
|
| 505 |
found_profile_in_args = True
|
| 506 |
logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
|
| 507 |
break
|
| 508 |
+
if not found_profile_in_args and profile is None: # If profile was initially None and not found in args
|
| 509 |
logger.error("Could not identify a valid gr.OAuthProfile object.")
|
| 510 |
return "Login error: Could not identify user profile.", pd.DataFrame()
|
| 511 |
|
| 512 |
logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
|
| 513 |
|
| 514 |
+
if not profile: # This check remains crucial
|
| 515 |
logger.warning("User not logged in for evaluation.")
|
| 516 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 517 |
|
|
|
|
| 520 |
|
| 521 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 522 |
logger.info(f"Agent code URL: {agent_code_url}")
|
| 523 |
+
results_log_data: List[Dict[str, Any]] = [] # Ensure it's initialized
|
| 524 |
|
| 525 |
try:
|
| 526 |
if GLOBAL_CHUCK_AGENT is None:
|
| 527 |
GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
|
| 528 |
+
agent_instance = GLOBAL_CHUCK_AGENT # Use a local variable for clarity
|
| 529 |
except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
|
| 530 |
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 531 |
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 532 |
+
except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError workaround might if it fails
|
| 533 |
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 534 |
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 535 |
|
| 536 |
try:
|
| 537 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 538 |
+
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data) # Use agent_instance
|
| 539 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 540 |
+
except (ConnectionError, ValueError) as e: # Catch errors from fetching/processing
|
| 541 |
submission_status = str(e)
|
| 542 |
+
except Exception as e: # Catch any other unexpected error in the pipeline
|
| 543 |
logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
|
| 544 |
submission_status = f"An unexpected error occurred: {e}"
|
| 545 |
|
|
|
|
| 559 |
)
|
| 560 |
gr.Markdown(
|
| 561 |
"""
|
| 562 |
+
**Disclaimers:** Once clicking on the "submit" button, it can take quite some time for the agent to process all questions. This space provides a basic setup.
|
| 563 |
"""
|
| 564 |
)
|
| 565 |
gr.Markdown(
|
|
|
|
| 568 |
**Technical Notes:**
|
| 569 |
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 570 |
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 571 |
+
* A workaround is active for `smolagents.CodeAgent` initialization due to a library issue.
|
| 572 |
+
* `pandas` has been added to authorized imports for the agent.
|
| 573 |
"""
|
| 574 |
)
|
| 575 |
|
| 576 |
login_button = gr.LoginButton()
|
| 577 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 578 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
|
| 579 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # Removed max_rows for better display
|
| 580 |
|
| 581 |
run_button.click(
|
| 582 |
fn=run_and_submit_all_evaluation,
|
|
|
|
| 604 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 605 |
|
| 606 |
print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
|
| 607 |
+
print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}") # For visibility
|
| 608 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 609 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 610 |
|
| 611 |
try:
|
| 612 |
+
demo.launch(debug=True, share=False) # share=False is default and safer
|
| 613 |
finally:
|
| 614 |
+
# Attempt to gracefully close the aiohttp session on exit
|
| 615 |
loop_to_use = None
|
| 616 |
+
# Check if event loop for http_session exists and is running
|
| 617 |
if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
|
| 618 |
loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
|
| 619 |
+
elif SHARED_HTTP_SESSION: # Fallback if agent not fully created but session was
|
| 620 |
loop_to_use = SHARED_HTTP_SESSION.loop
|
| 621 |
|
| 622 |
if loop_to_use and loop_to_use.is_running():
|
| 623 |
logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
|
| 624 |
try:
|
| 625 |
+
# Ensure we are using the correct event loop that the session was created with.
|
| 626 |
current_loop = asyncio.get_event_loop_policy().get_event_loop() # More robust way to get current loop
|
| 627 |
+
if current_loop is not loop_to_use and not loop_to_use.is_closed(): # Check if loop_to_use is not closed
|
| 628 |
asyncio.set_event_loop(loop_to_use)
|
| 629 |
|
| 630 |
if GLOBAL_CHUCK_AGENT:
|
| 631 |
loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
|
| 632 |
+
elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed: # Fallback, if agent didn't init but session did
|
| 633 |
loop_to_use.run_until_complete(close_shared_http_session())
|
| 634 |
+
except Exception as e: # Catch broader exceptions during cleanup
|
| 635 |
logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
|
| 636 |
else:
|
| 637 |
logger.info("No active HTTP session or running loop to close in finally block.")
|