""" 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)