File size: 40,394 Bytes
8ab4960
10e9b7d
8ab4960
afb28ab
 
10e9b7d
8ab4960
eccf8e4
8ab4960
3c4371f
8ab4960
8ab0ff1
8ab4960
8ab0ff1
8ab4960
8ab0ff1
8ab4960
ee4da95
8ab4960
1234db8
 
8ab0ff1
8ab4960
1234db8
 
 
10e9b7d
1234db8
 
8ab0ff1
cdb3541
7718b03
1234db8
 
7718b03
 
cdb3541
98644f2
1234db8
 
cdb3541
1234db8
 
 
8ab0ff1
 
8ab4960
8ab0ff1
 
8ab4960
8ab0ff1
afb28ab
8ab0ff1
 
1234db8
7718b03
8ab0ff1
 
1234db8
 
 
 
 
 
 
 
 
 
 
 
 
d0370bd
 
1234db8
 
 
 
d0370bd
 
d902a13
1234db8
 
 
d902a13
 
 
bd79378
 
fef1188
d902a13
fef1188
b106a8f
8ab0ff1
 
8ab4960
8ab0ff1
733ec57
 
 
 
 
8ab4960
733ec57
8ab0ff1
 
 
bd79378
 
8ab0ff1
 
98644f2
 
 
afb28ab
98644f2
 
 
 
8ab4960
8ab0ff1
1234db8
 
be5f4f9
42fc37a
7718b03
 
42fc37a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1234db8
 
afb28ab
1234db8
 
 
 
 
 
 
 
 
 
 
 
afb28ab
9047cda
1234db8
 
 
 
 
 
 
 
 
6765748
1234db8
7718b03
1234db8
7718b03
1234db8
 
 
42fc37a
 
1234db8
cdb3541
 
1234db8
5a64626
1234db8
42fc37a
 
1234db8
 
 
7718b03
 
cdb3541
5a64626
7718b03
42fc37a
 
5a64626
 
1234db8
 
733ec57
1234db8
 
 
8ab0ff1
1234db8
5a64626
42fc37a
3ad5e59
7718b03
5a64626
42fc37a
3ad5e59
1234db8
8ab0ff1
1234db8
afb28ab
3ad5e59
cdb3541
3ad5e59
bd79378
 
 
cdb3541
 
1234db8
 
bd79378
 
1234db8
bd79378
1234db8
bd79378
afb28ab
1234db8
 
afb28ab
1234db8
 
 
 
bd79378
 
7718b03
5a64626
bd79378
 
 
e6648f6
3ad5e59
cdb3541
bd79378
3ad5e59
1234db8
cdb3541
 
7718b03
afb28ab
1234db8
afb28ab
8ab0ff1
cdb3541
 
 
 
 
 
 
 
 
 
 
8ab0ff1
1234db8
 
 
cdb3541
3ad5e59
cdb3541
1234db8
98644f2
 
7718b03
1234db8
98644f2
afb28ab
42fc37a
 
5a64626
42fc37a
3ad5e59
 
98644f2
8ab4960
 
1234db8
 
8ab4960
1234db8
 
afb28ab
1234db8
98644f2
 
 
1234db8
8ab4960
98644f2
7718b03
 
98644f2
 
1234db8
 
 
 
 
 
 
 
 
8ab4960
3ad5e59
 
afb28ab
3ad5e59
 
 
 
1234db8
8ab4960
3ad5e59
 
 
 
8ab4960
3ad5e59
1234db8
 
 
 
98644f2
8ab4960
98644f2
 
 
 
 
 
 
 
 
 
8ab4960
98644f2
 
8ab4960
98644f2
 
afb28ab
8ab4960
98644f2
 
 
 
1234db8
98644f2
 
 
 
 
afb28ab
98644f2
 
8ab4960
98644f2
afb28ab
d063073
1234db8
98644f2
 
 
1234db8
 
d063073
98644f2
afb28ab
8ab4960
98644f2
 
d063073
98644f2
8ab4960
98644f2
 
 
8ab4960
98644f2
 
 
 
 
d063073
 
98644f2
 
 
 
 
 
8ab4960
 
98644f2
 
 
 
 
 
8ab4960
3ad5e59
8ab4960
98644f2
8ab4960
98644f2
8ab4960
afb28ab
8ab4960
 
98644f2
 
1234db8
a9d6c9f
8ab4960
a9d6c9f
5a64626
8ab4960
98644f2
1234db8
98644f2
 
 
1234db8
98644f2
91cdd82
a9d6c9f
98644f2
 
a9d6c9f
98644f2
 
8ab4960
a9d6c9f
 
98644f2
a9d6c9f
8ab4960
a9d6c9f
1234db8
afb28ab
a9d6c9f
 
42fc37a
 
3ad5e59
 
afb28ab
 
 
3ad5e59
 
 
8ab4960
a9d6c9f
1234db8
 
afb28ab
8ab4960
 
 
91cdd82
afb28ab
8ab4960
5a64626
8ab4960
afb28ab
7718b03
42fc37a
3ad5e59
 
 
 
 
 
 
 
a9d6c9f
3ad5e59
afb28ab
a9d6c9f
1234db8
8ab4960
98644f2
 
afb28ab
3ad5e59
afb28ab
8ab4960
98644f2
a9d6c9f
3ad5e59
 
5a64626
8ab4960
98644f2
 
3ad5e59
 
5a64626
8ab4960
98644f2
a9d6c9f
afb28ab
3ad5e59
98644f2
a9d6c9f
8ab4960
a9d6c9f
 
8ab4960
 
 
 
afb28ab
8ab4960
 
 
1234db8
8ab4960
 
 
1234db8
8ab4960
 
 
 
 
 
 
1234db8
 
 
 
8ab4960
1234db8
42fc37a
8ab4960
1234db8
8ab4960
 
 
 
 
 
 
 
 
1234db8
8ab4960
 
 
1234db8
8ab4960
 
 
 
 
 
 
afb28ab
a9d6c9f
 
1234db8
a9d6c9f
 
3ad5e59
1234db8
98644f2
3ad5e59
7718b03
 
 
 
 
 
cdb3541
7718b03
3ad5e59
 
cdb3541
7718b03
 
a9d6c9f
 
 
 
98644f2
a9d6c9f
 
afb28ab
a9d6c9f
 
98644f2
 
 
1234db8
 
98644f2
1234db8
98644f2
1234db8
8ab4960
afb28ab
8ab4960
 
 
 
 
 
 
1234db8
 
98644f2
1234db8
8ab4960
1234db8
98644f2
8ab4960
98644f2
 
8ab4960
 
 
1234db8
8ab4960
1234db8
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
print("DEBUG: app.py execution started (top of file)")
import os
print("DEBUG: os imported")
import sys
print("DEBUG: sys imported")
import gradio as gr
print("DEBUG: gradio imported")
import requests
print("DEBUG: requests imported")
import pandas as pd
print("DEBUG: pandas imported")
import asyncio
print("DEBUG: asyncio imported")
import re
print("DEBUG: re imported")
import json
print("DEBUG: json imported")
import logging
print("DEBUG: logging imported")
# import operator # Not currently used
# print("DEBUG: operator imported")
import aiohttp
print("DEBUG: aiohttp imported")
from typing import Optional, Dict, Any, List, Tuple, Type
from pydantic import BaseModel, Field
print("DEBUG: typing and pydantic imported")

# --- Pydantic AI Imports ---
PYDANTIC_AI_LOADED = False
try:
    from pydantic_ai import Agent
    print("DEBUG: pydantic-ai Agent imported successfully.")
    PYDANTIC_AI_LOADED = True
except ImportError as e:
    print(f"DEBUG: Failed to import pydantic-ai Agent. Error: {e}")
    logging.error(f"Failed to import pydantic-ai Agent. Please ensure it is installed. Error: {e}")
    class Agent: # Dummy Agent
        def __init__(self, *args, **kwargs):
            print("DEBUG: Dummy Pydantic AI Agent initialized.")
            logging.error("Dummy Pydantic AI Agent initialized.")
        async def run(self, *args, **kwargs):
            print("DEBUG: Dummy Pydantic AI Agent run called.")
            logging.error("Dummy Pydantic AI Agent run called.")
            return "Error: pydantic-ai Agent not loaded."

from datetime import datetime
print("DEBUG: datetime imported")

# --- Configuration ---
print("DEBUG: Defining AppConfig.")
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-4-1106-preview"
    SERPER_API_NUM_RESULTS = 3
    WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000

    PYDANTIC_AI_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 tools. If you need to use a tool, you will be provided with its definition.
Respond with your thought process and then the final answer.
When you have the final answer, you MUST present it on a new line prefixed with "FINAL ANSWER: " (note the space after the colon).
Example:
User: What is the capital of France?
Assistant:
THOUGHT: The user is asking for the capital of France. I should use the web_search tool.
[LLM would then indicate use of web_search tool, pydantic-ai handles the call]
OBSERVATION: [Search results for capital of France, e.g., "Paris is the capital..."]
THOUGHT: The search result clearly states that Paris is the capital of France. I have sufficient information.
FINAL ANSWER: Paris

Example for a question not needing a tool:
User: What is the opposite of left?
Assistant:
THOUGHT: The question asks for the opposite of the word "left". This is general knowledge and does not require a tool. The opposite of "left" is "right".
FINAL ANSWER: right

Formatting rules for the value that comes *after* "FINAL ANSWER: ":
- If the question asks for a number: Provide only the number itself (e.g., FINAL ANSWER: 42). Do not use commas for thousands separation.
- If the question asks for a string: Provide the most concise string possible (e.g., FINAL ANSWER: right).
- If the question asks for a comma-separated list: Apply string/number rules to each element. Separated ONLY by a comma (e.g., FINAL ANSWER: item one,item two,three). NO space after the comma unless it's part of an item.
"""

    SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
Given an original question and a detailed reasoning process (full agent log) that attempted to answer it, your task is to provide a very short, direct answer to the original question based *only* on the information present in the provided reasoning process.
This concise answer MUST strictly adhere to the provided formatting rules for numbers, strings, or comma-separated lists, as applicable to the original question.
Do NOT include "FINAL ANSWER:" or any other prefix in your response. Just output the answer value.
Do NOT explain your reasoning for the concise answer. Only provide the answer value.
If the reasoning provided does not contain a clear answer to the original question, output the exact phrase "Could not determine answer from reasoning."
"""

CONFIG = AppConfig()
print("DEBUG: AppConfig defined and CONFIG instance created.")

# --- Logging Setup ---
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
print("DEBUG: Logging configured.")

# --- Utility Functions ---
def ensure_dir_exists(directory_path: str):
    os.makedirs(directory_path, exist_ok=True)
    print(f"DEBUG: Ensured directory exists: {directory_path}")

ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)

def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
    space_id = os.getenv("SPACE_ID")
    if space_id:
        agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
    else:
        agent_code_url = "Agent code URL not found (SPACE_ID not set)"
    return space_id, agent_code_url

print("DEBUG: Utility functions defined.")

# --- Tool Definitions for Pydantic AI ---
print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")

async def web_search(query: str) -> str:
    """Searches the web using Serper API for information. Use this for current events or information not in your knowledge base. Input is the search query."""
    print(f"DEBUG: Web_search tool (undecorated) 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 in environment variables.")
        print("DEBUG: ERROR - SERPER_API_KEY not found.")
        return "Error: Serper API key not found in environment. Cannot perform web search."

    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})

    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
                response.raise_for_status()
                data = await response.json()
                print(f"DEBUG: web_search tool received data for query '{query}'.")
                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]
        except asyncio.TimeoutError:
            logger.error(f"Timeout performing search for '{query}'")
            print(f"DEBUG: ERROR - Timeout in web_search tool for query '{query}'.")
            return f"Error: Timeout during web search for '{query}'."
        except aiohttp.ClientResponseError as e:
            logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
            print(f"DEBUG: ERROR - HTTP Error {e.status} in web_search tool for query '{query}'.")
            return f"Error performing search (HTTP {e.status}): {e.message}"
        except aiohttp.ClientError as e:
            logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
            print(f"DEBUG: ERROR - ClientError in web_search tool for query '{query}': {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)}", exc_info=True)
            print(f"DEBUG: ERROR - Unexpected error in web_search tool for query '{query}': {str(e)}.")
            return f"Error performing search: An unexpected error occurred."

print("DEBUG: Defining PydanticQuestionAnsweringAgent (conceptual).")
print("DEBUG: Defining ChuckAgent (modified for Pydantic AI).")

class ChuckAgent:
    def __init__(self):
        print("DEBUG: ChuckAgent.__init__ called.")
        logger.info("ChuckAgent initialization started (Pydantic AI version).")
        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)}. Please set them in Space Secrets."
            print(f"DEBUG: ERROR - ChuckAgent missing env vars: {error_msg}")
            logger.critical(error_msg)
            raise EnvironmentError(error_msg)
        print("DEBUG: ChuckAgent environment variables checked.")
        self.agent_instance: Optional[Agent] = None
        try:
            self.loop = asyncio.get_running_loop()
            print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
        except RuntimeError:
            print("DEBUG: ChuckAgent - No current running event loop, creating a new one for this thread.")
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)
        print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
        logger.info("ChuckAgent basic initialization complete. Pydantic AI Agent will be created on first use.")
        print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")

    def _ensure_agent_initialized(self):
        global PYDANTIC_AI_LOADED
        print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
        if self.agent_instance is None and PYDANTIC_AI_LOADED:
            print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing Pydantic AI Agent...")
            logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
            try:
                model_identifier = f"openai:{CONFIG.OPENAI_MODEL_ID}"
                print(f"DEBUG: Initializing Pydantic AI Agent with model identifier: {model_identifier}")
                self.agent_instance = Agent(
                    model_identifier,
                    tools=[web_search],
                    system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
                    debug=True
                )
                print("DEBUG: ChuckAgent - Pydantic AI Agent initialized successfully with model string.")
                logger.info("Pydantic AI Agent initialized successfully with model string.")
            except Exception as e:
                print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
                logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
                PYDANTIC_AI_LOADED = False
                if self.agent_instance is None:
                    self.agent_instance = Agent()
                raise
        elif not PYDANTIC_AI_LOADED:
            print("DEBUG: ERROR - Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
            logger.error("Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
            if self.agent_instance is None:
                self.agent_instance = Agent()
        else:
            print("DEBUG: ChuckAgent - Pydantic AI Agent already initialized.")

    async def _process_question_async(self, question_text: str) -> Tuple[str, str]:
        print(f"DEBUG: ChuckAgent._process_question_async called for: '{question_text[:100]}...'")
        reasoning_trace = "Pydantic AI Agent execution started."
        final_answer_for_submission = "Error: Agent did not produce a recognizable answer."

        if self.agent_instance is None or not PYDANTIC_AI_LOADED:
            logger.error("Pydantic AI Agent instance not available or library not loaded.")
            print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
            if hasattr(self.agent_instance, 'run'):
                 dummy_error = await self.agent_instance.run("")
                 return dummy_error, "Agent not properly initialized or pydantic-ai not loaded."
            return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized at process time."

        try:
            agent_final_text_output = await self.agent_instance.run(question_text)
            reasoning_trace = str(agent_final_text_output)
            print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")

            match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)

            if match:
                final_answer_for_submission = match.group(1).strip()
                print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER candidate: '{final_answer_for_submission}'")
            elif PYDANTIC_AI_LOADED:
                logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
                print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
                summarizer_messages = [
                    {"role": "system", "content": CONFIG.SUMMARIZER_SYSTEM_PROMPT},
                    {"role": "user", "content": f"Original Question: {question_text}\n\nAgent's Full Output Log:\n{reasoning_trace}\n\nBased on the 'Agent's Full Output Log', extract or formulate a concise, direct answer to the 'Original Question'. Your response should be ONLY the answer value itself, adhering strictly to the formatting rules. If a clear answer cannot be determined, output 'Could not determine answer from reasoning.'"}
                ]
                print(f"DEBUG: Summarizer LLM call with messages (user message snippet): {summarizer_messages[1]['content'][:200]}...")
                try:
                    from openai import OpenAI as OfficialOpenAIClient
                    client = OfficialOpenAIClient(api_key=os.environ.get('OPENAI_API_KEY'))
                    response = client.chat.completions.create(
                        model=CONFIG.OPENAI_MODEL_ID,
                        messages=summarizer_messages,
                        temperature=0.0
                    )
                    concise_answer = response.choices[0].message.content.strip()
                    if concise_answer:
                        if "Could not determine answer from reasoning." in concise_answer:
                            print(f"DEBUG: LLM summarization fallback indicated no clear answer.")
                            final_answer_for_submission = "Could not determine answer from reasoning."
                        else:
                            final_answer_for_submission = concise_answer
                            print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
                    else:
                        print("DEBUG: ERROR - LLM summarization fallback returned empty. Using full agent output.")
                        final_answer_for_submission = reasoning_trace.strip() # Fallback to full trace
                except Exception as e_summary:
                    print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
                    logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
                    final_answer_for_submission = reasoning_trace.strip() # Fallback to full trace
            else:
                logger.warning("Could not find 'FINAL ANSWER:' and Pydantic AI not loaded or no fallback. Using agent's full output.")
                final_answer_for_submission = reasoning_trace.strip()

            if not final_answer_for_submission:
                final_answer_for_submission = "Could not determine answer."

            # --- TARGETED FIX FOR TRAILING "')" ---
            if isinstance(final_answer_for_submission, str) and \
               final_answer_for_submission.endswith("')") and \
               len(final_answer_for_submission) > 2:
                
                original_before_cleanup = final_answer_for_submission
                final_answer_for_submission = final_answer_for_submission[:-2] # Remove last two characters: ' and )
                print(f"DEBUG: Applied trailing ') cleanup. Original: '{original_before_cleanup}', Cleaned: '{final_answer_for_submission}'")
            # --- END TARGETED FIX ---

        except Exception as e:
            error_msg = f"Error processing question with Pydantic AI Agent: {type(e).__name__} - {str(e)}"
            print(f"DEBUG: ERROR - {error_msg}")
            logger.error(error_msg, exc_info=True)
            final_answer_for_submission = f"Error in Pydantic AI agent processing: {str(e)}" # Ensure it's a string
            reasoning_trace += f"\nError encountered during processing: {str(e)}"
        
        return final_answer_for_submission, reasoning_trace

    def __call__(self, question: str) -> Tuple[str, str]:
        global PYDANTIC_AI_LOADED
        print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
        try:
            self._ensure_agent_initialized()
            if not PYDANTIC_AI_LOADED and self.agent_instance is not None:
                print("DEBUG: ChuckAgent.__call__ - PYDANTIC_AI_LOADED is False, expecting dummy agent behavior.")
            elif self.agent_instance is None:
                 error_message = "Pydantic AI Agent instance is None after initialization attempt."
                 print(f"DEBUG: ERROR - ChuckAgent.__call__ {error_message}")
                 raise RuntimeError(error_message)

            print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
            if not self.loop.is_running():
                print(f"DEBUG: WARNING - ChuckAgent event loop {self.loop} is not running. Attempting to run _process_question_async directly.")
                final_answer, reasoning_trace = self.loop.run_until_complete(self._process_question_async(question))
            else:
                future = asyncio.run_coroutine_threadsafe(self._process_question_async(question), self.loop)
                print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
                final_answer, reasoning_trace = future.result(timeout=300)
            print(f"DEBUG: ChuckAgent future.result() obtained. Answer: '{final_answer[:50]}...'")
            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 (Pydantic AI): {type(e).__name__} - {str(e)}"
            print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
            logger.error(error_msg, exc_info=True)
            if "Pydantic AI Agent" in str(e) or "dummy placeholder" in str(e) or "Agent instance is None" in str(e):
                 PYDANTIC_AI_LOADED = False
            return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"

    async def shutdown_async(self):
        print("DEBUG: ChuckAgent.shutdown_async called (Pydantic AI version).")
        logger.info("ChuckAgent async shutdown initiated (Pydantic AI version).")
        logger.info("ChuckAgent async shutdown complete (Pydantic AI version).")
        print("DEBUG: ChuckAgent async shutdown complete (Pydantic AI version).")

    def close(self):
        print("DEBUG: ChuckAgent.close called (Pydantic AI version).")
        if self.loop and self.loop.is_running():
            print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
            future = asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop)
            try:
                future.result(timeout=10)
            except asyncio.TimeoutError:
                logger.warning("Timeout waiting for ChuckAgent async_shutdown to complete.")
            except Exception as e:
                logger.error(f"Error during async_shutdown result retrieval: {e}")
        elif self.loop and not self.loop.is_running():
             print("DEBUG: ChuckAgent.close - loop is not running, using run_until_complete for shutdown_async.")
             try:
                self.loop.run_until_complete(self.shutdown_async())
             except Exception as e:
                logger.error(f"Error during run_until_complete for shutdown_async: {e}")
        else:
            print("DEBUG: ChuckAgent.close - No running or available loop to manage for shutdown.")
        print("DEBUG: ChuckAgent.close finished (Pydantic AI version).")

print("DEBUG: ChuckAgent class defined (Pydantic AI version).")

def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
    print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
    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 isinstance(questions_data, list) or not questions_data:
            logger.warning(f"Fetched questions empty or invalid format: {questions_data}")
            raise ValueError("Fetched questions list is empty or not a list.")
        logger.info(f"Fetched {len(questions_data)} questions.")
        print(f"DEBUG: Fetched {len(questions_data)} questions.")
        return questions_data
    except requests.exceptions.RequestException as e:
        print(f"DEBUG: ERROR - Error fetching questions: {e}")
        logger.error(f"Error fetching questions: {e}", exc_info=True)
        raise ConnectionError(f"Error fetching questions: {e}")
    except requests.exceptions.JSONDecodeError as e:
        print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
        logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
        raise ValueError(f"Error decoding server response for questions: {e}")

def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
    print(f"DEBUG: process_all_questions called with {len(questions_data)} questions (Pydantic AI version).")
    answers_payload = []
    results_log_data = []
    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 with missing task_id or question: {item}")
            continue
        print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
        try:
            model_ans, reasoning = agent(question_text)
            payload_item = {"task_id": task_id, "submitted_answer": model_ans}
            if reasoning:
                payload_item["reasoning_trace"] = reasoning
            answers_payload.append(payload_item)
            results_log_data.append({
                "Task ID": task_id, "Question": question_text,
                "Submitted Answer": model_ans,
                "Reasoning Trace": reasoning
            })
        except Exception as e:
            print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
            logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
            error_answer = f"AGENT_CALL_ERROR: {str(e)}"
            answers_payload.append({"task_id": task_id, "submitted_answer": error_answer, "reasoning_trace": str(e)})
            results_log_data.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
    print(f"DEBUG: process_all_questions finished. Produced {len(answers_payload)} answers.")
    return answers_payload, results_log_data

def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
    print(f"DEBUG: submit_answers called for user '{username}' with {len(answers_payload)} answers.")
    if not answers_payload:
        logger.warning("No 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}
    if answers_payload:
        print(f"DEBUG: Sample of first answer payload being sent: {answers_payload[0]}")
    logger.info(f"Submitting {len(answers_payload)} answers for user '{username}' to {submit_url}...")
    try:
        response = requests.post(submit_url, json=submission_data, timeout=60)
        response.raise_for_status()
        result_data = response.json()
        final_status = (
            f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
            f"Overall Score: {result_data.get('score', 'N/A')}% ({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
            f"Message: {result_data.get('message', 'No message received.')}"
        )
        logger.info(f"Submission successful for user '{username}'. Score: {result_data.get('score', 'N/A')}%")
    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]}"
        final_status = f"Submission Failed: {error_detail}"; logger.error(final_status)
    except requests.exceptions.Timeout:
        final_status = "Submission Failed: The request timed out."; logger.error(final_status)
    except requests.exceptions.RequestException as e:
        final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
    except Exception as e:
        final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
    print(f"DEBUG: submit_answers final_status: {final_status}")
    return final_status

GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None

print("DEBUG: Defining run_and_submit_all_evaluation function.")
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
    global GLOBAL_CHUCK_AGENT, PYDANTIC_AI_LOADED
    print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
    logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")

    effective_profile: Optional[gr.OAuthProfile] = None
    if isinstance(profile, gr.OAuthProfile):
        effective_profile = profile
    elif args:
        logger.warning(f"Profile not directly passed or None. Checking *args: {args}")
        for arg_val in args:
            if isinstance(arg_val, gr.OAuthProfile):
                effective_profile = arg_val
                logger.info(f"Found gr.OAuthProfile in *args: {effective_profile.username if effective_profile else 'None (from args)'}")
                break
    if not effective_profile:
        logger.warning("User not logged in or profile not correctly passed for evaluation.")
        print("DEBUG: ERROR - User not logged in or profile not correctly passed for evaluation.")
        return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()

    username = effective_profile.username
    logger.info(f"User logged in: {username}")
    print(f"DEBUG: User logged in: {username}")

    _, agent_code_url = get_space_id_agent_code_url()
    results_log_data: List[Dict[str, Any]] = []

    try:
        if not PYDANTIC_AI_LOADED:
            error_msg = "CRITICAL ERROR: The 'pydantic-ai' library or its core components could not be imported. The Agent cannot function. Please ensure 'pydantic-ai' is correctly installed (e.g., in requirements.txt) and the environment is correctly set up, then restart the application. Check logs for specific import error."
            print(f"DEBUG: {error_msg}")
            logger.critical(error_msg)
            error_df_data = [{"Task ID": "N/A",
                            "Question": "Critical Dependency Error",
                            "Submitted Answer": "pydantic-ai import failed",
                            "Reasoning Trace": error_msg}]
            return error_msg, pd.DataFrame(error_df_data)

        print("DEBUG: run_and_submit_all_evaluation - Attempting to initialize/get GLOBAL_CHUCK_AGENT.")
        if GLOBAL_CHUCK_AGENT is None:
            print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance (Pydantic AI version).")
            logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance (Pydantic AI version).")
            GLOBAL_CHUCK_AGENT = ChuckAgent()
            print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
        else:
            print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
        agent_instance = GLOBAL_CHUCK_AGENT

        print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
        agent_instance._ensure_agent_initialized()
        print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")

        if not PYDANTIC_AI_LOADED: # Re-check after _ensure_agent_initialized could modify it
            critical_error_msg = "Agent initialization failed post-import or a secondary import within Agent init failed. PydanticAI is not usable."
            logger.critical(critical_error_msg)
            print(f"DEBUG: CRITICAL - {critical_error_msg}")
            error_df_data = [{"Task ID": "N/A",
                              "Question": "Agent Initialization Error",
                              "Submitted Answer": "Init Failed",
                              "Reasoning Trace": critical_error_msg}]
            return critical_error_msg, pd.DataFrame(error_df_data)

        questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
        answers_payload, results_log_data_processed = process_all_questions(agent_instance, questions_data)
        results_log_data.extend(results_log_data_processed)
        submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
    except EnvironmentError as e:
        print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
        logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
        submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
        if not results_log_data:
             results_log_data = [{"Task ID": "N/A", "Question": "Environment Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
    except (ConnectionError, ValueError) as e:
        print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
        logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
        submission_status = str(e)
        if not results_log_data:
             results_log_data = [{"Task ID": "N/A", "Question": "Connection/Value Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
    except RuntimeError as e:
        print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
        logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
        submission_status = f"Runtime Error: {e}"
        if not results_log_data:
             results_log_data = [{"Task ID": "N/A", "Question": "Runtime Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
    except Exception as e:
        print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
        logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
        submission_status = f"An unexpected error occurred: {e}"
        if not results_log_data:
             results_log_data = [{"Task ID": "N/A", "Question": "Unexpected Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]

    results_df = pd.DataFrame(results_log_data if results_log_data else [])
    print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
    return submission_status, results_df

print("DEBUG: Building Gradio interface.")
try:
    with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
        print("DEBUG: gr.Blocks context entered.")
        gr.Markdown("# Chuck's Agent Evaluation Runner (Pydantic AI Version)")
        gr.Markdown(
            """
            **Instructions:**
            1. This interface allows you to evaluate your AI agent (now using Pydantic AI) against a predefined set of questions.
            2. **Log in** to your Hugging Face account using the button below. Your HF username is used for submitting results.
            3. Click '**Run Evaluation & Submit All Answers**'. This will:
                a. Fetch questions from the evaluation server.
                b. Run your configured Pydantic AI agent on each question.
                c. Submit the answers back to the server.
                d. Display the overall status and a table of questions, your agent's answers, and reasoning.
            """
        )
        gr.Markdown(
           f"""
            ---
            **Technical Notes & Configuration (Pydantic AI Version):**
            * **Agent Backend**: `pydantic-ai` framework.
            * **OpenAI Model**: `{CONFIG.OPENAI_MODEL_ID}` (ensure this model supports function calling well).
            * **Web Search**: Serper API (`google.serper.dev`) via a Pydantic AI tool.
            * **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
            * **Gradio Version**: This app is tested with `gradio>=4.0`.
            * **`pydantic-ai`**: Ensure `pydantic-ai` (version compatible with documentation, e.g., ~0.2.4 based on PDF) and its dependencies (like `openai>=1.3.0`) are in `requirements.txt`.
            ---
            **Disclaimer**: Processing all questions can take some time.
            """
        )
        print("DEBUG: Gradio Markdown elements created.")
        login_button = gr.LoginButton()
        print("DEBUG: Gradio LoginButton created.")
        run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
        print("DEBUG: Gradio Run Button created.")
        with gr.Column():
            status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
            results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True)
        print("DEBUG: Gradio output elements (Textbox, DataFrame) created.")
        run_button.click(
            fn=run_and_submit_all_evaluation,
            inputs=[login_button],
            outputs=[status_output, results_table]
        )
        print("DEBUG: Gradio run_button.click event handler set.")
    print("DEBUG: Gradio interface definition complete.")
except Exception as e:
    print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
    logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
    demo = None

if __name__ == "__main__":
    print("\n" + "="*15 + " Application Startup (Pydantic AI) " + "="*15)
    space_host_startup = os.getenv("SPACE_HOST")
    space_id_startup, agent_url_startup = get_space_id_agent_code_url()
    print(f"Python Version: {'.'.join(map(str, sys.version_info[:3]))}")
    print(f"Gradio Version: {gr.__version__}")
    try:
        if PYDANTIC_AI_LOADED:
            try:
                import pydantic_ai
                if hasattr(pydantic_ai, '__version__'):
                    print(f"pydantic-ai Version: {pydantic_ai.__version__}")
                else:
                    print("pydantic-ai Version: unknown (loaded, but __version__ attribute missing at top level)")
            except ImportError:
                 print("pydantic-ai could not be imported for version check, though Agent was loaded.")
        else:
            print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
    except Exception as e_ver:
         print(f"Error during pydantic-ai version check: {e_ver}")

    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 (likely 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. Repo URL cannot be determined.")
    print(f"   Default API URL for scoring: {CONFIG.DEFAULT_API_URL}")
    print(f"   OpenAI Model ID for Agent: {CONFIG.OPENAI_MODEL_ID}")
    print("="* (30 + len(" Application Startup (Pydantic AI) ")) + "\n")
    print("Launching Gradio Interface for Chuck Agent Evaluation (Pydantic AI Version)...")
    print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
    print("Ensure pydantic-ai and openai>=1.3.0 are in requirements.txt.")

    if demo is not None:
        try:
            demo.launch(debug=True, share=False)
        except Exception as e:
            print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
            logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
        finally:
            print("DEBUG: Gradio demo.launch() finished or was interrupted.")
            logger.info("Gradio demo has been closed or failed to launch.")
            if GLOBAL_CHUCK_AGENT:
                print("DEBUG: Attempting to shutdown GLOBAL_CHUCK_AGENT (Pydantic AI version).")
                logger.info("Attempting to shutdown ChuckAgent (Pydantic AI version)...")
                try:
                    GLOBAL_CHUCK_AGENT.close()
                    print("DEBUG: GLOBAL_CHUCK_AGENT.close() called.")
                    logger.info("ChuckAgent shutdown process completed (Pydantic AI version).")
                except Exception as e_shutdown:
                    print(f"DEBUG: ERROR during GLOBAL_CHUCK_AGENT.close(): {e_shutdown}")
                    logger.error(f"Error during ChuckAgent final shutdown: {e_shutdown}", exc_info=True)
            else:
                print("DEBUG: No GLOBAL_CHUCK_AGENT instance to shutdown.")
    else:
        print("DEBUG: ERROR - Gradio demo object is None, cannot launch. Check for errors during UI definition.")
    print("\n" + "="*15 + " Application Shutdown (Pydantic AI) " + "="*15)
else:
    print("DEBUG: Script is being imported, not run as main.")