Spaces:
Sleeping
Sleeping
Add .env configuration, enhance app.py with async capabilities, and update requirements
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196import osimport gradio as grimport requestsimport inspectimport pandas as pd# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif profile:username= f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")return "Please Login to Hugging Face with the button.", Noneapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)# 2. Fetch Questionsprint(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()if not questions_data:print("Fetched questions list is empty.")return "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")print(f"Response text: {response.text[:500]}")return f"Error decoding server response for questions: {e}", Noneexcept Exception as e:print(f"An unexpected error occurred fetching questions: {e}")return f"An unexpected error occurred fetching questions: {e}", None# 3. Run your Agentresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})except Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:print("Agent did not produce any answers to submit.")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)# 4. Prepare Submissionsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."print(status_update)# 5. Submitprint(f"Submitting {len(answers_payload)} answers to: {submit_url}")try:response = requests.post(submit_url, json=submission_data, timeout=60)response.raise_for_status()result_data = response.json()final_status = (f"Submission Successful!\n"f"User: {result_data.get('username')}\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.')}")print("Submission successful.")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept requests.exceptions.HTTPError 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 requests.exceptions.JSONDecodeError:error_detail += f" Response: {e.response.text[:500]}"status_message = f"Submission Failed: {error_detail}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.Timeout:status_message = "Submission Failed: The request timed out."print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.RequestException as e:status_message = f"Submission Failed: Network error - {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept Exception as e:status_message = f"An unexpected error occurred during submission: {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_df# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:gr.Markdown("# Basic Agent Evaluation Runner")gr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**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 seperate action or even to answer the questions in async.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)# Removed max_rows=10 from DataFrame constructorresults_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(fn=run_and_submit_all,outputs=[status_output, results_table])if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")print(f" Runtime URL should be: https://{space_host_startup}.hf.space")else:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")print("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565"""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 thesequestions, submits the answers, and displays the results. It incorporatesasynchronous operations for API calls, structured logging, centralized errorhandling for API requests, a basic tool framework, and caching for questionsand tool calls.Configuration is loaded from a .env file."""import osimport loggingimport httpx # Asynchronous HTTP clientimport gradio as grimport pandas as pdfrom typing import Any, Dict, List, Tuple, Optional, Union, Callable # noqa: F401import timeimport re # For simple pattern matching in the agentfrom 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 .envformat="%(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 fileDEFAULT_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 overriderequest_timeout = timeoutif url.endswith("/questions"): # A bit simplistic, better to pass timeout explicitly if neededrequest_timeout = QUESTIONS_TIMEOUTelif url.endswith("/submit"):request_timeout = SUBMIT_TIMEOUTlogger.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, Noneexcept ValueError as e: # Handles json.JSONDecodeErrorlogger.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, Noneexcept 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_timeoutreturn 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 descriptionraise 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 aproduction 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 evalreturn 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 calculatorfor 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) -> resultself.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] = resultself.tool_usage_log.append(f"Used tool '{tool.name}' with input '{input_str}'. Result: '{result[:50]}...'")return resultexcept 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 Nonedef __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 calllogger.info(f"Agent received question (first 100 chars): {question[:100]}...")question_lower = question.lower()if ("calculate" in question_loweror ("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 = Noneif 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 answerelse: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 answerfixed_answer = "This is a default answer from the agent with tools and caching."logger.info(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerasync 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_cachelogger.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 environmentif 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_URLquestions_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}", Noneagent_code_url = (f"https://huggingface.co/spaces/{space_id}/tree/main"if space_idelse "Space ID not found (running locally or SPACE_ID not set)")logger.info(f"Agent code URL: {agent_code_url}")questions_data = Nonecurrent_time = time.time()# Use QUESTIONS_CACHE_DURATION_SECONDS from .envif (_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 .envfetched_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}", Noneif 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.", Nonequestions_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).", Noneanswers_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}")continuetask_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": "",})continuetry: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_dfsubmission_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 .envresult_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_dfif 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_dfelse: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 fortool selection and complex reasoning is still minimal and needs significant enhancementfor 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)
app.py+515-146