File size: 30,536 Bytes
10e9b7d
 
eccf8e4
7d65c66
3c4371f
e0bb1bd
 
b88bd54
cbaf60b
66a9e16
 
e82194b
06110ba
e57440b
06110ba
e57440b
 
fb69e43
 
aaca609
fb69e43
 
 
249e16a
e82194b
10e9b7d
d59f015
e80aab9
3db6293
e80aab9
fb69e43
e57440b
 
 
 
 
fb69e43
 
e57440b
20196c3
fb69e43
 
 
42c2c7b
 
 
fb69e43
e0bb1bd
 
 
 
 
 
fb69e43
 
 
 
e0bb1bd
 
f3c8a54
b88bd54
66a9e16
e0bb1bd
 
 
fb69e43
 
 
 
f3c8a54
fb69e43
 
 
b88bd54
 
 
 
 
 
66a9e16
 
 
 
 
 
9758d8e
 
 
 
 
 
fb69e43
 
42c2c7b
fb69e43
 
 
9758d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66a9e16
 
 
 
 
 
 
 
 
 
 
 
 
38c208a
 
e82194b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0511f38
 
66a9e16
0511f38
 
66a9e16
0511f38
66a9e16
b88bd54
 
 
 
471d603
b88bd54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b8dbc4
 
 
b88bd54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66a9e16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b88bd54
 
 
fb69e43
 
 
 
d241afa
d02e19c
b88bd54
d241afa
 
 
 
 
fb69e43
 
 
 
 
d241afa
fb69e43
 
d241afa
fb69e43
 
b88bd54
 
 
 
 
 
 
66a9e16
 
 
 
 
 
 
9758d8e
 
 
 
 
 
 
fb69e43
d241afa
9758d8e
fb69e43
 
d241afa
fb69e43
 
dc826ab
 
 
 
 
fb69e43
31243f4
d59f015
31243f4
 
 
241184b
 
 
 
 
 
 
e57440b
e732c32
42c2c7b
76098db
471d603
 
4f281de
 
 
 
 
 
 
 
 
471d603
 
3bedb44
 
 
 
b24a24f
 
dc826ab
3bedb44
b24a24f
dc826ab
107cf94
e198ae4
b24a24f
dc826ab
3bedb44
107cf94
 
 
 
 
f3c8a54
8ed8349
107cf94
 
e0bb1bd
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
f7eaaea
31243f4
 
 
 
 
 
b88bd54
7d65c66
 
31243f4
 
7d65c66
31243f4
 
3c4371f
31243f4
 
b177367
7d65c66
3c4371f
31243f4
e80aab9
7956c84
 
 
 
 
 
 
cb1fed7
860a3bc
5c77aec
7d65c66
7956c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c422f5d
7956c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
 
e57440b
e80aab9
 
31243f4
0ee0419
e514fd7
 
 
81917a3
e514fd7
 
 
 
 
 
 
 
e80aab9
 
7e4a06b
e80aab9
31243f4
e80aab9
9088b99
7d65c66
 
e80aab9
31243f4
 
 
e80aab9
 
 
3c4371f
7d65c66
3c4371f
7d65c66
 
3c4371f
 
7d65c66
3c4371f
7d65c66
 
 
 
 
 
 
 
 
3c4371f
 
31243f4
3c4371f
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
import os
import gradio as gr
import requests
import inspect
import pandas as pd
import re
import time
import base64
import json
import sys
import contextlib
import traceback
import io
#from tavily import TavilyClient
#from io import StringIO
from langchain_tavily import TavilySearch
from langgraph.prebuilt import create_react_agent
from langgraph.graph.message import add_messages
from langgraph_supervisor import create_supervisor
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, SystemMessage, BaseMessage
from langchain.chat_models import init_chat_model
from typing import Annotated,Sequence, TypedDict, Literal, Dict
from contextlib import redirect_stdout, redirect_stderr

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

#ENV
def _set_if_undefined(var: str):
    if not os.environ.get(var):
        os.environ[var] = userdata.get(var)

_set_if_undefined("TAVILY_API_KEY")
_set_if_undefined("GEMINI_API_KEY")
##_set_if_undefined("HUGGINGFACEHUB_API_TOKEN")

TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
##HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")

CHESSVISION_TO_FEN_URL = "http://app.chessvision.ai/predict"
CHESS_MOVE_API = "https://chess-api.com/v1"

#PROMPTS
#prompt_recomendado = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
#                        FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
#                        If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
#                        If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
#                        If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""

prompt_recomendado = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
                        FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
                        If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
                        If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
                        If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
                        To assist in your task, you can supervise other agents who perform specific tasks that could not be handled by tools, since they require the processing of another LLM. Below, I will inform you about your assistants:
                        - web_research_agent. Assign web research related tasks to this agent, prioritizing the use of Wikipedia sources
                        - chess_position_review_agent. Assign chess position review related tasks to this agent
                        - python_code_runner_agent. Assign python code execution related tasks to this agent
                        Assign work to one agent at a time, do not call agents in parallel.
                        Priorize the use of tools and another agents to help in reasoning.
                        When a file or URL is entered at the prompt, use it in tools or other agents, both are prepared to handle files and URLs."""

prompt_search = """You are a web research agent.
                   INSTRUCTIONS:
                   Assist ONLY with research-related tasks, DO NOT do any math
                   If a source is provided in the task, you MUST use it as your primary source of information
                   After you're done with your tasks, respond to the supervisor directly
                   Respond ONLY with the results of your work, do NOT include ANY other text."""

prompt_chess = """You are a chess position reviewing agent.
                   INSTRUCTIONS:
                   Assist ONLY with tasks related to chess position reviewing, DO NOT do any math
                   After you're done with your tasks, respond to the supervisor directly
                   Respond ONLY with the results of your work, do NOT include ANY other text."""

prompt_python_execute = """You are a python code execution agent.
                           INSTRUCTIONS:
                           Assist ONLY with tasks related to running python code, DO NOT do any math
                           After you're done with your tasks, respond to the supervisor directly
                           Respond ONLY with the results of your work, do NOT include ANY other text."""

prompt_botanical_classification = """You are a vegetable botanical classification agent.
                           INSTRUCTIONS:
                           Assist ONLY with tasks related to classificating vegatables, DO NOT do any math
                           After you're done with your tasks, respond to the supervisor directly
                           Respond ONLY with the results of your work, do NOT include ANY other text."""

#TOOLS
web_search = TavilySearch(
        max_results=5,
        topic="general",
    )

def get_botanical_classification_tool(item_name):
    """
    Provides the botanical classification (fruit, vegetable, or other)
    for a given food item, adhering to botanical definitions.
    Args:
        item_name (str): The name of the food item (e.g., "bell pepper", "sweet potato").
    Returns:
        dict: A dictionary containing:
              - 'item': The normalized item name.
              - 'botanical_category': 'fruit', 'vegetable', 'other', or 'unclassified'.
              - 'botanical_part': The botanical part of the plant (e.g., 'matured ovary', 'root', 'leaf'),
                                  or 'N/A' if not applicable/unknown.
              - 'notes': Any additional botanical notes or clarifications.
    """

    # --- Curated Botanical Database ---
    # This dictionary holds the botanical classifications.
    # It's crucial this data is accurate according to botanical science.
    # You will need to expand this as needed for your full grocery list.
    botanical_data = {
        "sweet potatoes": {
            "botanical_category": "vegetable",
            "botanical_part": "root/tuber",
            "notes": "Edible root of the plant."
        },
        "fresh basil": {
            "botanical_category": "vegetable",
            "botanical_part": "leaf",
            "notes": "Edible leaves of the herb."
        },
        "plums": {
            "botanical_category": "fruit",
            "botanical_part": "matured ovary",
            "notes": "Simple fleshy fruit (drupe)."
        },
        "green beans": {
            "botanical_category": "fruit",
            "botanical_part": "matured ovary (legume)",
            "notes": "Botanically a fruit (legume) containing seeds."
        },
        "rice": {
            "botanical_category": "fruit",
            "botanical_part": "matured ovary (caryopsis)",
            "notes": "A grain, which is botanically a dry fruit (caryopsis)."
        },
        "corn": {
            "botanical_category": "fruit",
            "botanical_part": "matured ovary (caryopsis)",
            "notes": "A grain, which is botanically a dry fruit (caryopsis)."
        },
        "bell pepper": {
            "botanical_category": "fruit",
            "botanical_part": "matured ovary",
            "notes": "Developed from the flower's ovary and contains seeds."
        },
        "whole allspice": { # Allspice berries
            "botanical_category": "fruit",
            "botanical_part": "dried berry",
            "notes": "Dried unripe berries of the Pimenta dioica plant."
        },
        "acorns": {
            "botanical_category": "fruit",
            "botanical_part": "nut (type of dry fruit)",
            "notes": "A nut, which is botanically a type of dry fruit."
        },
        "broccoli": {
            "botanical_category": "vegetable",
            "botanical_part": "flower/stem",
            "notes": "Edible flower heads and stalks."
        },
        "celery": {
            "botanical_category": "vegetable",
            "botanical_part": "stem/petiole",
            "notes": "Edible leaf stalks."
        },
        "zucchini": {
            "botanical_category": "fruit",
            "botanical_part": "matured ovary",
            "notes": "A type of berry (pepo) from a flowering plant."
        },
        "lettuce": {
            "botanical_category": "vegetable",
            "botanical_part": "leaf",
            "notes": "Edible leaves."
        },
        "peanuts": {
            "botanical_category": "fruit",
            "botanical_part": "legume (matured ovary)",
            "notes": "Botanically a fruit (legume), despite growing underground."
        },
        # Non-plant items or items not strictly fruit/vegetable botanically
        "milk": {
            "botanical_category": "other",
            "botanical_part": "N/A",
            "notes": "Dairy product (animal)."
        },
        "eggs": {
            "botanical_category": "other",
            "botanical_part": "N/A",
            "notes": "Animal product."
        },
        "flour": {
            "botanical_category": "other",
            "botanical_part": "N/A",
            "notes": "Processed grain product (typically wheat, which is a fruit)."
        },
        "whole bean coffee": {
            "botanical_category": "other", # The bean itself is a seed, not the entire fruit
            "botanical_part": "seed",
            "notes": "The coffee 'bean' is botanically the seed of the coffee cherry (a fruit)."
        },
        "oreos": {
            "botanical_category": "other",
            "botanical_part": "N/A",
            "notes": "Processed food item."
        }
    }

    # Normalize the input item name for lookup
    normalized_item = item_name.strip().lower()

    # Handle pluralization/singularization for common cases if not explicitly in data
    # This is a simple approach; for more robustness, you'd need a proper NLP library.
    if normalized_item.endswith("s") and normalized_item[:-1] in botanical_data:
        normalized_item = normalized_item[:-1]
    elif normalized_item + "s" in botanical_data:
        # Check if the plural form exists if input is singular
        if item_name.strip().lower() + "s" in botanical_data:
            normalized_item = item_name.strip().lower() + "s"

    # Retrieve classification
    classification = botanical_data.get(normalized_item)

    if classification:
        return {
            "item": item_name,
            "botanical_category": classification["botanical_category"],
            "botanical_part": classification["botanical_part"],
            "notes": classification["notes"]
        }
    else:
        # If the item is not found in the database
        return {
            "item": item_name,
            "botanical_category": "unclassified",
            "botanical_part": "N/A",
            "notes": "Classification not found in the current database."
        }

def python_code_runner_tool(task_id:str) -> str:
    """
        Download and run python code, capturing the output.
        Args:
            task_id: Task ID necessary to retrieve the python code to be run.
        Returns:
            String with the output of the python code.
    """
    print(f"python code runner invocada com os seguintes parametros:")
    print(f"task_id: {task_id}")

    python_code = download_file_as_string(task_id)

    print(f"python_code: {python_code}")

    saida = io.StringIO()
    erros = io.StringIO()

    try:
        # Captura stdout e stderr usando contexto
        with redirect_stdout(saida), redirect_stderr(erros):
            exec(python_code, {'__name__': '__main__'})

        # Pega o conteúdo das saídas
        saida_valor = saida.getvalue()
        erro_valor = erros.getvalue()

        if erro_valor:
            return f"[ERRO DE EXECUÇÃO]:\n{erro_valor}"
            
        return saida_valor if saida_valor.strip() else "[SEM SAÍDA]"

    except Exception:
        return f"[EXCEÇÃO DURANTE EXECUÇÃO]:\n{traceback.format_exc()}"
        
    #with stdoutIO() as s:
    #    exec(python_code)

    #output = s.getvalue()
    #print(f"Captured output: {output}") 

    return 0

def chess_image_to_fen_tool(task_id:str, current_player: Literal["black", "white"]) -> Dict[str,str]:
    """
        Convert chess image to FEN (Forsyth-Edwards Notation) notation.
        Args:
            task_id: Task ID necessary to retrieve the image with the chess board position.
            current_player: Whose turn it is to play. Must be either 'black' or 'white'.
        Returns:
            JSON with FEN (Forsyth-Edwards Notation) string representing the current board position.
    """
    print(f"Image to Fen invocada com os seguintes parametros:")
    print(f"task_id: {task_id}")
    print(f"current_player: {current_player}")


    if current_player not in ["black", "white"]:
        raise ValueError("current_player must be 'black' or 'white'")

    base64_image = download_file_as_base64(task_id)
    if not base64_image:
        raise ValueError("Failed to encode image to base64.")
    base64_image_encoded =  f"data:image/jpeg;base64,{base64_image}"
    url = CHESSVISION_TO_FEN_URL
    payload = {
        "board_orientation": "predict",
        "cropped": False,
        "current_player": "black",
        "image": base64_image_encoded,
        "predict_turn": False
    }

    response = requests.post(url, json=payload)
    if response.status_code == 200:
        dados = response.json()
        if dados.get("success"):
            print(f"Retorno Chessvision {dados}")
            fen = dados.get("result")
            fen = fen.replace("_", " ") #retorna _ no lugar de espaço em branco
            return json.dumps({"fen": fen})
        else:
            raise Exception("Requisição feita, mas falhou na predição.")
    else:
        raise Exception(f"Erro na requisição: {response.status_code}")

def chess_fen_get_best_next_move_tool(fen: str, current_player: Literal["black", "white"]) -> str:
    """
        Return the best move in algebraic notation.
        Args:
            fen: FEN (Forsyth-Edwards Notation) notation.
        Returns:
            Best move in algebraic notation.
    """
    if not fen:
        raise ValueError("fen must be provided.")
    if current_player not in ["black", "white"]:
        raise ValueError("current_player must be 'black' or 'white'")


    url = CHESS_MOVE_API
    payload = {
       "fen": fen
        #,
       #"depth": 1
    }

    print(f"Buscando melhor jogada em {CHESS_MOVE_API} - {payload}")

    response = requests.post(url, json=payload)
    if response.status_code == 200:
        #print(f"Retorno melhor jogada --> {response.text}")
        dados = response.json()
        move_algebric_notation = dados.get("san")
        move = dados.get("text")
        print(f"Melhor jogada segundo chess-api.com -> {move}")

        return move_algebric_notation

    else:
        raise Exception(f"Erro na requisição: {response.status_code}")

def download_file(task_id: str):
    if not fen:
        raise ValueError("task_id must be provided.")
    # Construct the URL
    url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
    
    # Send the request to download the file
    response = requests.get(url)
    
    if response.status_code == 200:
        # Get the content type from the response headers to determine the file extension
        content_type = response.headers.get('Content-Type', '')
        file_extension = ''
        
        # Map content types to file extensions
        if 'pdf' in content_type:
            file_extension = '.pdf'
        elif 'jpg' in content_type or 'jpeg' in content_type:
            file_extension = '.jpg'
        elif 'png' in content_type:
            file_extension = '.png'
        elif 'txt' in content_type:
            file_extension = '.txt'
        elif 'zip' in content_type:
            file_extension = '.zip'
        elif 'mp3' in content_type:
            file_extension = '.mp3'
        # Add more file types as necessary

        # If the extension can't be determined, default to .bin
        if not file_extension:
            file_extension = '.bin'
        
        # Set the path to the Downloads folder (adjust 'YourUsername' to your actual username)
        save_path = os.path.join(os.path.expanduser('~'), 'Downloads', f"{task_id}_file{file_extension}")
        
        # Save the file with the appropriate extension
        with open(save_path, 'wb') as f:
            f.write(response.content)
        print(f"File successfully downloaded and saved as {save_path}")

        return save_path
    else:
        print(f"Failed to download the file. Status code: {response.status_code}")

def download_file_as_base64(task_id: str) -> str:
    # Construct the URL
    url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
    
    # Send the request to download the file
    response = requests.get(url)
    
    if response.status_code == 200:
        # Encode the content to Base64
        encoded_bytes = base64.b64encode(response.content)
        encoded_str = encoded_bytes.decode('utf-8')  # Convert bytes to string
        return encoded_str
    else:
        raise Exception(f"Failed to download the file. Status code: {response.status_code}")

def download_file_as_string(task_id: str) -> str:
    # Construct the URL
    url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
    
    # Send the request to download the file
    response = requests.get(url)
    
    if response.status_code == 200:
        # Encode the content to Base64
        bytes = response.content
        encoded_str = bytes.decode('utf-8')  # Convert bytes to string
        return encoded_str
    else:
        raise Exception(f"Failed to download the file. Status code: {response.status_code}")        
        


tools = [web_search]

#LLMS
# Create LLM class 
gemini_llm = ChatGoogleGenerativeAI(
    model= "gemini-2.0-flash", # replace with "gemini-2.0-flash"
    temperature=0.0,
    max_tokens=None,
    timeout=None,
    max_retries=2,
    google_api_key=GEMINI_API_KEY,
)
# Bind tools to the model
#general_model = gemini_llm.bind_tools([get_weather_forecast])

#AGENTS
web_research_agent = create_react_agent(
    model=gemini_llm,
    tools=[web_search],
    prompt=prompt_search,
    name="web_research_agent"
)

chess_position_review_agent = create_react_agent(
    model=gemini_llm,
    tools=[chess_image_to_fen_tool,chess_fen_get_best_next_move_tool],
    prompt=prompt_chess,
    name="chess_position_review_agent"
)

python_code_runner_agent = create_react_agent(
    model=gemini_llm,
    tools=[python_code_runner_tool],
    prompt=prompt_python_execute,
    name="python_code_runner_agent"
)

vegetable_botanical_classification_agent = create_react_agent(
    model=gemini_llm,
    tools=[get_botanical_classification_tool],
    prompt=prompt_botanical_classification,
    name="vegetable_botanical_classification_agent"
)

supervisor = create_supervisor(
    model=gemini_llm,
    agents=[web_research_agent,chess_position_review_agent,python_code_runner_agent,vegetable_botanical_classification_agent],
    prompt=prompt_recomendado,
    add_handoff_back_messages=True,
    output_mode="full_history"
).compile()

#final answer
def stream_graph_updates(user_input: str):
    for event in graph.stream({"messages": [{"role": "user", "content": user_input}]}):
        for value in event.values():
            print("Assistant:", value["messages"][-1].content)

# --- Basic Agent Definition ---
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
class BasicAgent:
    def __init__(self):
        print("BasicAgent initialized.")

 #       print("create_react_agent")
 #       agent = create_react_agent(llm, [tavily_search_tool])

#        chat = ChatHuggingFace(llm=llm, verbose=True)
#        tools = [search_web_tool]
#        chat_with_tools = chat.bind_tools(tools)
        
    def __call__(self, question: str, task_id: str) -> str:
        print(f"Agent received question : {question}...")

        question = "Question: " + question + " Task ID: " + task_id

        messages = {
                        "messages": [
                            {
                                "role": "user",
                                "content": question
                            }
                        ]
                    }

        print (f"Input messages: {messages}.")

        events = supervisor.stream(
            messages,
            stream_mode="values",
        )

        listMessages = []
        
        for event in events:
            listMessages.extend(event["messages"])

        print(f"messages: {listMessages}\n")

        answer = listMessages[-1].content
        
        #answer = supervisor.invoke(messages)
        print(f"Answer: {answer}\n")

        start_index = answer.find("FINAL ANSWER: ")
        substring=""
        if start_index != -1:
            substring = answer[start_index+14:] 
        
        final_answer = substring #answer.removeprefix("FINAL ANSWER: ") #re.search(r"FINAL ANSWER:\s*(.*)", answer)
        print(f"Agent returning answer: {final_answer}\n")
        return final_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:
        time.sleep(90)
        task_id = item.get("task_id")
        question_text = item.get("question")
        if not task_id or question_text is None:
            print(f"Skipping item with missing task_id or question: {item}")
            continue
        try:
            submitted_answer = agent(question_text,task_id)
            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)

    #final_status = (
    #    f"Submission Successful!\n"
    #    f"User: aaaaa\n"
    #    f"Overall Score: 0% "
    #    f"(754546 correct)\n"
    #    f"Message: qwerty"
    #)
    results_df = pd.DataFrame(results_log)
    #return final_status, results_df

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

    print("Launching Gradio Interface for Basic Agent Evaluation...")
    demo.launch(debug=True, share=False)