Update app.py
Browse files
app.py
CHANGED
|
@@ -28,26 +28,22 @@ class AppConfig:
|
|
| 28 |
QUESTIONS_URL_PATH = "/questions"
|
| 29 |
SUBMIT_URL_PATH = "/submit"
|
| 30 |
SCREENSHOTS_DIR = "screenshots"
|
| 31 |
-
OPENAI_MODEL_ID = "gpt-3.5-turbo"
|
| 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 |
-
# MODIFIED AND ENHANCED AGENT_SYSTEM_PROMPT
|
| 38 |
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.
|
| 39 |
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.
|
| 40 |
When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
|
| 41 |
|
| 42 |
Available Tools:
|
| 43 |
-
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`.
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
Example of generated code: `print(await image_retriever(url="https://example.com/image.jpg"))`
|
| 49 |
-
|
| 50 |
-
Follow this thought process for every question:
|
| 51 |
1. THOUGHT: Understand the user's question. Identify the core information needed.
|
| 52 |
2. THOUGHT: Decide if one of your available tools (`web_search`, `calculator`, `image_retriever`) can help obtain this information. If yes, state which tool you will use and what input you will provide to it. If no tool is needed, explain that you can answer directly.
|
| 53 |
3. CODE (if using a tool):
|
|
@@ -55,11 +51,12 @@ Follow this thought process for every question:
|
|
| 55 |
# Your Python code to call ONE tool.
|
| 56 |
# REMEMBER: Use `await` for `web_search` and `image_retriever`.
|
| 57 |
# ALWAYS print the result of the tool call.
|
| 58 |
-
# Example:
|
| 59 |
-
#
|
| 60 |
-
# print(
|
| 61 |
-
#
|
| 62 |
-
#
|
|
|
|
| 63 |
```<end_code>
|
| 64 |
4. OBSERVATION: [The system will insert the printed output of your tool call here.]
|
| 65 |
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,8 +66,8 @@ CRITICAL: Your *entire response* to the user for each turn must culminate in the
|
|
| 69 |
FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
|
| 70 |
|
| 71 |
Formatting rules for the value in FINAL ANSWER:
|
| 72 |
-
- If the question asks for a number: Provide only the number (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.
|
| 73 |
-
- 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
|
| 74 |
- 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.
|
| 75 |
- If the answer is a calculation result, provide just the number.
|
| 76 |
"""
|
|
@@ -108,11 +105,11 @@ async def close_shared_http_session():
|
|
| 108 |
|
| 109 |
# --- Tool Definitions ---
|
| 110 |
class ImageRetrievalTool(Tool):
|
| 111 |
-
name = "image_retriever"
|
| 112 |
description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
|
| 113 |
inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
|
| 114 |
output_type = "string"
|
| 115 |
-
is_async = True
|
| 116 |
|
| 117 |
def __init__(self, session: aiohttp.ClientSession):
|
| 118 |
super().__init__()
|
|
@@ -143,11 +140,11 @@ class ImageRetrievalTool(Tool):
|
|
| 143 |
return f"Error retrieving image: {str(e)}"
|
| 144 |
|
| 145 |
class WebSearchTool(Tool):
|
| 146 |
-
name = "web_search"
|
| 147 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 148 |
inputs = {"query": {"type": "string", "description": "The search query to execute."}}
|
| 149 |
output_type = "string"
|
| 150 |
-
is_async = True
|
| 151 |
|
| 152 |
def __init__(self, session: aiohttp.ClientSession):
|
| 153 |
super().__init__()
|
|
@@ -196,11 +193,11 @@ class WebSearchTool(Tool):
|
|
| 196 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 197 |
|
| 198 |
class CalculatorTool(Tool):
|
| 199 |
-
name = "calculator"
|
| 200 |
description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
|
| 201 |
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
|
| 202 |
output_type = "string"
|
| 203 |
-
is_async = False
|
| 204 |
|
| 205 |
def __init__(self):
|
| 206 |
super().__init__()
|
|
@@ -211,7 +208,7 @@ class CalculatorTool(Tool):
|
|
| 211 |
}
|
| 212 |
self.allowed_chars = "0123456789+-*/^(). "
|
| 213 |
|
| 214 |
-
async def forward(self, expression: str) -> str:
|
| 215 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 216 |
try:
|
| 217 |
safe_expr = "".join(c for c in expression if c in self.allowed_chars)
|
|
@@ -231,7 +228,7 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 231 |
CalculatorTool(),
|
| 232 |
ImageRetrievalTool(session=http_session)
|
| 233 |
]
|
| 234 |
-
|
| 235 |
effective_model = model
|
| 236 |
if effective_model is None:
|
| 237 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
|
@@ -242,37 +239,69 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 242 |
api_key=openai_api_key
|
| 243 |
)
|
| 244 |
|
| 245 |
-
#
|
| 246 |
-
super()
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 256 |
|
|
|
|
| 257 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
| 258 |
reasoning_trace = "Agent execution started."
|
| 259 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 260 |
try:
|
| 261 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 262 |
|
| 263 |
-
raw_output_obj = self.run(question_text)
|
| 264 |
|
| 265 |
-
# Attempt to get the most complete textual output from the agent's run
|
| 266 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 267 |
full_agent_response = str(raw_output_obj.log_string())
|
| 268 |
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 269 |
full_agent_response = str(raw_output_obj.text)
|
| 270 |
-
elif isinstance(raw_output_obj, str):
|
| 271 |
full_agent_response = raw_output_obj
|
| 272 |
-
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 273 |
full_agent_response = str(raw_output_obj.result)
|
| 274 |
else:
|
| 275 |
-
full_agent_response = str(raw_output_obj)
|
| 276 |
|
| 277 |
reasoning_trace = full_agent_response
|
| 278 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
|
@@ -280,24 +309,18 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 280 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 281 |
if match:
|
| 282 |
final_answer_for_submission = match.group(1).strip()
|
| 283 |
-
# Further clean up if necessary, e.g., removing trailing thoughts if any part of the thought process
|
| 284 |
-
# accidentally got included after "FINAL ANSWER:" due to LLM verbosity.
|
| 285 |
-
# This simple strip might be enough for now.
|
| 286 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 287 |
else:
|
| 288 |
-
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback
|
| 289 |
-
|
| 290 |
-
# The full_agent_response might be just thoughts, or a conversational answer.
|
| 291 |
-
# For submission, this might be penalized.
|
| 292 |
-
final_answer_for_submission = full_agent_response.strip() # Fallback
|
| 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
|
| 300 |
-
final_answer_for_submission = f"Error in agent processing: {str(te)}"
|
| 301 |
reasoning_trace += f"\nTypeError encountered: {str(te)}"
|
| 302 |
except Exception as e:
|
| 303 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
|
|
@@ -324,7 +347,7 @@ class ChuckAgent:
|
|
| 324 |
asyncio.set_event_loop(self.loop)
|
| 325 |
|
| 326 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
| 327 |
-
self.agent = QuestionAnsweringAgent(http_session=self.http_session)
|
| 328 |
logger.info("ChuckAgent fully initialized")
|
| 329 |
|
| 330 |
def __call__(self, question: str) -> Tuple[str, str]:
|
|
@@ -341,250 +364,4 @@ class ChuckAgent:
|
|
| 341 |
except Exception as e:
|
| 342 |
error_msg = f"Error running ChuckAgent: {str(e)}"
|
| 343 |
logger.error(error_msg, exc_info=True)
|
| 344 |
-
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg
|
| 345 |
-
|
| 346 |
-
async def shutdown(self):
|
| 347 |
-
logger.info("ChuckAgent shutting down...")
|
| 348 |
-
await close_shared_http_session()
|
| 349 |
-
logger.info("ChuckAgent shutdown complete.")
|
| 350 |
-
|
| 351 |
-
# --- Core Evaluation Logic ---
|
| 352 |
-
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 353 |
-
space_id = os.getenv("SPACE_ID")
|
| 354 |
-
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)"
|
| 355 |
-
return space_id, agent_code_url
|
| 356 |
-
|
| 357 |
-
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 358 |
-
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
| 359 |
-
logger.info(f"Fetching questions from: {questions_url}")
|
| 360 |
-
try:
|
| 361 |
-
response = requests.get(questions_url, timeout=30)
|
| 362 |
-
response.raise_for_status()
|
| 363 |
-
questions_data = response.json()
|
| 364 |
-
if not questions_data or not isinstance(questions_data, list):
|
| 365 |
-
logger.warning(f"Fetched questions empty or invalid: {questions_data}")
|
| 366 |
-
raise ValueError("Fetched questions list is empty or not a list.")
|
| 367 |
-
logger.info(f"Fetched {len(questions_data)} questions.")
|
| 368 |
-
return questions_data
|
| 369 |
-
except requests.exceptions.RequestException as e:
|
| 370 |
-
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 371 |
-
raise ConnectionError(f"Error fetching questions: {e}") from e
|
| 372 |
-
except (requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 373 |
-
logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 374 |
-
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 375 |
-
|
| 376 |
-
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 377 |
-
answers_payload = []
|
| 378 |
-
results_log = []
|
| 379 |
-
logger.info(f"Running agent on {len(questions_data)} questions...")
|
| 380 |
-
|
| 381 |
-
for i, item in enumerate(questions_data):
|
| 382 |
-
task_id = item.get("task_id")
|
| 383 |
-
question_text = item.get("question")
|
| 384 |
-
if not task_id or question_text is None:
|
| 385 |
-
logger.warning(f"Skipping item {i+1} with missing data: {item}")
|
| 386 |
-
continue
|
| 387 |
-
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 388 |
-
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 389 |
-
try:
|
| 390 |
-
model_ans, reasoning = agent(question_text)
|
| 391 |
-
except Exception as e:
|
| 392 |
-
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 393 |
-
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 394 |
-
reasoning = str(e)
|
| 395 |
-
|
| 396 |
-
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 397 |
-
if reasoning:
|
| 398 |
-
payload_item["reasoning_trace"] = reasoning
|
| 399 |
-
answers_payload.append(payload_item)
|
| 400 |
-
|
| 401 |
-
results_log.append({
|
| 402 |
-
"Task ID": task_id,
|
| 403 |
-
"Question": question_text,
|
| 404 |
-
"Submitted Answer": model_ans,
|
| 405 |
-
"Reasoning Trace": reasoning
|
| 406 |
-
})
|
| 407 |
-
return answers_payload, results_log
|
| 408 |
-
|
| 409 |
-
def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
|
| 410 |
-
if not answers_payload:
|
| 411 |
-
logger.warning("Agent did not produce any answers to submit.")
|
| 412 |
-
return "Agent did not produce any answers to submit."
|
| 413 |
-
|
| 414 |
-
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 415 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 416 |
-
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 417 |
-
try:
|
| 418 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 419 |
-
response.raise_for_status()
|
| 420 |
-
result_data = response.json()
|
| 421 |
-
return (
|
| 422 |
-
f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
|
| 423 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 424 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 425 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 426 |
-
)
|
| 427 |
-
except requests.exceptions.HTTPError as e:
|
| 428 |
-
error_detail = f"Server responded with {e.response.status_code}."
|
| 429 |
-
try:
|
| 430 |
-
error_json = e.response.json()
|
| 431 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 432 |
-
except requests.exceptions.JSONDecodeError:
|
| 433 |
-
error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 434 |
-
logger.error(f"Submission Failed: {error_detail}")
|
| 435 |
-
return f"Submission Failed: {error_detail}"
|
| 436 |
-
except requests.exceptions.Timeout:
|
| 437 |
-
logger.error("Submission Failed: The request timed out.")
|
| 438 |
-
return "Submission Failed: The request timed out."
|
| 439 |
-
except requests.exceptions.RequestException as e:
|
| 440 |
-
logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
|
| 441 |
-
return f"Submission Failed: Network error - {e}"
|
| 442 |
-
except Exception as e:
|
| 443 |
-
logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
|
| 444 |
-
return f"An unexpected error occurred during submission: {e}"
|
| 445 |
-
|
| 446 |
-
# --- Gradio Interface Main Function ---
|
| 447 |
-
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 448 |
-
|
| 449 |
-
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 450 |
-
global GLOBAL_CHUCK_AGENT
|
| 451 |
-
logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
|
| 452 |
-
if args:
|
| 453 |
-
logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
|
| 454 |
-
|
| 455 |
-
if not isinstance(profile, gr.OAuthProfile) and profile is not None:
|
| 456 |
-
logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
|
| 457 |
-
found_profile_in_args = False
|
| 458 |
-
for arg_val in args: # Renamed arg to arg_val to avoid conflict with outer scope 'args' name
|
| 459 |
-
if isinstance(arg_val, gr.OAuthProfile):
|
| 460 |
-
profile = arg_val
|
| 461 |
-
found_profile_in_args = True
|
| 462 |
-
logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
|
| 463 |
-
break
|
| 464 |
-
if not found_profile_in_args and profile is None:
|
| 465 |
-
logger.error("Could not identify a valid gr.OAuthProfile object.")
|
| 466 |
-
return "Login error: Could not identify user profile.", pd.DataFrame()
|
| 467 |
-
|
| 468 |
-
logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
|
| 469 |
-
|
| 470 |
-
if not profile:
|
| 471 |
-
logger.warning("User not logged in for evaluation.")
|
| 472 |
-
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 473 |
-
|
| 474 |
-
username = profile.username
|
| 475 |
-
logger.info(f"User logged in: {username}")
|
| 476 |
-
|
| 477 |
-
_, agent_code_url = get_space_id_agent_code_url()
|
| 478 |
-
logger.info(f"Agent code URL: {agent_code_url}")
|
| 479 |
-
results_log_data: List[Dict[str, Any]] = []
|
| 480 |
-
|
| 481 |
-
try:
|
| 482 |
-
if GLOBAL_CHUCK_AGENT is None:
|
| 483 |
-
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 484 |
-
agent_instance = GLOBAL_CHUCK_AGENT # Use a local variable for clarity
|
| 485 |
-
except EnvironmentError as e:
|
| 486 |
-
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 487 |
-
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 488 |
-
except Exception as e:
|
| 489 |
-
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 490 |
-
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 491 |
-
|
| 492 |
-
try:
|
| 493 |
-
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 494 |
-
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data) # Use agent_instance
|
| 495 |
-
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 496 |
-
except (ConnectionError, ValueError) as e:
|
| 497 |
-
submission_status = str(e)
|
| 498 |
-
except Exception as e:
|
| 499 |
-
logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
|
| 500 |
-
submission_status = f"An unexpected error occurred: {e}"
|
| 501 |
-
|
| 502 |
-
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 503 |
-
return submission_status, results_df
|
| 504 |
-
|
| 505 |
-
# --- Build Gradio Interface ---
|
| 506 |
-
with gr.Blocks() as demo:
|
| 507 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 508 |
-
gr.Markdown(
|
| 509 |
-
"""
|
| 510 |
-
**Instructions:**
|
| 511 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 512 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 513 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 514 |
-
"""
|
| 515 |
-
)
|
| 516 |
-
gr.Markdown(
|
| 517 |
-
"""
|
| 518 |
-
**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.
|
| 519 |
-
"""
|
| 520 |
-
)
|
| 521 |
-
gr.Markdown(
|
| 522 |
-
f"""
|
| 523 |
-
---
|
| 524 |
-
**Technical Notes:**
|
| 525 |
-
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 526 |
-
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 527 |
-
* `requirements.txt` should specify `gradio>=4.19.2` or newer. (`gradio==4.25.0` or a similar fixed version recommended from previous discussions).
|
| 528 |
-
* Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` (current default) or `"gpt-4"` in the script for different performance/capability.
|
| 529 |
-
"""
|
| 530 |
-
)
|
| 531 |
-
|
| 532 |
-
login_button = gr.LoginButton()
|
| 533 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 534 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
|
| 535 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # max_rows removed
|
| 536 |
-
|
| 537 |
-
run_button.click(
|
| 538 |
-
fn=run_and_submit_all_evaluation,
|
| 539 |
-
inputs=[login_button],
|
| 540 |
-
outputs=[status_output, results_table]
|
| 541 |
-
)
|
| 542 |
-
|
| 543 |
-
# --- Application Startup & Shutdown Handling ---
|
| 544 |
-
if __name__ == "__main__":
|
| 545 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 546 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 547 |
-
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 548 |
-
|
| 549 |
-
if space_host_startup:
|
| 550 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 551 |
-
print(f" Runtime URL might be: https://{space_host_startup}")
|
| 552 |
-
else:
|
| 553 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 554 |
-
|
| 555 |
-
if space_id_startup:
|
| 556 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 557 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 558 |
-
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 559 |
-
else:
|
| 560 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 561 |
-
|
| 562 |
-
print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
|
| 563 |
-
print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
|
| 564 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 565 |
-
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 566 |
-
|
| 567 |
-
try:
|
| 568 |
-
demo.launch(debug=True, share=False)
|
| 569 |
-
finally:
|
| 570 |
-
loop_to_use = None
|
| 571 |
-
if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
|
| 572 |
-
loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
|
| 573 |
-
elif SHARED_HTTP_SESSION: # Fallback if agent not fully created but session was
|
| 574 |
-
loop_to_use = SHARED_HTTP_SESSION.loop
|
| 575 |
-
|
| 576 |
-
if loop_to_use and loop_to_use.is_running():
|
| 577 |
-
logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
|
| 578 |
-
try:
|
| 579 |
-
current_loop = asyncio.get_event_loop()
|
| 580 |
-
if current_loop is not loop_to_use and not loop_to_use.is_closed(): # Check if loop_to_use is not closed
|
| 581 |
-
asyncio.set_event_loop(loop_to_use)
|
| 582 |
-
|
| 583 |
-
if GLOBAL_CHUCK_AGENT:
|
| 584 |
-
loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
|
| 585 |
-
elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
|
| 586 |
-
loop_to_use.run_until_complete(close_shared_http_session())
|
| 587 |
-
except Exception as e: # Catch broader exceptions during cleanup
|
| 588 |
-
logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
|
| 589 |
-
else:
|
| 590 |
-
logger.info("No active HTTP session or running loop to close in finally block.")
|
|
|
|
| 28 |
QUESTIONS_URL_PATH = "/questions"
|
| 29 |
SUBMIT_URL_PATH = "/submit"
|
| 30 |
SCREENSHOTS_DIR = "screenshots"
|
| 31 |
+
OPENAI_MODEL_ID = "gpt-3.5-turbo"
|
| 32 |
SERPER_API_NUM_RESULTS = 3
|
| 33 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 34 |
+
AGENT_MAX_STEPS = 10
|
| 35 |
+
AGENT_VERBOSITY_LEVEL = 2 # Will attempt to set this via workaround
|
| 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`. Example: `search_results = await web_search(query="latest news on AI")\nprint(search_results)`
|
| 43 |
+
2. `calculator(expression: str) -> str`: Use this tool for any mathematical calculations. This tool is synchronous. Example: `result = calculator(expression="((1024 / 8) + 55 - 5) * 2")\nprint(result)`
|
| 44 |
+
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`. Example: `retrieval_status = await image_retriever(url="http://example.com/image.png")\nprint(retrieval_status)`. The tool returns a status message.
|
| 45 |
+
|
| 46 |
+
Follow this process for every question:
|
|
|
|
|
|
|
|
|
|
| 47 |
1. THOUGHT: Understand the user's question. Identify the core information needed.
|
| 48 |
2. THOUGHT: Decide if one of your available tools (`web_search`, `calculator`, `image_retriever`) can help obtain this information. If yes, state which tool you will use and what input you will provide to it. If no tool is needed, explain that you can answer directly.
|
| 49 |
3. CODE (if using a tool):
|
|
|
|
| 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.
|
|
|
|
| 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:
|
| 69 |
+
- 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.
|
| 70 |
+
- 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.
|
| 71 |
- 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.
|
| 72 |
- If the answer is a calculation result, provide just the number.
|
| 73 |
"""
|
|
|
|
| 105 |
|
| 106 |
# --- Tool Definitions ---
|
| 107 |
class ImageRetrievalTool(Tool):
|
| 108 |
+
name = "image_retriever"
|
| 109 |
description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
|
| 110 |
inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
|
| 111 |
output_type = "string"
|
| 112 |
+
is_async = True
|
| 113 |
|
| 114 |
def __init__(self, session: aiohttp.ClientSession):
|
| 115 |
super().__init__()
|
|
|
|
| 140 |
return f"Error retrieving image: {str(e)}"
|
| 141 |
|
| 142 |
class WebSearchTool(Tool):
|
| 143 |
+
name = "web_search"
|
| 144 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 145 |
inputs = {"query": {"type": "string", "description": "The search query to execute."}}
|
| 146 |
output_type = "string"
|
| 147 |
+
is_async = True
|
| 148 |
|
| 149 |
def __init__(self, session: aiohttp.ClientSession):
|
| 150 |
super().__init__()
|
|
|
|
| 193 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 194 |
|
| 195 |
class CalculatorTool(Tool):
|
| 196 |
+
name = "calculator"
|
| 197 |
description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
|
| 198 |
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
|
| 199 |
output_type = "string"
|
| 200 |
+
is_async = False
|
| 201 |
|
| 202 |
def __init__(self):
|
| 203 |
super().__init__()
|
|
|
|
| 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)
|
|
|
|
| 228 |
CalculatorTool(),
|
| 229 |
ImageRetrievalTool(session=http_session)
|
| 230 |
]
|
| 231 |
+
|
| 232 |
effective_model = model
|
| 233 |
if effective_model is None:
|
| 234 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
|
|
|
| 239 |
api_key=openai_api_key
|
| 240 |
)
|
| 241 |
|
| 242 |
+
# REINSTATED WORKAROUND for MultiStepAgent TypeError
|
| 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().__init__(**minimal_super_args)
|
| 252 |
+
logger.info("QuestionAnsweringAgent (CodeAgent) super().__init__ called with MINIMAL args (workaround active).")
|
| 253 |
+
|
| 254 |
+
# Explicitly set CodeAgent-specific attributes after init.
|
| 255 |
+
# This relies on CodeAgent using these instance attributes.
|
| 256 |
+
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
|
| 257 |
+
logger.info(f"Explicitly set self.system_prompt for CodeAgent.")
|
| 258 |
+
|
| 259 |
+
# These might be read-only or set internally in a way this doesn't override.
|
| 260 |
+
# We log a warning if the attribute doesn't exist to be set.
|
| 261 |
+
if hasattr(self, 'verbosity_level'):
|
| 262 |
+
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
|
| 263 |
+
logger.info(f"Set self.verbosity_level to: {self.verbosity_level}")
|
| 264 |
+
else:
|
| 265 |
+
logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
|
| 266 |
|
| 267 |
+
if hasattr(self, 'additional_authorized_imports'):
|
| 268 |
+
self.additional_authorized_imports = ["PIL"] # Make sure PIL is in requirements if needed
|
| 269 |
+
logger.info(f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
|
| 270 |
+
else:
|
| 271 |
+
logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
|
| 272 |
+
|
| 273 |
+
# The CodeWriter is crucial for CodeAgent. It's usually initialized within CodeAgent's __init__.
|
| 274 |
+
# If the minimal super call doesn't set it up, the agent might fail to generate code.
|
| 275 |
+
# This is a deeper aspect of the workaround's potential side effects.
|
| 276 |
+
if not hasattr(self, 'code_writer') or self.code_writer is None:
|
| 277 |
+
logger.warning("self.code_writer might not be initialized due to workaround. Agent may fail to generate code.")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
except TypeError as e:
|
| 281 |
+
logger.error(f"WORKAROUND FAILED: Still got TypeError during minimal super().__init__: {e}", exc_info=True)
|
| 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]:
|
| 288 |
reasoning_trace = "Agent execution started."
|
| 289 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 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]}...")
|
|
|
|
| 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 |
+
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 |
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:
|
| 326 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
|
|
|
|
| 347 |
asyncio.set_event_loop(self.loop)
|
| 348 |
|
| 349 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
| 350 |
+
self.agent = QuestionAnsweringAgent(http_session=self.http_session) # This might raise if the workaround fails
|
| 351 |
logger.info("ChuckAgent fully initialized")
|
| 352 |
|
| 353 |
def __call__(self, question: str) -> Tuple[str, str]:
|
|
|
|
| 364 |
except Exception as e:
|
| 365 |
error_msg = f"Error running ChuckAgent: {str(e)}"
|
| 366 |
logger.error(error_msg, exc_info=True)
|
| 367 |
+
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|