Update app.py
#499
by marantmir - opened
app.py
CHANGED
|
@@ -1,103 +1,208 @@
|
|
|
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
|
|
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 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 |
try:
|
| 43 |
agent = BasicAgent()
|
| 44 |
except Exception as e:
|
| 45 |
-
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
| 47 |
-
# 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)
|
| 48 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
-
print(agent_code)
|
| 50 |
|
| 51 |
-
# 2. Fetch Questions
|
| 52 |
-
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
response = requests.get(questions_url, timeout=15)
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
| 57 |
if not questions_data:
|
| 58 |
-
|
| 59 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 60 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
-
except requests.exceptions.RequestException as e:
|
| 62 |
-
print(f"Error fetching questions: {e}")
|
| 63 |
-
return f"Error fetching questions: {e}", None
|
| 64 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 66 |
-
print(f"Response text: {response.text[:500]}")
|
| 67 |
-
return f"Error decoding server response for questions: {e}", None
|
| 68 |
except Exception as e:
|
| 69 |
-
|
| 70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
|
| 72 |
-
# 3. Run your Agent
|
| 73 |
results_log = []
|
| 74 |
answers_payload = []
|
| 75 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 76 |
for item in questions_data:
|
| 77 |
task_id = item.get("task_id")
|
| 78 |
question_text = item.get("question")
|
| 79 |
if not task_id or question_text is None:
|
| 80 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
submitted_answer = agent(question_text)
|
| 84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
except Exception as e:
|
| 87 |
-
|
| 88 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
-
|
| 92 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
-
|
| 95 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
-
print(status_update)
|
| 98 |
|
| 99 |
-
# 5. Submit
|
| 100 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
try:
|
| 102 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 103 |
response.raise_for_status()
|
|
@@ -105,92 +210,20 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 105 |
final_status = (
|
| 106 |
f"Submission Successful!\n"
|
| 107 |
f"User: {result_data.get('username')}\n"
|
| 108 |
-
f"Overall Score: {result_data.get('score', 'N/A')}%
|
| 109 |
-
f"
|
| 110 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 111 |
)
|
| 112 |
-
|
| 113 |
-
results_df = pd.DataFrame(results_log)
|
| 114 |
-
return final_status, results_df
|
| 115 |
-
except requests.exceptions.HTTPError as e:
|
| 116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 117 |
-
try:
|
| 118 |
-
error_json = e.response.json()
|
| 119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 120 |
-
except requests.exceptions.JSONDecodeError:
|
| 121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 122 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 123 |
-
print(status_message)
|
| 124 |
-
results_df = pd.DataFrame(results_log)
|
| 125 |
-
return status_message, results_df
|
| 126 |
-
except requests.exceptions.Timeout:
|
| 127 |
-
status_message = "Submission Failed: The request timed out."
|
| 128 |
-
print(status_message)
|
| 129 |
-
results_df = pd.DataFrame(results_log)
|
| 130 |
-
return status_message, results_df
|
| 131 |
-
except requests.exceptions.RequestException as e:
|
| 132 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 133 |
-
print(status_message)
|
| 134 |
-
results_df = pd.DataFrame(results_log)
|
| 135 |
-
return status_message, results_df
|
| 136 |
except Exception as e:
|
| 137 |
-
|
| 138 |
-
print(status_message)
|
| 139 |
-
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
-
|
| 142 |
|
| 143 |
-
#
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
-
gr.Markdown(
|
| 147 |
-
"""
|
| 148 |
-
**Instructions:**
|
| 149 |
-
|
| 150 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
-
|
| 154 |
-
---
|
| 155 |
-
**Disclaimers:**
|
| 156 |
-
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).
|
| 157 |
-
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.
|
| 158 |
-
"""
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
gr.LoginButton()
|
| 162 |
-
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
-
|
| 165 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
-
|
| 169 |
-
run_button.click(
|
| 170 |
-
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 172 |
-
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 179 |
-
|
| 180 |
-
if space_host_startup:
|
| 181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
-
else:
|
| 184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
-
|
| 186 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 187 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
-
else:
|
| 191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
-
|
| 193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
-
|
| 195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
import os
|
| 3 |
+
import time
|
| 4 |
import requests
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
from smolagents import CodeAgent, LiteLLMModel, tool
|
| 9 |
|
| 10 |
+
# URL da API responsável por fornecer as perguntas e receber o envio do benchmark.
|
|
|
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
+
# 1. Carrega variáveis de ambiente (útil para testes locais, ignorado no HF Spaces)
|
| 16 |
+
load_dotenv()
|
| 17 |
+
|
| 18 |
+
# 2. Configuração do Langfuse (Opcional - não vai quebrar se falhar)
|
| 19 |
+
try:
|
| 20 |
+
from langfuse import get_client
|
| 21 |
+
from openinference.instrumentation.smolagents import SmolagentsInstrumentor
|
| 22 |
+
|
| 23 |
+
langfuse_client = get_client()
|
| 24 |
+
if langfuse_client.auth_check():
|
| 25 |
+
print("📡 Langfuse autenticado com sucesso!")
|
| 26 |
+
SmolagentsInstrumentor().instrument()
|
| 27 |
+
else:
|
| 28 |
+
print("⚠️ Langfuse ignorado (chaves ausentes).")
|
| 29 |
+
except Exception:
|
| 30 |
+
print("⚠️ Monitoramento do Langfuse desativado.")
|
| 31 |
+
|
| 32 |
+
# Valida a presença da chave do Gemini (Obrigatório para o cérebro)
|
| 33 |
+
gemini_key = os.getenv("GEMINI_API_KEY")
|
| 34 |
+
if not gemini_key:
|
| 35 |
+
print("❌ ERRO: A variável 'GEMINI_API_KEY' não foi encontrada nos Secrets.")
|
| 36 |
+
|
| 37 |
+
# 3. Inicialização do modelo LLM usando LiteLLM (Corrigido para Gemini 2.0 Flash)
|
| 38 |
+
self.model = LiteLLMModel(
|
| 39 |
+
model_id="gemini/gemini-2.0-flash",
|
| 40 |
+
api_key=gemini_key,
|
| 41 |
+
num_retries=3 # Resiliência contra o erro 429
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# 4. Ferramenta de busca Web
|
| 45 |
+
@tool
|
| 46 |
+
def busca_web(query: str) -> str:
|
| 47 |
+
"""Useful to search the web for up-to-date facts, Wikipedia articles, or general information.
|
| 48 |
+
Args:
|
| 49 |
+
query: The exact search query to look up on the internet.
|
| 50 |
+
"""
|
| 51 |
+
try:
|
| 52 |
+
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36'}
|
| 53 |
+
url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(query)}"
|
| 54 |
+
res = requests.get(url, headers=headers, timeout=15)
|
| 55 |
+
res.raise_for_status()
|
| 56 |
+
|
| 57 |
+
from bs4 import BeautifulSoup
|
| 58 |
+
soup = BeautifulSoup(res.text, 'html.parser')
|
| 59 |
+
snippets = [span.get_text() for span in soup.find_all('span', class_='result__snippet')]
|
| 60 |
+
|
| 61 |
+
if not snippets:
|
| 62 |
+
return "No clear results found on the web for this query."
|
| 63 |
+
return "\n\n".join(snippets[:4])
|
| 64 |
+
except Exception as e:
|
| 65 |
+
return f"Search failed due to network error: {e}"
|
| 66 |
+
|
| 67 |
+
# 5. Ferramenta de transcrição de áudio via OpenAI Whisper
|
| 68 |
+
@tool
|
| 69 |
+
def transcribe_audio(file_path: str) -> str:
|
| 70 |
+
"""Useful to transcribe any audio file (like MP3, WAV, M4A) into text.
|
| 71 |
+
Always use this tool first when a question involves understanding audio.
|
| 72 |
+
Args:
|
| 73 |
+
file_path: The local path to the audio file (e.g., 'audio.mp3').
|
| 74 |
+
"""
|
| 75 |
+
openai_key = os.getenv("OPENAI_API_KEY")
|
| 76 |
+
if not openai_key:
|
| 77 |
+
return "Error: OPENAI_API_KEY not found in secrets. Cannot transcribe audio."
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
import openai
|
| 81 |
+
client = openai.OpenAI(api_key=openai_key)
|
| 82 |
+
with open(file_path, "rb") as audio_file:
|
| 83 |
+
transcript = client.audio.transcriptions.create(
|
| 84 |
+
model="whisper-1",
|
| 85 |
+
file=audio_file
|
| 86 |
+
)
|
| 87 |
+
return f"Audio Transcription Content:\n{transcript.text}"
|
| 88 |
+
except Exception as e:
|
| 89 |
+
return f"Error transcribing audio: {e}."
|
| 90 |
+
|
| 91 |
+
# 6. Instanciação do CodeAgent
|
| 92 |
+
self.agent = CodeAgent(
|
| 93 |
+
tools=[busca_web, transcribe_audio],
|
| 94 |
+
model=self.model,
|
| 95 |
+
add_base_tools=False,
|
| 96 |
+
max_steps=10, # Adicionado limite de passos para evitar loops infinitos
|
| 97 |
+
additional_authorized_imports=[
|
| 98 |
+
"requests", "pydub", "wave", "openai",
|
| 99 |
+
"PIL", "pdfplumber", "pypdf",
|
| 100 |
+
"json", "csv", "openpyxl", "pandas",
|
| 101 |
+
"os", "pathlib", "zipfile",
|
| 102 |
+
"math", "datetime", "re", "itertools", "bs4"
|
| 103 |
+
]
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
def __call__(self, question: str) -> str:
|
| 107 |
+
"""Permite chamar o agente diretamente passando a pergunta."""
|
| 108 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 109 |
+
|
| 110 |
+
# Prompt ajustado com regras rígidas para o GAIA
|
| 111 |
+
prompt_ajustado = (
|
| 112 |
+
f"TASK TO SOLVE: {question}\n\n"
|
| 113 |
+
"EXECUTION RULES:\n"
|
| 114 |
+
"1. You MUST solve this task step-by-step using Python code.\n"
|
| 115 |
+
"2. Every single response you generate MUST strictly follow this exact grammar:\n"
|
| 116 |
+
"Thoughts: <your reasoning here>\n"
|
| 117 |
+
"<code>\n"
|
| 118 |
+
"# your python code here using available tools\n"
|
| 119 |
+
"</code>\n"
|
| 120 |
+
"3. NEVER write conversational text or explanations outside of the 'Thoughts' or '<code>' sections.\n"
|
| 121 |
+
"4. To finish the task and deliver the answer, you MUST call the `final_answer` tool inside a code block.\n"
|
| 122 |
+
"5. CRITICAL FOR GAIA BENCHMARK (EXACT MATCH STRICT RULE):\n"
|
| 123 |
+
"Inside the `final_answer()` tool, pass ONLY the raw string or number value matching the exact required format. Do NOT add labels or conversational prefixes.\n\n"
|
| 124 |
+
"FEW-SHOT EXAMPLES OF EXPECTED FINAL ANSWERS:\n"
|
| 125 |
+
"- Question: What was the actual enrollment count of the clinical trial on H. pylori in acne vulgaris patients from Jan-May 2018 as listed on the NIH website?\n"
|
| 126 |
+
" Correct Call: final_answer(90) or final_answer('90')\n\n"
|
| 127 |
+
"- Question: If this whole pint is made up of ice cream, how many percent above or below the US federal standards for butterfat content is it when using the standards as reported by Wikipedia in 2020? Answer as + or - a number rounded to one decimal place.\n"
|
| 128 |
+
" Correct Call: final_answer('+4.6')\n\n"
|
| 129 |
+
"- Question: In NASA's Astronomy Picture of the Day on 2006 January 21, two astronauts are visible... Give the last name of the astronaut, separated from the number of minutes by a semicolon.\n"
|
| 130 |
+
" Correct Call: final_answer('White; 5876')\n\n"
|
| 131 |
+
"6. WEB REQUESTS: Always provide a User-Agent header when using `requests.get()` to avoid 403 Forbidden errors."
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
max_tentativas = 2 # Reduzido de 3 para 2 para evitar estourar cota de tempo atoa
|
| 135 |
+
segundos_de_espera = 15
|
| 136 |
+
|
| 137 |
+
for tentativa in range(max_tentativas):
|
| 138 |
+
try:
|
| 139 |
+
resposta_final = self.agent.run(prompt_ajustado)
|
| 140 |
+
texto_resposta = str(resposta_final).strip()
|
| 141 |
+
|
| 142 |
+
# Sanitização
|
| 143 |
+
prefixos_para_remover = [
|
| 144 |
+
"final answer:", "final answer",
|
| 145 |
+
"the final answer is:", "the final answer is",
|
| 146 |
+
"answer:", "the answer is:"
|
| 147 |
+
]
|
| 148 |
+
texto_lower = texto_resposta.lower()
|
| 149 |
+
for prefixo in prefixos_para_remover:
|
| 150 |
+
if texto_lower.startswith(prefixo):
|
| 151 |
+
texto_resposta = texto_resposta[len(prefixo):].strip()
|
| 152 |
+
texto_lower = texto_resposta.lower()
|
| 153 |
+
|
| 154 |
+
texto_resposta = texto_resposta.strip(" \t\n\r:.\"'")
|
| 155 |
+
return texto_resposta
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"⚠️ Falha na tentativa {tentativa + 1}/{max_tentativas}: {e}")
|
| 159 |
+
if tentativa < max_tentativas - 1:
|
| 160 |
+
time.sleep(segundos_de_espera)
|
| 161 |
+
else:
|
| 162 |
+
return f"Erro definitivo da API: {e}"
|
| 163 |
+
|
| 164 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 165 |
+
# Resgata automaticamente os dados do Space atual
|
| 166 |
+
username = os.getenv("SPACE_AUTHOR_NAME", "marantmir")
|
| 167 |
+
space_id = os.getenv("SPACE_ID", f"{username}/Final_Assignment_Template")
|
| 168 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 169 |
+
|
| 170 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 171 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 172 |
+
|
| 173 |
try:
|
| 174 |
agent = BasicAgent()
|
| 175 |
except Exception as e:
|
|
|
|
| 176 |
return f"Error initializing agent: {e}", None
|
|
|
|
|
|
|
|
|
|
| 177 |
|
|
|
|
|
|
|
| 178 |
try:
|
| 179 |
response = requests.get(questions_url, timeout=15)
|
| 180 |
response.raise_for_status()
|
| 181 |
questions_data = response.json()
|
| 182 |
if not questions_data:
|
| 183 |
+
return "Fetched questions list is empty.", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
except Exception as e:
|
| 185 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 186 |
|
|
|
|
| 187 |
results_log = []
|
| 188 |
answers_payload = []
|
|
|
|
| 189 |
for item in questions_data:
|
| 190 |
task_id = item.get("task_id")
|
| 191 |
question_text = item.get("question")
|
| 192 |
if not task_id or question_text is None:
|
|
|
|
| 193 |
continue
|
| 194 |
try:
|
| 195 |
submitted_answer = agent(question_text)
|
| 196 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 197 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 198 |
except Exception as e:
|
| 199 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
|
|
|
| 200 |
|
| 201 |
if not answers_payload:
|
| 202 |
+
return "Agent did not produce any answers.", pd.DataFrame(results_log)
|
|
|
|
| 203 |
|
| 204 |
+
submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
|
|
|
|
|
|
| 205 |
|
|
|
|
|
|
|
| 206 |
try:
|
| 207 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 208 |
response.raise_for_status()
|
|
|
|
| 210 |
final_status = (
|
| 211 |
f"Submission Successful!\n"
|
| 212 |
f"User: {result_data.get('username')}\n"
|
| 213 |
+
f"Overall Score: {result_data.get('score', 'N/A')}%\n"
|
| 214 |
+
f"Message: {result_data.get('message', '')}"
|
|
|
|
| 215 |
)
|
| 216 |
+
return final_status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
except Exception as e:
|
| 218 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
+
# Interface Gradio
|
| 221 |
with gr.Blocks() as demo:
|
| 222 |
+
gr.Markdown("# GAIA Benchmark - SmolAgents Runner")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 224 |
+
status_output = gr.Textbox(label="Run Status", interactive=False)
|
|
|
|
|
|
|
| 225 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 226 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
demo.launch(debug=True, share=False)
|