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)