import os import gradio as gr import requests import pandas as pd import asyncio import re import json import logging import operator # Used by CalculatorTool import aiohttp from typing import Optional, Dict, Any, List, Tuple # Import necessary components from smolagents try: from smolagents import CodeAgent, Tool, OpenAIServerModel except ImportError: logging.error("Failed to import smolagents. Please ensure it is installed.") # Dummy classes for script parsing if smolagents is not installed class CodeAgent: pass class Tool: pass class OpenAIServerModel: pass from datetime import datetime # --- Configuration --- class AppConfig: DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" QUESTIONS_URL_PATH = "/questions" SUBMIT_URL_PATH = "/submit" SCREENSHOTS_DIR = "screenshots" OPENAI_MODEL_ID = "gpt-4o" SERPER_API_NUM_RESULTS = 3 WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000 AGENT_MAX_STEPS = 10 AGENT_VERBOSITY_LEVEL = 2 # Will attempt to set this via workaround 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. 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. When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed. Available Tools: 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)` 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)` 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. Follow this process for every question: 1. THOUGHT: Understand the user's question. Identify the core information needed. 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. 3. CODE (if using a tool): ```python # Your Python code to call ONE tool. # REMEMBER: Use `await` for `web_search` and `image_retriever`. # ALWAYS print the result of the tool call. # Example for web_search: # search_result = await web_search(query="some specific query") # print(search_result) # Example for calculator: # calc_result = calculator(expression="1+1") # print(calc_result) ``` 4. OBSERVATION: [The system will insert the printed output of your tool call here.] 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. 6. If you have the information, formulate the final answer according to the formatting rules. CRITICAL: Your *entire response* to the user for each turn must culminate in the final answer using this exact template on a new line: FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.] Formatting rules for the value in FINAL ANSWER: - 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. - 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. - 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. - If the answer is a calculation result, provide just the number. """ CONFIG = AppConfig() # --- Logging Setup --- logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # --- Utility Functions --- def ensure_dir_exists(directory_path: str): os.makedirs(directory_path, exist_ok=True) ensure_dir_exists(CONFIG.SCREENSHOTS_DIR) # --- HTTP Client Session Management --- SHARED_HTTP_SESSION: Optional[aiohttp.ClientSession] = None async def get_shared_http_session() -> aiohttp.ClientSession: global SHARED_HTTP_SESSION if SHARED_HTTP_SESSION is None or SHARED_HTTP_SESSION.closed: SHARED_HTTP_SESSION = aiohttp.ClientSession() logger.info("Created shared aiohttp.ClientSession.") return SHARED_HTTP_SESSION async def close_shared_http_session(): global SHARED_HTTP_SESSION if SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed: await SHARED_HTTP_SESSION.close() SHARED_HTTP_SESSION = None logger.info("Closed shared aiohttp.ClientSession.") # --- Tool Definitions --- class ImageRetrievalTool(Tool): name = "image_retriever" description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message." inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}} output_type = "string" is_async = True def __init__(self, session: aiohttp.ClientSession): super().__init__() self.image_memory: Dict[str, Dict[str, Any]] = {} self.screenshot_count = 0 self._session = session async def forward(self, url: str) -> str: logger.info(f"ImageRetrievalTool called with URL: {url}") try: async with self._session.get(url, timeout=aiohttp.ClientTimeout(total=20)) as response: response.raise_for_status() image_data = await response.read() image_id = f"image_{self.screenshot_count}" self.image_memory[image_id] = { 'data': image_data, 'url': url, 'timestamp': datetime.now().isoformat() } self.screenshot_count += 1 return f"Image retrieved successfully from {url}. Stored in memory as {image_id}." except asyncio.TimeoutError: logger.error(f"Timeout retrieving image {url}") return f"Error: Timeout retrieving image {url}." except aiohttp.ClientError as e: logger.error(f"ClientError retrieving image {url}: {type(e).__name__} - {str(e)}") return f"Error retrieving image (client error): {str(e)}" except Exception as e: logger.error(f"Unexpected error retrieving image {url}: {type(e).__name__} - {str(e)}") return f"Error retrieving image: {str(e)}" class WebSearchTool(Tool): name = "web_search" description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string." inputs = {"query": {"type": "string", "description": "The search query to execute."}} output_type = "string" is_async = True def __init__(self, session: aiohttp.ClientSession): super().__init__() self._session = session async def forward(self, query: str) -> str: logger.info(f"WebSearchTool called with query: {query}") serper_api_key = os.environ.get('SERPER_API_KEY') if not serper_api_key: logger.error("SERPER_API_KEY not found.") return "Error: Serper API key not found in environment." url = "https://google.serper.dev/search" headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'} payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS}) try: async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response: response.raise_for_status() data = await response.json() return self._format_results(data) except asyncio.TimeoutError: logger.error(f"Timeout performing search for '{query}'") return f"Error: Timeout during web search for '{query}'." except aiohttp.ClientError as e: logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}") return f"Error performing search (client error): {str(e)}" except Exception as e: logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}") return f"Error performing search: {str(e)}" def _format_results(self, data: Dict[str, Any]) -> str: results = [] if 'organic' in data and data['organic']: for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]: title = result.get('title', 'N/A') snippet = result.get('snippet', 'N/A') results.append(f"Title: {title}\nSnippet: {snippet}\n---") if not results and 'knowledgeGraph' in data: kg = data['knowledgeGraph'] title = kg.get('title', '') description = kg.get('description', '') if title or description: results.append(f"Knowledge Graph: {title}\n{description}\n---") formatted_output = "\n".join(results) if results else "No relevant search results found." return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH] class CalculatorTool(Tool): name = "calculator" description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string." inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}} output_type = "string" is_async = False def __init__(self): super().__init__() self.operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, '^': operator.pow } self.allowed_chars = "0123456789+-*/^(). " async def forward(self, expression: str) -> str: logger.info(f"CalculatorTool called with expression: {expression}") try: safe_expr = "".join(c for c in expression if c in self.allowed_chars) if not safe_expr: return "Error: Empty or invalid expression for calculator." result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore return f"Calculation result: {safe_expr} = {float(result)}" except Exception as e: logger.error(f"Error evaluating expression '{expression}': {str(e)}") return f"Error: Could not evaluate expression '{expression}'. Ensure it's a simple arithmetic expression." # --- Agent Definition --- class QuestionAnsweringAgent(CodeAgent): def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None): tools = [ WebSearchTool(session=http_session), CalculatorTool(), ImageRetrievalTool(session=http_session) ] effective_model = model if effective_model is None: openai_api_key = os.environ.get('OPENAI_API_KEY') if not openai_api_key: raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.") effective_model = OpenAIServerModel( model_id=CONFIG.OPENAI_MODEL_ID, api_key=openai_api_key ) # REINSTATED WORKAROUND for MultiStepAgent TypeError # Call super() with only arguments known/likely for MultiStepAgent minimal_super_args = { "model": effective_model, "tools": tools, "max_steps": CONFIG.AGENT_MAX_STEPS, # "code_writer": None, # If CodeAgent expects a code_writer to be passed to MultiStepAgent explicitly } try: super().__init__(**minimal_super_args) logger.info("QuestionAnsweringAgent (CodeAgent) super().__init__ called with MINIMAL args (workaround active).") # Explicitly set CodeAgent-specific attributes after init. # This relies on CodeAgent using these instance attributes. self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT logger.info(f"Explicitly set self.system_prompt for CodeAgent.") # These might be read-only or set internally in a way this doesn't override. # We log a warning if the attribute doesn't exist to be set. if hasattr(self, 'verbosity_level'): self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL logger.info(f"Set self.verbosity_level to: {self.verbosity_level}") else: logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.") if hasattr(self, 'additional_authorized_imports'): self.additional_authorized_imports = ["PIL"] # Make sure PIL is in requirements if needed logger.info(f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}") else: logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.") # The CodeWriter is crucial for CodeAgent. It's usually initialized within CodeAgent's __init__. # If the minimal super call doesn't set it up, the agent might fail to generate code. # This is a deeper aspect of the workaround's potential side effects. if not hasattr(self, 'code_writer') or self.code_writer is None: logger.warning("self.code_writer might not be initialized due to workaround. Agent may fail to generate code.") except TypeError as e: logger.error(f"WORKAROUND FAILED: Still got TypeError during minimal super().__init__: {e}", exc_info=True) raise e logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.") async def process_question(self, question_text: str) -> Tuple[str, str]: reasoning_trace = "Agent execution started." final_answer_for_submission = "Error: Agent did not produce a recognizable answer." try: logger.info(f"Processing question with CodeAgent: {question_text[:100]}...") raw_output_obj = self.run(question_text) if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string): full_agent_response = str(raw_output_obj.log_string()) elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None: full_agent_response = str(raw_output_obj.text) elif isinstance(raw_output_obj, str): full_agent_response = raw_output_obj elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None: full_agent_response = str(raw_output_obj.result) else: full_agent_response = str(raw_output_obj) reasoning_trace = full_agent_response logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...") match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL) if match: final_answer_for_submission = match.group(1).strip() logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}") else: logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.") final_answer_for_submission = full_agent_response.strip() if not final_answer_for_submission: logger.warning("Extracted final answer is empty. Defaulting to a placeholder.") final_answer_for_submission = "Could not determine answer." except TypeError as te: logger.error(f"TypeError during agent processing: {str(te)}", exc_info=True) final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}" reasoning_trace += f"\nTypeError encountered: {str(te)}" except Exception as e: logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True) final_answer_for_submission = f"Error in agent processing: {str(e)}" reasoning_trace += f"\nError encountered: {str(e)}" return final_answer_for_submission, reasoning_trace # --- Agent Adapter for Synchronous Use (e.g., Gradio) --- class ChuckAgent: def __init__(self): required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY'] missing_vars = [var for var in required_env_vars if not os.environ.get(var)] if missing_vars: error_msg = f"Missing required environment variables: {', '.join(missing_vars)}" logger.critical(error_msg) raise EnvironmentError(error_msg) logger.info("ChuckAgent initialization started") try: self.loop = asyncio.get_running_loop() except RuntimeError: self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.http_session = self.loop.run_until_complete(get_shared_http_session()) self.agent = QuestionAnsweringAgent(http_session=self.http_session) # This might raise if the workaround fails logger.info("ChuckAgent fully initialized") def __call__(self, question: str) -> Tuple[str, str]: logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...") try: if asyncio.get_event_loop() is not self.loop: asyncio.set_event_loop(self.loop) final_answer, reasoning_trace = self.loop.run_until_complete( self.agent.process_question(question) ) logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...") return final_answer, reasoning_trace except Exception as e: error_msg = f"Error running ChuckAgent: {str(e)}" logger.error(error_msg, exc_info=True) return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}" async def shutdown(self): logger.info("ChuckAgent shutting down...") await close_shared_http_session() logger.info("ChuckAgent shutdown complete.") # --- Core Evaluation Logic --- def get_space_id_agent_code_url() -> Tuple[Optional[str], str]: space_id = os.getenv("SPACE_ID") 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)" return space_id, agent_code_url def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]: questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}" logger.info(f"Fetching questions from: {questions_url}") try: response = requests.get(questions_url, timeout=30) response.raise_for_status() questions_data = response.json() if not questions_data or not isinstance(questions_data, list): logger.warning(f"Fetched questions empty or invalid: {questions_data}") raise ValueError("Fetched questions list is empty or not a list.") logger.info(f"Fetched {len(questions_data)} questions.") return questions_data except requests.exceptions.RequestException as e: logger.error(f"Error fetching questions: {e}", exc_info=True) raise ConnectionError(f"Error fetching questions: {e}") from e except (requests.exceptions.JSONDecodeError, ValueError) as e: logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True) raise ValueError(f"Error decoding server response for questions: {e}") from e def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: answers_payload = [] results_log = [] logger.info(f"Running agent on {len(questions_data)} questions...") for i, item in enumerate(questions_data): 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 {i+1} with missing data: {item}") continue logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}") model_ans, reasoning = "Error: Agent did not run", "No reasoning generated." try: model_ans, reasoning = agent(question_text) except Exception as e: logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True) model_ans = f"AGENT_CALL_ERROR: {e}" reasoning = str(e) payload_item = {"task_id": task_id, "submitted_answer": model_ans} if reasoning: payload_item["reasoning_trace"] = reasoning answers_payload.append(payload_item) results_log.append({ "Task ID": task_id, "Question": question_text, "Submitted Answer": model_ans, "Reasoning Trace": reasoning }) return answers_payload, results_log def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str: if not answers_payload: logger.warning("Agent did not produce any answers to submit.") return "Agent did not produce any answers to submit." submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}" submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload} logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...") try: response = requests.post(submit_url, json=submission_data, timeout=60) response.raise_for_status() result_data = response.json() return ( f"Submission Successful!\nUser: {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.')}" ) except requests.exceptions.HTTPError as e: error_detail = f"Server responded with {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" Raw Response: {e.response.text[:500]}" logger.error(f"Submission Failed: {error_detail}") return f"Submission Failed: {error_detail}" except requests.exceptions.Timeout: logger.error("Submission Failed: The request timed out.") return "Submission Failed: The request timed out." except requests.exceptions.RequestException as e: logger.error(f"Submission Failed: Network error - {e}", exc_info=True) return f"Submission Failed: Network error - {e}" except Exception as e: logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True) return f"An unexpected error occurred during submission: {e}" # --- Gradio Interface Main Function --- GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]: global GLOBAL_CHUCK_AGENT logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}") if args: logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}") if not isinstance(profile, gr.OAuthProfile) and profile is not None: logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}") found_profile_in_args = False for arg_val in args: if isinstance(arg_val, gr.OAuthProfile): profile = arg_val found_profile_in_args = True logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}") break if not found_profile_in_args and profile is None: logger.error("Could not identify a valid gr.OAuthProfile object.") return "Login error: Could not identify user profile.", pd.DataFrame() logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}") if not profile: logger.warning("User not logged in for evaluation.") return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame() username = profile.username logger.info(f"User logged in: {username}") _, agent_code_url = get_space_id_agent_code_url() logger.info(f"Agent code URL: {agent_code_url}") results_log_data: List[Dict[str, Any]] = [] try: if GLOBAL_CHUCK_AGENT is None: GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated agent_instance = GLOBAL_CHUCK_AGENT except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init logger.critical(f"Agent instantiation failed due to missing env vars: {e}") return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame() except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError we're fixing logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True) return f"Error initializing agent: {e}", pd.DataFrame() try: questions_data = fetch_questions(CONFIG.DEFAULT_API_URL) answers_payload, results_log_data = process_all_questions(agent_instance, questions_data) submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload) except (ConnectionError, ValueError) as e: submission_status = str(e) except Exception as e: logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True) submission_status = f"An unexpected error occurred: {e}" results_df = pd.DataFrame(results_log_data if results_log_data else []) return submission_status, results_df # --- Build Gradio Interface --- 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. """ ) gr.Markdown( """ **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. """ ) gr.Markdown( f""" --- **Technical Notes:** * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches. * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets. * `requirements.txt` should specify a compatible `gradio` version (e.g., `gradio==4.29.0` or `gradio==4.44.1`). * The current `smolagents` version might have an internal issue with `CodeAgent` initialization. A workaround is active. """ ) login_button = gr.LoginButton() run_button = gr.Button("Run Evaluation & Submit All Answers") status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False) results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) run_button.click( fn=run_and_submit_all_evaluation, inputs=[login_button], outputs=[status_output, results_table] ) # --- Application Startup & Shutdown Handling --- if __name__ == "__main__": print("\n" + "-"*30 + " App Starting " + "-"*30) space_host_startup = os.getenv("SPACE_HOST") space_id_startup, agent_url_startup = get_space_id_agent_code_url() if space_host_startup: print(f"✅ SPACE_HOST found: {space_host_startup}") print(f" Runtime URL might be: https://{space_host_startup}") else: print("ℹ️ SPACE_HOST environment variable not found (running locally?).") if space_id_startup: print(f"✅ SPACE_ID found: {space_id_startup}") print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") print(f" Agent Code URL reported to server: {agent_url_startup}") else: print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.") print(f" Default API URL: {CONFIG.DEFAULT_API_URL}") print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}") print("-"*(60 + len(" App Starting ")) + "\n") print("Launching Gradio Interface for Chuck Agent Evaluation...") try: demo.launch(debug=True, share=False) finally: loop_to_use = None if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session: loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop elif SHARED_HTTP_SESSION: loop_to_use = SHARED_HTTP_SESSION.loop if loop_to_use and loop_to_use.is_running(): logger.info("Attempting to shutdown agent and close HTTP session in finally block...") try: current_loop = asyncio.get_event_loop_policy().get_event_loop() # More robust way to get current loop if current_loop is not loop_to_use and not loop_to_use.is_closed(): asyncio.set_event_loop(loop_to_use) if GLOBAL_CHUCK_AGENT: loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown()) elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed: loop_to_use.run_until_complete(close_shared_http_session()) except Exception as e: logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True) else: logger.info("No active HTTP session or running loop to close in finally block.")