Spaces:
Sleeping
Sleeping
File size: 23,168 Bytes
36e7caa 10e9b7d 36e7caa 10e9b7d 3c4371f 36e7caa 10e9b7d e80aab9 31243f4 36e7caa 31243f4 36e7caa 31243f4 4021bf3 36e7caa 31243f4 36e7caa 31243f4 36e7caa 3c4371f 36e7caa 7e4a06b 36e7caa 7e4a06b 36e7caa 7d65c66 3c4371f 36e7caa e80aab9 36e7caa 31243f4 36e7caa 31243f4 36e7caa 31243f4 36e7caa 31243f4 36e7caa e80aab9 36e7caa e80aab9 36e7caa e80aab9 36e7caa 0ee0419 e514fd7 36e7caa e514fd7 36e7caa e514fd7 e80aab9 7e4a06b 31243f4 36e7caa e80aab9 36e7caa e80aab9 36e7caa 3c4371f 36e7caa 7d65c66 3c4371f 36e7caa 3c4371f 36e7caa 7d65c66 36e7caa 7d65c66 36e7caa 7d65c66 36e7caa 3c4371f 36e7caa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | """
Module for running an agent evaluation using Gradio.
This script defines a `BasicAgent` with tool usage capabilities and caching,
fetches questions from a remote API (with caching), runs the agent on these
questions, submits the answers, and displays the results. It incorporates
asynchronous operations for API calls, structured logging, centralized error
handling for API requests, a basic tool framework, and caching for questions
and tool calls.
Configuration is loaded from a .env file.
"""
import os
import logging
import httpx # Asynchronous HTTP client
import gradio as gr
import pandas as pd
from typing import Any, Dict, List, Tuple, Optional, Union, Callable # noqa: F401
import time
import re # For simple pattern matching in the agent
from dotenv import load_dotenv # Import the dotenv library
# --- Load Environment Variables ---
# Load environment variables from a .env file in the same directory
# This should be one of the first things your script does.
load_dotenv()
# --- Logging Configuration ---
logging.basicConfig(
level=os.getenv(
"LOG_LEVEL", "INFO"
).upper(), # Allow configuring log level via .env
format="%(asctime)s - %(levelname)s - %(module)s - %(funcName)s - %(message)s",
handlers=[logging.StreamHandler()],
)
logger = logging.getLogger(__name__)
# --- Constants (Loaded from Environment Variables) ---
# Ensure these variable names match what you have in your .env file
DEFAULT_API_URL = os.getenv(
"DEFAULT_API_URL", "https://agents-course-unit4-scoring.hf.space"
)
QUESTIONS_TIMEOUT = float(os.getenv("QUESTIONS_TIMEOUT", 40.0))
SUBMIT_TIMEOUT = float(os.getenv("SUBMIT_TIMEOUT", 120.0))
QUESTIONS_CACHE_DURATION_SECONDS = int(
os.getenv("QUESTIONS_CACHE_DURATION_SECONDS", 10 * 60)
)
# HF_TOKEN will be automatically picked up by huggingface_hub library if set in .env
# and loaded by load_dotenv(), or if huggingface-cli login was used.
logger.info(f"DEFAULT_API_URL set to: {DEFAULT_API_URL}")
logger.info(f"QUESTIONS_TIMEOUT set to: {QUESTIONS_TIMEOUT}")
logger.info(f"SUBMIT_TIMEOUT set to: {SUBMIT_TIMEOUT}")
logger.info(
f"QUESTIONS_CACHE_DURATION_SECONDS set to: {QUESTIONS_CACHE_DURATION_SECONDS}"
)
# --- Caching Variables ---
# In-memory cache for questions: {"timestamp": float, "data": List[Dict]}
_questions_cache: Dict[str, Any] = {"timestamp": 0.0, "data": None}
# --- API Request Helper ---
async def _make_api_request_async(
method: str,
url: str,
client: httpx.AsyncClient,
json_payload: Optional[Dict[str, Any]] = None,
timeout: float = 10.0, # Default timeout for individual requests
) -> Tuple[Optional[Any], Optional[str]]:
"""
Makes an asynchronous API request and handles common errors.
Returns the JSON response (or raw text if JSON decoding fails but request was 'successful' text-wise)
"""
try:
# Use the globally configured timeouts if the specific call doesn't override
request_timeout = timeout
if url.endswith(
"/questions"
): # A bit simplistic, better to pass timeout explicitly if needed
request_timeout = QUESTIONS_TIMEOUT
elif url.endswith("/submit"):
request_timeout = SUBMIT_TIMEOUT
logger.info(
f"Making {method} request to {url} with timeout {request_timeout}s."
)
if json_payload:
logger.debug(
f"Request payload (first 200 chars): {str(json_payload)[:200]}"
)
response = await client.request(
method, url, json=json_payload, timeout=request_timeout
)
response.raise_for_status()
try:
response_data = response.json()
logger.info(f"Successfully received and parsed JSON response from {url}.")
logger.debug(f"Response data (first 200 chars): {str(response_data)[:200]}")
return response_data, None
except ValueError as e: # Handles json.JSONDecodeError
logger.warning(
f"Could not decode JSON from {url}, but request was successful (status {response.status_code}). "
f"Returning raw text. Error: {e}"
)
return response.text, None
except httpx.HTTPStatusError as e:
error_detail = f"Server responded with status {e.response.status_code}."
try:
error_json = e.response.json()
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except ValueError:
error_detail += f" Response: {e.response.text[:500]}"
logger.error(f"HTTP error for {url}: {error_detail}", exc_info=True)
return None, f"API request failed: {error_detail}"
except httpx.TimeoutException:
logger.error(
f"Request to {url} timed out.", exc_info=True
) # Timeout value is in request_timeout
return None, "API request timed out."
except httpx.RequestError as e:
logger.error(f"Network error during request to {url}: {e}", exc_info=True)
return None, f"API request failed due to a network error: {e}"
except Exception as e:
logger.error(
f"An unexpected error occurred during API request to {url}: {e}",
exc_info=True,
)
return None, f"An unexpected error occurred: {e}"
# --- Tool Definition ---
class Tool:
"""
Abstract base class for tools that an agent can use.
"""
name: str = "BaseTool"
description: str = "This is a base tool."
def __init__(self):
if self.name == "BaseTool": # Ensure child classes define name and description
raise NotImplementedError(
"Tool subclasses must define 'name' and 'description'."
)
def execute(self, input_str: str) -> str:
"""
Executes the tool with the given input string.
Args:
input_str: The input to the tool.
Returns:
A string representing the tool's output.
"""
raise NotImplementedError(
"Tool subclasses must implement the 'execute' method."
)
def __str__(self) -> str:
return f"{self.name}: {self.description}"
class CalculatorTool(Tool):
"""
A tool for evaluating simple arithmetic expressions.
WARNING: This tool uses eval(), which is NOT SAFE for untrusted input in a
production environment. Use a safer expression parser for real applications.
"""
name: str = "Calculator"
description: str = (
"Useful for evaluating simple arithmetic expressions. "
"Input should be a valid Python evaluable string like '2+2' or '(5*3)/2'."
)
def execute(self, input_str: str) -> str:
"""
Evaluates the given arithmetic expression string.
Args:
input_str: The arithmetic expression (e.g., "2+2").
Returns:
The result of the calculation as a string, or an error message.
"""
try:
# Sanitize input slightly: allow numbers, basic operators, parentheses.
# This is NOT a replacement for a proper secure parser.
if not re.match(r"^[0-9+\-*/().\s]+$", input_str):
return "Error: Invalid characters in input. Only numbers and basic operators (+-*/().) are allowed."
# WARNING: eval() is dangerous with untrusted input.
# This is for demonstration purposes only.
# In a real application, use a library like 'asteval' or 'numexpr'.
result = eval(input_str, {"__builtins__": {}}, {}) # Restricted eval
return str(result)
except Exception as e:
logger.warning(
f"CalculatorTool error evaluating '{input_str}': {e}", exc_info=True
)
return f"Error: Could not evaluate expression '{input_str}'. Reason: {e}"
# --- Basic Agent Definition ---
class BasicAgent:
"""
A simple agent that can use tools and caches their results.
Its primary response is fixed, but it attempts to use a calculator
for questions that appear to be calculations.
"""
def __init__(self, tools: Optional[List[Tool]] = None):
"""
Initializes the BasicAgent.
Args:
tools: A list of tools the agent can use.
"""
logger.info("BasicAgent initialized.")
self.tools = tools if tools else []
self._tool_call_cache: Dict[
Tuple[str, str], str
] = {} # Cache for tool calls: (tool_name, input_str) -> result
self.tool_usage_log: List[str] = []
def _use_tool(self, tool_name: str, input_str: str) -> Optional[str]:
"""
Uses a specified tool and caches the result.
Args:
tool_name: The name of the tool to use.
input_str: The input string for the tool.
Returns:
The tool's output string, or None if the tool is not found or fails.
"""
cache_key = (tool_name, input_str)
if cache_key in self._tool_call_cache:
logger.info(
f"Using cached result for tool '{tool_name}' with input '{input_str}'."
)
return self._tool_call_cache[cache_key]
for tool in self.tools:
if tool.name == tool_name:
try:
logger.info(f"Executing tool '{tool_name}' with input: {input_str}")
result = tool.execute(input_str)
self._tool_call_cache[cache_key] = result
self.tool_usage_log.append(
f"Used tool '{tool.name}' with input '{input_str}'. Result: '{result[:50]}...'"
)
return result
except Exception as e:
logger.error(
f"Error executing tool {tool_name}: {e}", exc_info=True
)
self.tool_usage_log.append(
f"Error using tool '{tool.name}' with input '{input_str}': {e}"
)
return f"Error executing {tool_name}: {e}"
logger.warning(f"Tool '{tool_name}' not found.")
return None
def __call__(self, question: str) -> str:
"""
Processes a question and returns an answer.
Attempts to use the CalculatorTool if the question looks like a calculation.
"""
self.tool_usage_log = [] # Reset log for this call
logger.info(f"Agent received question (first 100 chars): {question[:100]}...")
question_lower = question.lower()
if (
"calculate" in question_lower
or ("what is" in question_lower and re.search(r"\d", question))
or re.match(r"^\s*[\d\s()+\-*/.]+\??\s*$", question_lower)
):
match = re.search(r"calculate\s*(.*)", question_lower)
expr_to_calc = None
if match:
expr_to_calc = match.group(1).strip()
else:
match = re.search(r"what is\s*(.*)", question_lower)
if match:
expr_to_calc = match.group(1).replace("?", "").strip()
elif re.match(r"^\s*[\d\s()+\-*/.]+\??\s*$", question_lower):
expr_to_calc = question.replace("?", "").strip()
if expr_to_calc:
logger.info(
f"Attempting to use CalculatorTool for expression: '{expr_to_calc}'"
)
calc_result = self._use_tool("Calculator", expr_to_calc)
if calc_result:
if "Error:" not in calc_result:
answer = f"The calculation result for '{expr_to_calc}' is {calc_result}."
logger.info(
f"Agent returning calculator-based answer: {answer}"
)
return answer
else:
logger.warning(
f"CalculatorTool returned an error: {calc_result}"
)
answer = f"I tried to calculate '{expr_to_calc}', but encountered an issue: {calc_result}. My default response is: This is a default answer."
logger.info(f"Agent returning error-fallback answer: {answer}")
return answer
fixed_answer = "This is a default answer from the agent with tools and caching."
logger.info(f"Agent returning fixed answer: {fixed_answer}")
return fixed_answer
async def run_and_submit_all(
profile: Optional[gr.OAuthProfile],
) -> Tuple[str, Optional[pd.DataFrame]]:
"""
Asynchronously fetches questions (with caching), runs the BasicAgent on them,
submits all answers, and displays the results.
"""
global _questions_cache
logger.info("Starting 'run_and_submit_all' process.")
results_log_list: List[Dict[str, Any]] = []
space_id = os.getenv("SPACE_ID") # This is usually set by the HF Space environment
if profile:
username = f"{profile.username}"
logger.info(f"User logged in: {username}")
else:
# If HF_TOKEN is set in .env, Gradio might still pick it up for local debugging
# but profile object will be None if not in a Space or if login fails.
# The huggingface_hub library itself will use HF_TOKEN if available.
# For this script's logic, we rely on the profile object for username.
logger.warning("User not logged in via Gradio. Aborting evaluation.")
return "Please Login to Hugging Face with the button.", None
# API URLs are now loaded from .env via DEFAULT_API_URL
questions_url = f"{DEFAULT_API_URL}/questions"
submit_url = f"{DEFAULT_API_URL}/submit"
async with httpx.AsyncClient() as client:
try:
calculator = CalculatorTool()
agent = BasicAgent(tools=[calculator])
except Exception as e:
logger.error(f"Error instantiating agent or tools: {e}", exc_info=True)
return f"Error initializing agent/tools: {e}", None
agent_code_url = (
f"https://huggingface.co/spaces/{space_id}/tree/main"
if space_id
else "Space ID not found (running locally or SPACE_ID not set)"
)
logger.info(f"Agent code URL: {agent_code_url}")
questions_data = None
current_time = time.time()
# Use QUESTIONS_CACHE_DURATION_SECONDS from .env
if (
_questions_cache["data"]
and (current_time - _questions_cache["timestamp"])
< QUESTIONS_CACHE_DURATION_SECONDS
):
logger.info("Using cached questions.")
questions_data = _questions_cache["data"]
else:
logger.info(f"Fetching fresh questions from: {questions_url}")
# _make_api_request_async will use QUESTIONS_TIMEOUT from .env
fetched_data, error_msg = await _make_api_request_async(
"GET",
questions_url,
client, # Timeout is handled within _make_api_request_async
)
if error_msg:
logger.error(f"Failed to fetch questions: {error_msg}")
return f"Error fetching questions: {error_msg}", None
if not fetched_data or not isinstance(fetched_data, list):
logger.error(
f"Fetched questions list is empty or invalid format. Data: {fetched_data}"
)
return "Fetched questions list is empty or invalid format.", None
questions_data = fetched_data
_questions_cache = {"timestamp": current_time, "data": questions_data}
logger.info(f"Fetched and cached {len(questions_data)} questions.")
if not questions_data:
return "Failed to obtain questions (either from cache or API).", None
answers_payload: List[Dict[str, Any]] = []
logger.info(f"Running agent on {len(questions_data)} questions...")
for item in questions_data:
if not isinstance(item, dict):
logger.warning(f"Skipping invalid item in questions_data: {item}")
continue
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
logger.warning(
f"Skipping item with missing task_id or question: {item}"
)
results_log_list.append(
{
"Task ID": task_id or "N/A",
"Question": question_text or "N/A",
"Submitted Answer": "SKIPPED - Missing data",
"Tool Log": "",
}
)
continue
try:
submitted_answer = agent(question_text)
answers_payload.append(
{"task_id": task_id, "submitted_answer": submitted_answer}
)
results_log_list.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": submitted_answer,
"Tool Log": "; ".join(agent.tool_usage_log),
}
)
except Exception as e:
logger.error(
f"Error running agent on task {task_id}: {e}", exc_info=True
)
results_log_list.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": f"AGENT ERROR: {e}",
"Tool Log": "; ".join(agent.tool_usage_log),
}
)
results_df = pd.DataFrame(results_log_list)
if not answers_payload:
logger.warning("Agent did not produce any answers to submit.")
return "Agent did not produce any answers to submit.", results_df
submission_data = {
"username": username.strip(),
"agent_code": agent_code_url,
"answers": answers_payload,
}
status_update = (
f"Agent finished processing {len(results_log_list)} questions. "
f"Submitting {len(answers_payload)} answers for user '{username}'..."
)
logger.info(status_update)
logger.info(f"Submitting {len(answers_payload)} answers to: {submit_url}")
# _make_api_request_async will use SUBMIT_TIMEOUT from .env
result_data, error_msg = await _make_api_request_async(
"POST",
submit_url,
client,
json_payload=submission_data, # Timeout handled within
)
if error_msg:
logger.error(f"Submission failed: {error_msg}")
return f"Submission Failed: {error_msg}", results_df
if result_data and isinstance(result_data, dict):
final_status = (
f"Submission Successful!\n"
f"User: {result_data.get('username', 'N/A')}\n"
f"Overall Score: {result_data.get('score', 'N/A')}% "
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
f"Message: {result_data.get('message', 'No message received.')}"
)
logger.info("Submission successful. Result: %s", result_data)
return final_status, results_df
else:
logger.error(
f"Submission response was not in expected format. Data: {result_data}"
)
return (
"Submission completed, but response format was unexpected.",
results_df,
)
# --- Build Gradio Interface using Blocks ---
with gr.Blocks(
css=".gradio-container { max-width: 1024px !important; margin: auto !important; }"
) as demo:
gr.Markdown("# Agent Evaluation Runner (with .env Configuration, Tools & Caching)")
gr.Markdown(
"""
**Instructions:**
1. Ensure your `.env` file is in the same directory as this script and contains `HF_TOKEN`, `DEFAULT_API_URL`, etc.
2. Modify the `BasicAgent` class and `Tool` implementations to define your agent's logic.
*The current `CalculatorTool` uses `eval()` which is unsafe for production.*
3. Log in to your Hugging Face account using the button below (mocked locally if `HF_TOKEN` or `huggingface-cli login` is used).
4. Click 'Run Evaluation & Submit All Answers'. Questions are cached based on `QUESTIONS_CACHE_DURATION_SECONDS` in your `.env`.
---
**Disclaimers:**
This version includes a basic tool framework and caching. The agent's intelligence for
tool selection and complex reasoning is still minimal and needs significant enhancement
for benchmarks like GAIA.
"""
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(
label="Run Status / Submission Result", lines=5, interactive=False
)
results_table = gr.DataFrame(
label="Questions, Agent Answers, and Tool Log",
wrap=True,
headers=["Task ID", "Question", "Submitted Answer", "Tool Log"],
)
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
if __name__ == "__main__":
logger.info("\n" + "-" * 30 + " App Starting " + "-" * 30)
# SPACE_ID and SPACE_HOST are typically set by the Hugging Face Spaces environment
# If running locally, these might be None, which is handled where they are used.
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID")
if space_host_startup:
logger.info(f"✅ SPACE_HOST found: {space_host_startup}")
logger.info(f" Runtime URL should be: https://{space_host_startup}.hf.space")
else:
logger.info(
"ℹ️ SPACE_HOST environment variable not found (normal if running locally)."
)
if space_id_startup:
logger.info(f"✅ SPACE_ID found: {space_id_startup}")
logger.info(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
else:
logger.info(
"ℹ️ SPACE_ID environment variable not found (normal if running locally)."
)
# Check if HF_TOKEN is loaded (optional check, as huggingface_hub handles it)
if os.getenv("HF_TOKEN"):
logger.info("✅ HF_TOKEN environment variable is loaded.")
else:
logger.warning(
"⚠️ HF_TOKEN environment variable is NOT loaded. Ensure it's in your .env file or you've used `huggingface-cli login` for local debugging with OAuth features."
)
logger.info("-" * (60 + len(" App Starting ")) + "\n")
logger.info("Launching Gradio Interface...")
demo.launch(debug=True, share=False)
|