File size: 31,341 Bytes
10e9b7d
 
eccf8e4
3c4371f
8ab0ff1
 
 
 
 
 
 
10e9b7d
8ab0ff1
 
 
 
 
b106a8f
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
b106a8f
8ab0ff1
 
b106a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b106a8f
 
 
8ab0ff1
b106a8f
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b106a8f
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
b106a8f
 
 
8ab0ff1
b106a8f
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b106a8f
 
 
8ab0ff1
b106a8f
e80aab9
31243f4
8ab0ff1
 
 
 
 
 
 
3c4371f
b106a8f
8ab0ff1
 
 
 
 
 
 
 
 
 
e80aab9
8ab0ff1
 
f24fa86
8ab0ff1
 
 
 
 
f445e67
8ab0ff1
 
 
 
 
 
 
 
 
 
b106a8f
 
 
 
f445e67
 
b106a8f
 
 
f445e67
f24fa86
 
8ab0ff1
 
 
 
 
bda7196
b106a8f
 
 
 
 
 
bda7196
b106a8f
bda7196
b106a8f
 
 
 
bda7196
b106a8f
8ab0ff1
 
 
 
 
b106a8f
 
 
8ab0ff1
 
bda7196
b106a8f
 
 
 
8ab0ff1
b106a8f
8ab0ff1
 
bda7196
b106a8f
bda7196
 
 
8ab0ff1
 
 
 
bda7196
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eccf8e4
8ab0ff1
7d65c66
31243f4
8ab0ff1
 
 
 
 
e80aab9
8ab0ff1
 
 
 
 
e80aab9
8ab0ff1
5049fca
 
 
 
b106a8f
5049fca
 
 
 
b106a8f
5049fca
 
b106a8f
8ab0ff1
b106a8f
8ab0ff1
 
 
 
b106a8f
 
 
 
8ab0ff1
b106a8f
bda7196
 
5049fca
bda7196
b106a8f
8ab0ff1
31243f4
8ab0ff1
31243f4
8ab0ff1
 
e80aab9
8ab0ff1
 
 
e80aab9
7d65c66
e80aab9
 
8ab0ff1
 
3c4371f
 
 
e80aab9
 
8ab0ff1
e80aab9
 
3c4371f
e80aab9
8ab0ff1
 
 
3c4371f
8ab0ff1
 
e80aab9
8ab0ff1
 
 
 
 
 
 
 
 
1e555c6
8ab0ff1
1e555c6
 
 
 
 
 
 
b106a8f
 
 
1e555c6
 
 
b106a8f
1e555c6
 
b106a8f
1e555c6
 
b106a8f
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
 
b106a8f
8ab0ff1
 
 
7d65c66
8ab0ff1
 
e80aab9
8ab0ff1
 
b106a8f
8ab0ff1
 
 
 
 
 
 
 
 
e80aab9
8ab0ff1
e80aab9
31243f4
0ee0419
e514fd7
 
8ab0ff1
 
 
 
 
 
 
 
 
 
 
 
e514fd7
8ab0ff1
 
 
b106a8f
8ab0ff1
e514fd7
e80aab9
 
8ab0ff1
31243f4
8ab0ff1
b106a8f
e80aab9
31243f4
8ab0ff1
 
31243f4
e80aab9
 
8ab0ff1
e80aab9
3c4371f
 
8ab0ff1
7d65c66
3c4371f
 
8ab0ff1
3c4371f
7d65c66
 
8ab0ff1
7d65c66
 
8ab0ff1
7d65c66
 
8ab0ff1
 
b106a8f
3c4371f
8ab0ff1
 
 
 
 
 
 
 
b106a8f
8ab0ff1
 
 
 
 
 
b106a8f
8ab0ff1
 
 
 
b106a8f
8ab0ff1
b106a8f
8ab0ff1
 
b106a8f
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
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-3.5-turbo" # Sticking with this for speed/cost
    SERPER_API_NUM_RESULTS = 3
    WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
    AGENT_MAX_STEPS = 10 # Keep an eye on logs; increase if agent often hits max_steps before solving
    AGENT_VERBOSITY_LEVEL = 2 # Set to 2 for more detailed logs from smolagents

    # MODIFIED AND ENHANCED AGENT_SYSTEM_PROMPT
    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 of generated code: `print(await web_search(query="current weather in London"))`
2.  `calculator(expression: str) -> str`: Use this tool for any mathematical calculations. This tool is synchronous.
    Example of generated code: `print(calculator(expression="((1024 / 8) + 55 - 5) * 2"))`
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`. It returns a status message about the retrieval (e.g., "Image retrieved successfully...").
    Example of generated code: `print(await image_retriever(url="https://example.com/image.jpg"))`

Follow this thought 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:
    # async_tool_result = await web_search(query="some specific query")
    # print(async_tool_result)
    # sync_tool_result = calculator(expression="1+1")
    # print(sync_tool_result)
    ```<end_code>
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 (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 the question specifically asks for digits.
- 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" # Exact name LLM must use
    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 # Hint for some executors, though LLM must generate await

    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" # Exact name LLM must use
    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 # Hint for some executors

    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" # Exact name LLM must use
    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 # Explicitly synchronous

    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: # Still async for Tool compatibility, but logic is sync
        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
            )

        # Standard call to CodeAgent's __init__
        super().__init__(
            model=effective_model,
            tools=tools,
            system_prompt=CONFIG.AGENT_SYSTEM_PROMPT, # This is critical
            additional_authorized_imports=["PIL"],    # Make sure PIL is in requirements if actually needed by LLM code
            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_obj = self.run(question_text) # Assuming self.run() is synchronous
            
            # Attempt to get the most complete textual output from the agent's run
            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): # If run() itself returns a string
                full_agent_response = raw_output_obj
            elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None: # Another common attribute
                full_agent_response = str(raw_output_obj.result)
            else: 
                full_agent_response = str(raw_output_obj) # Fallback
            
            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()
                # Further clean up if necessary, e.g., removing trailing thoughts if any part of the thought process
                # accidentally got included after "FINAL ANSWER:" due to LLM verbosity.
                # This simple strip might be enough for now.
                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).")
                # If "FINAL ANSWER:" is not found, the LLM didn't follow instructions.
                # The full_agent_response might be just thoughts, or a conversational answer.
                # For submission, this might be penalized.
                final_answer_for_submission = full_agent_response.strip() # Fallback

            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 (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]]]:
    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: # Renamed arg to arg_val to avoid conflict with outer scope 'args' name
            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()
        agent_instance = GLOBAL_CHUCK_AGENT # Use a local variable for clarity
    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_instance, questions_data) # Use agent_instance
        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 `gradio>=4.19.2` or newer. (`gradio==4.25.0` or a similar fixed version recommended from previous discussions).
        * 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 removed

    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: # Fallback if agent not fully created but session was
            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()
                if current_loop is not loop_to_use and not loop_to_use.is_closed(): # Check if loop_to_use is not 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: # Catch broader exceptions during cleanup
                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.")