|
|
import os |
|
|
import gradio as gr |
|
|
import requests |
|
|
import inspect |
|
|
import pandas as pd |
|
|
import re |
|
|
import time |
|
|
import base64 |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" |
|
|
|
|
|
|
|
|
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") |
|
|
|
|
|
|
|
|
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY") |
|
|
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") |
|
|
|
|
|
|
|
|
CHESSVISION_TO_FEN_URL = "http://app.chessvision.ai/predict" |
|
|
CHESS_MOVE_API = "https://chess-api.com/v1" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
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.""" |
|
|
|
|
|
|
|
|
web_search = TavilySearch( |
|
|
max_results=5, |
|
|
topic="general", |
|
|
) |
|
|
|
|
|
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: |
|
|
image_path: Path to the image file. |
|
|
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("_", " ") |
|
|
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: |
|
|
|
|
|
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.") |
|
|
|
|
|
url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}" |
|
|
|
|
|
|
|
|
response = requests.get(url) |
|
|
|
|
|
if response.status_code == 200: |
|
|
|
|
|
content_type = response.headers.get('Content-Type', '') |
|
|
file_extension = '' |
|
|
|
|
|
|
|
|
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' |
|
|
|
|
|
|
|
|
|
|
|
if not file_extension: |
|
|
file_extension = '.bin' |
|
|
|
|
|
|
|
|
save_path = os.path.join(os.path.expanduser('~'), 'Downloads', f"{task_id}_file{file_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: |
|
|
|
|
|
url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}" |
|
|
|
|
|
|
|
|
response = requests.get(url) |
|
|
|
|
|
if response.status_code == 200: |
|
|
|
|
|
encoded_bytes = base64.b64encode(response.content) |
|
|
encoded_str = encoded_bytes.decode('utf-8') |
|
|
return encoded_str |
|
|
else: |
|
|
raise Exception(f"Failed to download the file. Status code: {response.status_code}") |
|
|
|
|
|
|
|
|
|
|
|
tools = [web_search] |
|
|
|
|
|
|
|
|
|
|
|
gemini_llm = ChatGoogleGenerativeAI( |
|
|
model= "gemini-2.0-flash-exp", |
|
|
temperature=0.0, |
|
|
max_tokens=None, |
|
|
timeout=None, |
|
|
max_retries=2, |
|
|
google_api_key=GEMINI_API_KEY, |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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" |
|
|
) |
|
|
|
|
|
supervisor = create_supervisor( |
|
|
model=gemini_llm, |
|
|
agents=[web_research_agent], |
|
|
prompt=prompt_recomendado, |
|
|
add_handoff_back_messages=True, |
|
|
output_mode="full_history" |
|
|
).compile() |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
class BasicAgent: |
|
|
def __init__(self): |
|
|
print("BasicAgent initialized.") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def __call__(self, question: str, path: str) -> str: |
|
|
print(f"Agent received question : {question}...") |
|
|
|
|
|
messages = { |
|
|
"messages": [ |
|
|
{ |
|
|
"role": "user", |
|
|
"content": question |
|
|
} |
|
|
] |
|
|
} |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
print(f"Answer: {answer}\n") |
|
|
|
|
|
start_index = answer.find("FINAL ANSWER: ") |
|
|
substring="" |
|
|
if start_index != -1: |
|
|
substring = answer[start_index+14:] |
|
|
|
|
|
final_answer = substring |
|
|
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. |
|
|
""" |
|
|
|
|
|
space_id = os.getenv("SPACE_ID") |
|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
try: |
|
|
agent = BasicAgent() |
|
|
except Exception as e: |
|
|
print(f"Error instantiating agent: {e}") |
|
|
return f"Error initializing agent: {e}", None |
|
|
|
|
|
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" |
|
|
print(agent_code) |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
results_log = [] |
|
|
answers_payload = [] |
|
|
print(f"Running agent on {len(questions_data)} questions...") |
|
|
for item in questions_data: |
|
|
time.sleep(60) |
|
|
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) |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
space_host_startup = os.getenv("SPACE_HOST") |
|
|
space_id_startup = os.getenv("SPACE_ID") |
|
|
|
|
|
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(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) |