GoodLuckChuck's picture
Update app.py
bda7196 verified
Raw History Blame
29.9 kB
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.")
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-3.5-turbo" # Defaulting to faster/cheaper model
SERPER_API_NUM_RESULTS = 3
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
AGENT_MAX_STEPS = 10
AGENT_VERBOSITY_LEVEL = 2
AGENT_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
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 images from web pages. Input is a URL to an image. Returns a success/error message."
inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
output_type = "string"
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 = "Performs web searches using Serper API to find information. Input is a search query."
inputs = {"query": {"type": "string", "description": "The search query to execute"}}
output_type = "string"
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 is a mathematical expression string (e.g., '2+2*5')."
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate"}}
output_type = "string"
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
)
# Call super() with ONLY arguments known to be core for MultiStepAgent
# We will lose system_prompt, verbosity, and additional_imports for now,
# which will likely make the agent not perform as intended, but this is
# to see if the base MultiStepAgent initializes.
try:
super().__init__(
model=effective_model,
tools=tools,
max_steps=CONFIG.AGENT_MAX_STEPS
# system_prompt IS DELIBERATELY OMITTED for this test
# verbosity_level IS DELIBERATELY OMITTED for this test
# additional_authorized_imports IS DELIBERATELY OMITTED for this test
)
logger.info("QuestionAnsweringAgent (CodeAgent) super().__init__ called with minimal args.")
# If the above works, CodeAgent is initialized but might not have its specific settings.
# We can try to set them now if they are attributes.
# This depends on CodeAgent's internal design.
if hasattr(self, 'system_prompt'):
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
logger.info(f"Set self.system_prompt to: {self.system_prompt[:50]}...")
else:
logger.warning("CodeAgent instance does not have attribute 'system_prompt' to set after init.")
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("CodeAgent instance does not have attribute 'verbosity_level' to set after init.")
if hasattr(self, 'additional_authorized_imports'):
self.additional_authorized_imports = ["PIL"]
logger.info(f"Set self.additional_authorized_imports to: {self.additional_authorized_imports}")
else:
logger.warning("CodeAgent instance does not have attribute 'additional_authorized_imports' to set after init.")
except TypeError as e:
logger.error(f"Still got TypeError during minimal super().__init__: {e}", exc_info=True)
# This would mean even model, tools, or max_steps is an issue for MultiStepAgent's init
# or CodeAgent itself requires more in its direct init before calling super.
raise e # re-raise the error
logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
async def process_question(self, question_text: str) -> Tuple[str, str]:
"""Processes a question and returns the final answer and reasoning trace."""
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]}...")
# MODIFICATION: Removed 'await' if self.run() is not async
# This assumes self.run() returns an object that can be converted to string,
# or an object that CodeAgent expects. If self.run() is truly async,
# then AgentText might be an intermediate result not meant to be awaited directly.
raw_output_obj = self.run(question_text)
# Convert raw_output_obj to string. This might need adjustment
# depending on what self.run() actually returns (e.g., AgentText might have a .text property)
if hasattr(raw_output_obj, 'text'): # Common pattern for such objects
full_agent_response = str(raw_output_obj.text)
elif isinstance(raw_output_obj, str):
full_agent_response = raw_output_obj
else: # Fallback, try to stringify directly
full_agent_response = str(raw_output_obj)
reasoning_trace = full_agent_response # Use the full response as the trace
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 (may be incorrect for submission).")
final_answer_for_submission = full_agent_response.strip()
if not final_answer_for_submission: # If empty after stripping
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
final_answer_for_submission = "Could not determine answer."
except TypeError as te: # Catching the specific TypeError first
logger.error(f"TypeError during agent processing (likely self.run call): {str(te)}", exc_info=True)
final_answer_for_submission = f"Error in agent processing: {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)
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]]]:
# ... (other code remains the same) ...
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)
# MODIFICATION: Renamed 'model_answer' to 'submitted_answer' for the payload
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
if reasoning: # Add reasoning_trace if it's available and not empty
payload_item["reasoning_trace"] = reasoning
answers_payload.append(payload_item)
results_log.append({
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": model_ans, # This key is for your display df, can be different
"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
# MODIFIED: Added *args to catch unexpected additional arguments
# and ensure 'profile' is keyword-or-positional
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
global GLOBAL_CHUCK_AGENT
# Log what was actually received
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}")
# The actual profile data should come from the named 'profile' argument
# due to the 'inputs=[login_button]' mapping.
# If 'profile' is None here but args contains something, it's an issue.
if not isinstance(profile, gr.OAuthProfile) and profile is not None:
# This can happen if Gradio passes something unexpected as the first argument.
# We could try to see if the profile is in args, but it should be the named parameter.
logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
# Attempt to find the profile in args if it was misplaced
found_profile_in_args = False
for arg in args:
if isinstance(arg, gr.OAuthProfile):
profile = arg
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: # if profile was not None but wrong type, it will still fail below
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: # This check remains important
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
# ... rest of your function code ...
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()
agent = GLOBAL_CHUCK_AGENT
except EnvironmentError as e:
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:
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, 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 ---
# This is the UI part that was adjusted to look more like the screenshot
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 `gradio>=4.19.2` or newer.
* Consider trying `OPENAI_MODEL_ID = "gpt-3.5-turbo"` (current default) or `"gpt-4"` in the script for different performance/capability.
"""
)
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}") # For visibility
print("-"*(60 + len(" App Starting ")) + "\n")
print("Launching Gradio Interface for Chuck Agent Evaluation...")
try:
demo.launch(debug=True, share=False)
finally:
# Attempt to gracefully close the aiohttp session on exit
# This part is a bit tricky with how Gradio's launch() blocks
# and how different environments handle script termination.
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...")
# Ensure we are using the correct event loop that the session was created with.
# This can be complex if multiple loops were involved or if the main loop closed.
try:
current_loop = asyncio.get_event_loop()
if current_loop is not loop_to_use:
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: # Fallback
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 loop to close in finally block.")