File size: 24,977 Bytes
10e9b7d
 
eccf8e4
3c4371f
8ab0ff1
 
 
 
 
 
 
10e9b7d
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
31243f4
8ab0ff1
 
 
 
 
 
 
3c4371f
8ab0ff1
 
 
 
 
 
 
 
 
 
 
e80aab9
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eccf8e4
8ab0ff1
7d65c66
31243f4
8ab0ff1
 
 
 
 
e80aab9
8ab0ff1
 
 
 
 
e80aab9
8ab0ff1
7d65c66
8ab0ff1
 
 
31243f4
 
 
8ab0ff1
31243f4
8ab0ff1
 
31243f4
8ab0ff1
31243f4
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
31243f4
8ab0ff1
31243f4
8ab0ff1
 
e80aab9
8ab0ff1
 
 
e80aab9
7d65c66
e80aab9
 
8ab0ff1
 
3c4371f
 
 
e80aab9
 
8ab0ff1
e80aab9
 
3c4371f
e80aab9
8ab0ff1
 
 
3c4371f
8ab0ff1
 
e80aab9
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d65c66
8ab0ff1
 
e80aab9
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
e80aab9
8ab0ff1
 
e80aab9
31243f4
8ab0ff1
0ee0419
e514fd7
 
8ab0ff1
 
 
 
 
e514fd7
8ab0ff1
 
 
 
 
 
 
 
e514fd7
8ab0ff1
 
 
 
 
e514fd7
e80aab9
 
8ab0ff1
31243f4
8ab0ff1
 
e80aab9
31243f4
8ab0ff1
 
31243f4
e80aab9
 
8ab0ff1
e80aab9
3c4371f
 
8ab0ff1
7d65c66
3c4371f
 
8ab0ff1
3c4371f
7d65c66
 
8ab0ff1
7d65c66
 
8ab0ff1
7d65c66
 
8ab0ff1
 
 
3c4371f
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c4371f
8ab0ff1
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
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
            )

        super().__init__(
            tools=tools,
            model=effective_model,
            system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
            additional_authorized_imports=["PIL"],
            max_steps=CONFIG.AGENT_MAX_STEPS,
            verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
        )
        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 = await self.run(question_text)
            full_agent_response = str(raw_output)
            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 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]]]:
    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, "model_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]) -> Tuple[str, pd.DataFrame]:
    global GLOBAL_CHUCK_AGENT
    logger.info(f"run_and_submit_all_evaluation called. Profile: {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()
        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, max_rows=20)

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