File size: 29,570 Bytes
10e9b7d
 
eccf8e4
06a4d84
3c4371f
06a4d84
c233f47
5439472
06a4d84
f9d0203
7581b17
06a4d84
df85cc9
06a4d84
 
 
 
 
 
 
 
 
 
fa9ac9e
 
 
 
06a4d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df85cc9
06a4d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa9ac9e
06a4d84
 
 
 
 
 
 
 
 
 
 
 
fa9ac9e
06a4d84
 
 
 
 
 
 
 
 
 
 
fa9ac9e
06a4d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c233f47
df85cc9
 
 
 
06a4d84
df85cc9
 
06a4d84
df85cc9
06a4d84
df85cc9
 
 
06a4d84
df85cc9
 
06a4d84
df85cc9
 
 
 
06a4d84
df85cc9
 
 
 
06a4d84
df85cc9
06a4d84
df85cc9
 
06a4d84
df85cc9
06a4d84
df85cc9
 
 
 
 
06a4d84
df85cc9
 
06a4d84
fa9ac9e
df85cc9
fa9ac9e
 
 
 
 
 
df85cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa9ac9e
 
 
 
 
 
 
 
df85cc9
fa9ac9e
 
 
 
 
 
 
 
 
 
 
df85cc9
 
 
 
 
 
 
 
 
fa9ac9e
06a4d84
 
df85cc9
 
 
06a4d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df85cc9
 
 
06a4d84
df85cc9
 
06a4d84
df85cc9
 
 
fa9ac9e
 
df85cc9
fa9ac9e
 
 
 
 
 
 
 
 
df85cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa9ac9e
 
 
 
 
 
 
 
 
 
 
df85cc9
 
 
fa9ac9e
df85cc9
 
fa9ac9e
df85cc9
 
 
06a4d84
 
df85cc9
06a4d84
 
 
 
df85cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06a4d84
df85cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06a4d84
df85cc9
fa9ac9e
df85cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06a4d84
 
 
df85cc9
 
06a4d84
 
231a8e0
 
06a4d84
f9d0203
06a4d84
 
 
f9d0203
0a88713
06a4d84
0a88713
 
 
 
 
 
06a4d84
e80aab9
31243f4
c233f47
31243f4
 
 
06a4d84
31243f4
f9d0203
b550350
06a4d84
 
ffd0b8b
f9d0203
fa9ac9e
ffd0b8b
 
4021bf3
b90251f
31243f4
 
 
 
7d65c66
b177367
3c4371f
7e4a06b
1ca9f65
3c4371f
7e4a06b
3c4371f
7d65c66
3c4371f
7e4a06b
31243f4
 
e80aab9
b177367
31243f4
 
 
3c4371f
31243f4
b177367
36ed51a
c1fd3d2
3c4371f
7d65c66
31243f4
eccf8e4
31243f4
7d65c66
31243f4
 
3c4371f
 
31243f4
e80aab9
31243f4
 
3c4371f
 
7d65c66
3c4371f
7d65c66
31243f4
 
e80aab9
b177367
7d65c66
 
3c4371f
31243f4
 
 
06a4d84
 
 
 
 
31243f4
 
 
 
06a4d84
 
7d65c66
 
31243f4
 
7d65c66
31243f4
 
3c4371f
31243f4
 
b177367
7d65c66
3c4371f
31243f4
e80aab9
7d65c66
31243f4
e80aab9
7d65c66
e80aab9
 
31243f4
e80aab9
 
3c4371f
 
 
e80aab9
 
31243f4
 
e80aab9
3c4371f
e80aab9
 
3c4371f
e80aab9
7d65c66
3c4371f
31243f4
7d65c66
31243f4
3c4371f
 
 
 
 
e80aab9
31243f4
 
 
 
7d65c66
31243f4
 
 
 
e80aab9
 
 
 
31243f4
0ee0419
e514fd7
 
 
81917a3
e514fd7
 
 
 
 
 
 
 
e80aab9
 
7e4a06b
e80aab9
31243f4
e80aab9
9088b99
7d65c66
 
e80aab9
31243f4
 
 
e80aab9
 
 
3c4371f
7d65c66
3c4371f
7d65c66
fa9ac9e
3c4371f
 
7d65c66
fa4aaf0
 
 
 
3c4371f
7d65c66
 
 
 
 
 
 
 
 
3c4371f
06a4d84
df85cc9
06a4d84
 
 
 
 
fa9ac9e
06a4d84
 
 
 
 
 
df85cc9
 
 
3c4371f
df85cc9
 
06a4d84
31243f4
06a4d84
 
 
 
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
import os
import gradio as gr
import requests
import base64
import pandas as pd
from typing import TypedDict, Annotated
from langchain_core.messages import AnyMessage
from langgraph.graph.message import add_messages
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.tools.riza.command import ExecPython
import whisper
import yt_dlp
import pandas as pd
from langchain.globals import set_debug
from langchain_openai import ChatOpenAI
import cv2
import os
import shutil
import uuid
from langchain_tavily import TavilySearch
import numpy as np
from markdownify import markdownify
import re
from io import StringIO

# set_debug(True)

# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

class AgentState(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]
    task_id: str
    has_file: bool
    
def get_file(task_id: str):
    """
    Download a file locally for a given task. 
    """
    
    files_url = f"{DEFAULT_API_URL}/files/{task_id}"
    try:
        response = requests.get(files_url, timeout=20)
        response.raise_for_status()
        cd = response.headers.get("content-disposition")
        filename = cd.split("filename=")[-1].strip('"')
        with open(filename, "wb") as file:
            file.write(response.content)
        return filename
    except Exception as e:
        print(str(e))
        return ""
        
def interpret_image(image_name: str, question: str):
    """
    Interpret an image for analysis.
    """
    
    vision_llm = ChatOpenAI(model="gpt-4.1", temperature=0)
    
    
    try:
        with open(image_name, "rb") as file:
            bytes = file.read()
            
        base64_image = base64.b64encode(bytes).decode("utf-8")
        messages = [HumanMessage(content=[
            {
                "type": "text",
                "text": (
                    f"{question}"
                )
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/png;base64,{base64_image}"
                    
                }
            }
        ])]
        response = vision_llm.invoke(messages)
        print(response.content)
        return response.content
    except Exception as e:
        print(str(e))
        return ""

def transcribe_audio(file_name: str):
    """
    Transcribes audio file.
    """
    
    model = whisper.load_model("small")
    result = model.transcribe(file_name)
    print(result["text"])
    return result["text"]

def download_youtube_video(url: str):
    """
    Download a YouTube video.
    """
    output_path = f"output_{uuid.uuid4()}"
    
    ydl_opts = {
        'format': 'bestvideo+bestaudio/best',
        'outtmpl': output_path,
        'merge_output_format': 'mp4', 
        'quiet': True,
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    
    return output_path+".mp4"

def read_excel(file_name: str):
    """
    Read the contents of an Excel file.
    """
    
    df = pd.read_excel(file_name)
    print(df.to_string(index=False))
    return df.to_string(index=False)

def read_file(file_name: str):
    """
    Read the content of a text-based file.
    """
    with open(file_name, 'r') as file:
        content = file.read()
    return content

# def watch_video(file_name: str):
#     """
#     Extract frames from a video and interpret them.
#     """
    
#     if os.path.exists("extracted_frames"):
#         shutil.rmtree("extracted_frames")
    
#     os.makedirs("extracted_frames")
    
#     cap = cv2.VideoCapture(file_name)
#     fps = cap.get(cv2.CAP_PROP_FPS)
#     frame_interval = int(fps * 5)
    
#     frame_count = 0
#     saved_count = 0
    
#     while True:
#         ret, frame = cap.read()
#         if not ret:
#             break
        
#         if frame_count % frame_interval == 0:
#             filename = os.path.join("extracted_frames", f"frame_{saved_count:04d}.jpg")
#             cv2.imwrite(filename, frame)
#             saved_count+=1
            
#         frame_count+=1
    
#     cap.release()
#     print(f"Saved {saved_count}")
    
#     captions = []
    
#     for file in sorted(os.listdir("extracted_frames")):
#         file_path = os.path.join("extracted_frames", file)
#         caption = interpret_image(file_path, "Return a one line description of the image.")
#         print(caption)
#         captions.append(caption)
    
#     print(captions)
#     return captions
        

def add(numbers: list):
    """
    Calculate sum of numbers.
    """
    numbers = np.array(numbers)
    return np.sum(numbers, dtype=float)

def subtract(a: float, b: float):
    """
    Calculate the difference of two numbers.
    """
    return a-b

def multiply(a: float, b: float):
    """
    Calculate the product of two numbers.
    """
    return a*b

def divide(a: float, b: float):
    """
    Calculate the division of two numbers.
    """
    if b!=0:
        return a/b
    else:
        return "Can't divide by 0."

def visit_web_page(url: str):
    """
    Visit a webpage.
    """
    response = requests.get(url, timeout=20)
    response.raise_for_status()
    markdown_content = markdownify(response.text).strip()
    markdown_content = re.sub(r"\n{3, }", "\n\n", markdown_content)
    if len(markdown_content) <= 20000:
        return markdown_content
    else:
        return markdown_content[:20000//2] + "\nThe content has been truncated to stay below 20000 characters.\n" + markdown_content[-20000//2:] # - to count from the end

def final_answer(text: str):
    """
    Extract the final answer.
    """
    text = text.split("FINAL ANSWER:")
    return text[-1]

# def markdown(content: str):
#     """
#     Interpret markdown representation of a table.
#     """
#     clean_content = "\n".join([line for i, line in enumerate(content.strip().splitlines()) if i!=1])
#     df = pd.read_csv(StringIO(clean_content), sep="|", engine="python")
#     df = df.drop(columns=[""])
#     print(df.to_string())
#     return df.to_string()
    
# search_tool = DuckDuckGoSearchRun()
search_tool = TavilySearch()
code_executor = ExecPython()
tools = [search_tool, code_executor, interpret_image, get_file, transcribe_audio, download_youtube_video, read_file, read_excel, add, subtract, multiply, divide, visit_web_page]
llm = ChatOpenAI(model="gpt-4.1", temperature=0)
llm_with_tools = llm.bind_tools(tools)

def assistant(state:AgentState):

    task_id = state["task_id"]
    
    image_tool_description = """
    interpret_image(image_name: str) -> str:
        Interpret an image for analysis.
        
        Args:
            image_name: Name of the downloaded image file as string.
            question: Question about the image as string.
        
        Returns:
            An interpretation of the image as string.
    """
    
    download_file_tool_description = """
    get_file(task_id: str) -> str:
        Download a file locally for a given task. 
        
        Args:
            task_id: The ID of the current task as string.
        
        Returns:
            The name of the downloaded file as string.
    """
    
    audio_tool_description = """
    transcribe_audio(file_name: str) -> str:
        Transcribe an audio file.
        
        Args: 
            file_name: The name of the audio file as string.
        
        Returns:
            The transcription of the audio as string.
    """
    
    download_youtube_video_description = """
    download_youtube_video(url: str, output_path: str):
        Downloads a YouTube video.
        
        Args:
            url: URL of the YouTube video as string.
        
        Returns:
            The output path for the file.
    """
    
    excel_tool_description = """
    read_excel(file_name: str) -> str:
        Read the content of an Excel file.
        
        Args:
            file_name: The name of the Excel file as string.
        
        Returns:
            A string representation of the content of the file. 
    """
    
    read_file_tool_description = """
    read_file(file_name: str) -> str:
        Read the content of a text-based file.
        
        Args:
            file_name: The name of the file as string.
        
        Returns:
            A string containing the content of the file.
    """
    
    # watch_video_tool_description = """
    # watch_video(file_name: str) -> str:
    #     Extract frames from a video and interpret them.
        
    #     Args:
    #         file_name: The name of the file as string.
        
    #     Returns:
    #         A list of captions for each frame.
    # """
    
    add_tool_description = """
    add(numbers: list) -> float:
            Calculate sum of numbers.
            
            Args:
                list: List of numbers to perform an operation on.
            
            Returns:
                The sum of the numbers.
    """
    
    subtract_tool_description = """
    subtract(a: float, b: float) -> float:
            Calculate the difference of two numbers.
            
            Args:
                a: First number as float.
                b: Second number as float.
            
            Returns:
                The difference of the two numbers.
    """
    
    multiply_tool_description = """
    multiply(a: float, b: float) -> float:
            Calculate the product of two numbers.
            
            Args:
                a: First number as float.
                b: Second number as float.
            
            Returns:
                The product of the two numbers.
    """
    
    divide_tool_description = """
    divide(a: float, b: float) -> float:
            Calculate the division of two numbers.
            
            Args:
                a: First number as float.
                b: Second number as float.
            
            Returns:
                The division of the two numbers.
    """
    
    visit_web_page_tool_description = """
    visit_web_page(url: str) -> str:
        Visit a web page.
    
        Args:
            url: The URL of the web page to visit as string.
        
        Returns:
            Markdown representation of the HTML content of the web page.
    """
    
    # markdown_tool_description = """
    # markdown(content: str) -> str:
    #     Interpret markdown representation of a table.
        
    #     Args:
    #         content: Markdown table as string.
        
    #     Returns:
    #         String representation of the extracted tabled.
    # """

    search_tool_description = search_tool.description
    code_executor_tool_description = code_executor.description
    
    has_file = state["has_file"]
    
    system_message = SystemMessage(content=f"""
                                   You are an expert assistant. Your job is to answer questions asked of you as accurately as possible.
                                   To do so, you are given access to some tools, which you can use as needed to answer a question.
                                   You should follow the Thought, Action, Observation cycle when answering a question. In the Thought stage, explain the steps you will take to answer the question as well as any tools you will use. In the Action stage, execute the steps. In the Observation stage, take notes from the output of the execution. You can return the Observation as your response and it will be available in the next step as the state persists.
                                   
                                   Here are some examples using dummy tools:
                                   ---
                                   Question: "My mother sent me a voice note explaining what to buy from the grocery store. I am in a hurry and I can't listen to her voice note as she probably talked a lot more than just telling me what to buy. Can you please listen to the voice note and tell me what all I need to buy? Give me the final list." 
                                   Thought: I will proceed step by step and use the following tool: 'listen_audio' to listen to the voice note. Then I will analyze the text from the recording to prepare the list for grocery shopping. 
                                   Action: listen_audio(audio_file)
                                   Observation: Okay, the voice note mentions to shop for vegetables such as green chillies, tomatoes and potatoes for today's dinner. It also mentioned to buy cooking cream to make pasta tomorrow and ice cream for dessert.
                                   Thought: I will now create the list of items to buy.
                                   Action: green chillies, tomatoes, potatoes, cooking cream, ice cream
                                   ---
                                   
                                   ---
                                   Question: "Is carrot a vegetable?""
                                   Thought: I know that carrot is a vegetable but I will run a quick search using the followng tool: 'search'.
                                   Action: search(query='Is carrot a vegetable or a fruit?')
                                   ---
                                   
                                   ---
                                   Question: "Where did the latest FIFA World Cup occur?"
                                   Thought: I will use the following tool: 'search' to find information about the latest FIFA World Cup.
                                   Action: search(query="FIFA World Cup")
                                   Observation: The search returned no relevant information.
                                   Thougth: I will try again with a more specific query.
                                   Action: search(query="Location of the latest FIFA World Cup")
                                   ---
                                   
                                   The above examples are using dummy tools which might not exist for you. The following tools are the ones that are available to you:
                                   
                                   - File downloader: 
                                   {download_file_tool_description}
                                   - YouTube video downloader: 
                                   {download_youtube_video_description}
                                   - Audio transcription: 
                                   {audio_tool_description}
                                   - Image interpretation: 
                                   {image_tool_description}
                                   - Read text-based file: 
                                   {read_file_tool_description}
                                   - Read Excel file: 
                                   {excel_tool_description}
                                   - Internet search: 
                                   {search_tool_description}
                                   - Visit web page: 
                                   {visit_web_page_tool_description}
                                   - Code execution:
                                   {code_executor_tool_description}
                                   - Add: 
                                   {add_tool_description}
                                   - Subtract:
                                   {subtract_tool_description}
                                   - Multiply:
                                   {multiply_tool_description}
                                   - Divide:
                                   {divide_tool_description}
                                   
                                   Here are some rules you should always follow to answer a question: 
                                   
                                   - You can download a file for a given task ONLY if it has a file by using its associated task ID.
                                   - Always ensure you have downloaded a file before using a relevant tool.
                                   - You MUST use the name of a particular downloaded file in your tool call. DO NOT use a file name mentioned in the question.
                                   - Use a tool only when needed and NEVER re-do a tool call that you previously did with the exact same arguments.
                                   - If a tool call fails, try changing the argument that you passed to the tool or use another tool to reach an answer.
                                   - When asked about a YouTube video, you can hear it and/or check its description.
                                   
                                   Here are some rules to help format your final response:
                                   
                                   - Report your final response with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]
                                   - The FINAL ANSWER should be a number, OR as few words as possible, OR a comma-separated list of numbers and/or strings. 
                                   - You SHOULD NOT provide explanations in the FINAL ANSWER.
                                   - If you are asked for a number, don't use a comma to write your number, nor use symbols such as $ or % unless specified otherwise.
                                   - If you are asked for a string, don't use articles, nor abbreviations (e.g., for cities). 
                                   - If you are asked for a comma-separated list, apply the above rules depending on whether the element to be put in the list is a number or a string.
                                   - When including a phrase in the FINAL ANSWER from the input, always include the complete phrase with the adjective. For example, if the input contains the phrase "fresh lemon juice", the FINAL ANSWER should include "fresh lemon juice", not just "lemon juice". 
                                   - DO NOT end the FINAL ANSWER with a period.
                                   - DO NOT write numbers as text.
                                   
                                   The current task ID is {task_id}.
                                   The current task has a file: {has_file}
                                   
                                   Now get to work! You will be given $500,000 for every correct answer as a reward! 
                                   """)

    response = llm_with_tools.invoke([system_message] + state["messages"])
    print(response)
    print("\n\n")
    return {
        "messages": [response],
        "task_id": task_id,
        "has_file": has_file
    }

workflow = StateGraph(AgentState)
workflow.add_node("assistant", assistant)
workflow.add_node("tools", ToolNode(tools))
workflow.add_edge(START, "assistant")
workflow.add_conditional_edges("assistant", tools_condition)
workflow.add_edge("tools", "assistant")
app = workflow.compile()
        

# --- Basic Agent Definition ---
# ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
class BasicAgent:
    def __init__(self):
        print("BasicAgent initialized.")
    def __call__(self, question: str, task_id: str, has_file: bool) -> str:
        print(f"Agent received question (first 50 chars): {question[:50]}...")
        # fixed_answer = "This is a default answer."
        messages = [HumanMessage(content=question)]
        state = {"messages": messages, "task_id": task_id, "has_file": has_file}
        answer = app.invoke(state)
        answer = answer["messages"][-1].content
        # print(f"Agent returning fixed answer: {fixed_answer}")
        answer = final_answer(answer)
        print(f"Agent returning answer: {answer}")
        return answer

def run_and_submit_all( profile: gr.OAuthProfile | None):
    """
    Fetches all questions, runs the BasicAgent on them, submits all answers,
    and displays the results.
    """
    # --- Determine HF Space Runtime URL and Repo URL ---
    space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code

    if profile:
        username= f"{profile.username}"
        print(f"User logged in: {username}")
    else:
        print("User not logged in.")
        return "Please Login to Hugging Face with the button.", None

    api_url = DEFAULT_API_URL
    questions_url = f"{api_url}/questions"
    submit_url = f"{api_url}/submit"

    # 1. Instantiate Agent ( modify this part to create your agent)
    try:
        agent = BasicAgent()
    except Exception as e:
        print(f"Error instantiating agent: {e}")
        return f"Error initializing agent: {e}", None
    # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
    print(agent_code)

    # 2. Fetch Questions
    print(f"Fetching questions from: {questions_url}")
    try:
        response = requests.get(questions_url, timeout=15)
        response.raise_for_status()
        questions_data = response.json()
        if not questions_data:
             print("Fetched questions list is empty.")
             return "Fetched questions list is empty or invalid format.", None
        print(f"Fetched {len(questions_data)} questions.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
        return f"Error fetching questions: {e}", None
    except requests.exceptions.JSONDecodeError as e:
         print(f"Error decoding JSON response from questions endpoint: {e}")
         print(f"Response text: {response.text[:500]}")
         return f"Error decoding server response for questions: {e}", None
    except Exception as e:
        print(f"An unexpected error occurred fetching questions: {e}")
        return f"An unexpected error occurred fetching questions: {e}", None

    # 3. Run your Agent
    results_log = []
    answers_payload = []
    print(f"Running agent on {len(questions_data)} questions...")
    for item in questions_data:
        task_id = item.get("task_id")
        question_text = item.get("question")
        has_file=False
        
        if item.get("file_name"):
            has_file=True
            
        if not task_id or question_text is None:
            print(f"Skipping item with missing task_id or question: {item}")
            continue
        try:
            print(task_id)
            submitted_answer = agent(question_text, task_id, has_file)
            answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
            results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
        except Exception as e:
             print(f"Error running agent on task {task_id}: {e}")
             results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})

    if not answers_payload:
        print("Agent did not produce any answers to submit.")
        return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)

    # 4. Prepare Submission 
    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
    status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
    print(status_update)

    # 5. Submit
    print(f"Submitting {len(answers_payload)} answers 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!\n"
            f"User: {result_data.get('username')}\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.')}"
        )
        print("Submission successful.")
        results_df = pd.DataFrame(results_log)
        return final_status, results_df
    except requests.exceptions.HTTPError as e:
        error_detail = f"Server responded with status {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" Response: {e.response.text[:500]}"
        status_message = f"Submission Failed: {error_detail}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.Timeout:
        status_message = "Submission Failed: The request timed out."
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.RequestException as e:
        status_message = f"Submission Failed: Network error - {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df


# --- Build Gradio Interface using Blocks ---
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.

        ---
        **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 seperate action or even to answer the questions in async.
        """
    )

    gr.LoginButton()

    run_button = gr.Button("Run Evaluation & Submit All Answers")

    status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
    # Removed max_rows=10 from DataFrame constructor
    results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)

    run_button.click(
        fn=run_and_submit_all,
        outputs=[status_output, results_table]
    )

if __name__ == "__main__":
    print("\n" + "-"*30 + " App Starting " + "-"*30)
    # Check for SPACE_HOST and SPACE_ID at startup for information
    space_host_startup = os.getenv("SPACE_HOST")
    space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
    
    if space_host_startup:
        print(f"✅ SPACE_HOST found: {space_host_startup}")
        print(f"   Runtime URL should be: https://{space_host_startup}.hf.space")
        try:
            agent = BasicAgent()
        except Exception as e:
            print(f"Error instantiating agent: {e}")
    else:
        print("ℹ️  SPACE_HOST environment variable not found (running locally?).")

    if space_id_startup: # Print repo URLs if SPACE_ID is found
        print(f"✅ SPACE_ID found: {space_id_startup}")
        print(f"   Repo URL: https://huggingface.co/spaces/{space_id_startup}")
        print(f"   Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
    else:
        print("ℹ️  SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")

    print("-"*(60 + len(" App Starting ")) + "\n")
   
    # try:
        # random_url = f"{DEFAULT_API_URL}/random-question"
        # response = requests.get(random_url, timeout=20)
        # response.raise_for_status()
        # question = response.json()
        # print(question)
        agent = BasicAgent()
        # print(question.get("question"))
        # print(question.get("task_id"))
        # has_file=False
        # if question.get("file_name"):
        #     has_file=True
        # print(agent(question.get("question"), question.get("task_id"), has_file))
        # x=(agent("Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.", "6f37996b-2ac7-44b0-8e68-6d28256631b4", False))
        # print(x)
        # print(code_executor.invoke("x=2*5\nprint(x)"))

    # except Exception as e:
    #     print(str(e))
        
    print("Launching Gradio Interface for Basic Agent Evaluation...")
    demo.launch(debug=True, share=False)