Spaces:
Runtime error
Runtime error
Upload 4 files
#1
by InacioPina - opened
- README.md +51 -9
- agent.py +79 -0
- app.py +148 -176
- requirements.txt +3 -2
README.md
CHANGED
|
@@ -1,15 +1,57 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 5.
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
hf_oauth: true
|
| 11 |
-
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
| 12 |
-
hf_oauth_expiration_minutes: 480
|
| 13 |
---
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: GAIA Agent Gemini
|
| 3 |
+
emoji: 🔎
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.23.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
|
|
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# GAIA Agent — Gemini API
|
| 13 |
+
|
| 14 |
+
Agente para o projeto final da Hugging Face Agents Course. Busca questões na API oficial do curso, usa Gemini com Google Search grounding e submete as respostas para avaliação.
|
| 15 |
+
|
| 16 |
+
## Arquitetura
|
| 17 |
+
|
| 18 |
+
- `app.py`: interface Gradio, busca das questões, execução, revisão e submissão.
|
| 19 |
+
- `agent.py`: integração com Gemini, grounding por Google Search e download opcional de anexos da questão.
|
| 20 |
+
- `requirements.txt`: dependências do Space.
|
| 21 |
+
|
| 22 |
+
## Configuração
|
| 23 |
+
|
| 24 |
+
1. Duplique o [template oficial](https://huggingface.co/spaces/agents-course/Final_Assignment_Template) ou crie um Space público com SDK Gradio.
|
| 25 |
+
2. Envie estes arquivos para o repositório do Space.
|
| 26 |
+
3. Em **Settings → Variables and secrets → Secrets**, crie:
|
| 27 |
+
- `GEMINI_API_KEY`: chave da Google AI Studio.
|
| 28 |
+
4. Opcionalmente crie a variável `GEMINI_MODEL` (padrão `gemini-2.5-flash`).
|
| 29 |
+
5. Aguarde o build terminar e abra o Space.
|
| 30 |
+
|
| 31 |
+
## Uso
|
| 32 |
+
|
| 33 |
+
1. Informe seu username Hugging Face.
|
| 34 |
+
2. Confirme a URL pública do Space terminada em `/tree/main`.
|
| 35 |
+
3. Execute primeiro com **Processar todas as 20 questões** desmarcado. Isso usa uma questão aleatória quando a API permite.
|
| 36 |
+
4. Confira respostas e logs.
|
| 37 |
+
5. Execute as 20 questões e revise as respostas.
|
| 38 |
+
6. Clique em **Submeter respostas**. A pontuação exibida deve vir da API oficial; não é estimada pelo app.
|
| 39 |
+
|
| 40 |
+
## API oficial usada
|
| 41 |
+
|
| 42 |
+
`https://agents-course-unit4-scoring.hf.space`
|
| 43 |
+
|
| 44 |
+
- `GET /questions`
|
| 45 |
+
- `GET /random-question`
|
| 46 |
+
- `GET /files/{task_id}`
|
| 47 |
+
- `POST /submit`
|
| 48 |
+
|
| 49 |
+
O formato de resposta enviado é `{"task_id": "...", "submitted_answer": "..."}`. A submissão inclui `username`, `agent_code` e `answers`, conforme a documentação do curso.
|
| 50 |
+
|
| 51 |
+
## Segurança e limitações
|
| 52 |
+
|
| 53 |
+
- Nunca coloque a chave Gemini diretamente no código ou em arquivos versionados.
|
| 54 |
+
- O agente utiliza Google Search grounding; isso não garante que todas as páginas ou fontes sejam acessíveis.
|
| 55 |
+
- Anexos acima de 18 MB não são enviados inline ao modelo.
|
| 56 |
+
- A implementação inicial pode precisar de ajustes conforme o formato atual dos dados retornados pela API. O app apresenta erros de API em vez de inventar pontuações.
|
| 57 |
+
- A pontuação mínima do curso é 30% (6 de 20), mas o resultado só é conhecido após a submissão oficial.
|
agent.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mimetypes
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import requests
|
| 5 |
+
from google import genai
|
| 6 |
+
from google.genai import types
|
| 7 |
+
|
| 8 |
+
SCORING_API = os.getenv("GAIA_API_URL", "https://agents-course-unit4-scoring.hf.space")
|
| 9 |
+
MODEL_NAME = os.getenv("GEMINI_MODEL", "gemini-2.5-flash")
|
| 10 |
+
|
| 11 |
+
SYSTEM_INSTRUCTION = """
|
| 12 |
+
You are a research agent solving GAIA benchmark questions.
|
| 13 |
+
Use Google Search grounding to verify factual claims and prefer primary sources.
|
| 14 |
+
Reason carefully through multi-step questions, dates, units, calculations, and requested output formatting.
|
| 15 |
+
The user may refer to an attached file associated with the task. Inspect it if available.
|
| 16 |
+
Return ONLY the answer requested by the question: no explanation, no citations, no markdown,
|
| 17 |
+
no prefix such as 'Final answer'. If a number is requested, output the number only unless
|
| 18 |
+
the question explicitly asks for units or symbols. If a list is requested, use the exact
|
| 19 |
+
separator and order requested. Do not invent facts. If you cannot determine the answer,
|
| 20 |
+
give the most defensible concise answer rather than a fabricated explanation.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def clean_answer(value):
|
| 25 |
+
text = str(value or "").strip()
|
| 26 |
+
text = re.sub(r"^\s*(final\s+answer|answer)\s*:\s*", "", text, flags=re.I)
|
| 27 |
+
text = text.strip().strip("`").strip()
|
| 28 |
+
text = re.sub(r"\s+", " ", text)
|
| 29 |
+
# Remove wrapping quotes only; preserve punctuation that may be part of the expected answer.
|
| 30 |
+
if len(text) >= 2 and text[0] == text[-1] and text[0] in ("'", '"'):
|
| 31 |
+
text = text[1:-1].strip()
|
| 32 |
+
return text
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class GaiaGeminiAgent:
|
| 36 |
+
def __init__(self):
|
| 37 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 38 |
+
if not api_key:
|
| 39 |
+
raise RuntimeError("GEMINI_API_KEY não está configurada.")
|
| 40 |
+
self.client = genai.Client(api_key=api_key)
|
| 41 |
+
|
| 42 |
+
def _attachment_parts(self, task_id):
|
| 43 |
+
"""Download task attachment using the course API; return Gemini-compatible parts."""
|
| 44 |
+
if not task_id:
|
| 45 |
+
return []
|
| 46 |
+
url = f"{SCORING_API}/files/{task_id}"
|
| 47 |
+
try:
|
| 48 |
+
response = requests.get(url, timeout=45)
|
| 49 |
+
if response.status_code != 200 or not response.content:
|
| 50 |
+
return []
|
| 51 |
+
content_type = response.headers.get("content-type", "").split(";")[0].strip()
|
| 52 |
+
if not content_type or content_type == "application/octet-stream":
|
| 53 |
+
guessed, _ = mimetypes.guess_type(response.url)
|
| 54 |
+
content_type = guessed or "application/octet-stream"
|
| 55 |
+
# Gemini inline data has size limits; skip unexpectedly large attachments rather than crashing.
|
| 56 |
+
if len(response.content) > 18 * 1024 * 1024:
|
| 57 |
+
return [types.Part.from_text(text="[Attachment was larger than 18 MB and could not be attached inline.]")]
|
| 58 |
+
return [types.Part.from_bytes(data=response.content, mime_type=content_type)]
|
| 59 |
+
except Exception:
|
| 60 |
+
return []
|
| 61 |
+
|
| 62 |
+
def solve(self, question, task_id=""):
|
| 63 |
+
contents = [
|
| 64 |
+
"Question:\n" + question,
|
| 65 |
+
]
|
| 66 |
+
contents.extend(self._attachment_parts(task_id))
|
| 67 |
+
response = self.client.models.generate_content(
|
| 68 |
+
model=MODEL_NAME,
|
| 69 |
+
contents=contents,
|
| 70 |
+
config=types.GenerateContentConfig(
|
| 71 |
+
system_instruction=SYSTEM_INSTRUCTION,
|
| 72 |
+
temperature=0.1,
|
| 73 |
+
tools=[types.Tool(google_search=types.GoogleSearch())],
|
| 74 |
+
),
|
| 75 |
+
)
|
| 76 |
+
answer = clean_answer(response.text)
|
| 77 |
+
if not answer:
|
| 78 |
+
raise RuntimeError("Gemini retornou uma resposta vazia.")
|
| 79 |
+
return answer
|
app.py
CHANGED
|
@@ -1,196 +1,168 @@
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
return fixed_answer
|
| 21 |
-
|
| 22 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
-
"""
|
| 24 |
-
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
-
and displays the results.
|
| 26 |
-
"""
|
| 27 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 29 |
-
|
| 30 |
-
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
-
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
api_url = DEFAULT_API_URL
|
| 38 |
-
questions_url = f"{api_url}/questions"
|
| 39 |
-
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
for item in
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
if not
|
| 80 |
-
|
| 81 |
continue
|
|
|
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
try:
|
| 102 |
-
response = requests.post(
|
| 103 |
response.raise_for_status()
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 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 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 138 |
-
print(status_message)
|
| 139 |
-
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
# --- Build Gradio Interface using Blocks ---
|
| 144 |
-
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
-
|
| 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 |
-
|
| 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.
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
run_button.click(
|
| 170 |
-
|
| 171 |
-
|
|
|
|
| 172 |
)
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 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 |
+
import json
|
| 2 |
import os
|
| 3 |
+
import time
|
| 4 |
+
from urllib.parse import quote
|
| 5 |
+
|
| 6 |
import gradio as gr
|
| 7 |
import requests
|
| 8 |
+
|
| 9 |
+
from agent import GaiaGeminiAgent, clean_answer
|
| 10 |
+
|
| 11 |
+
SCORING_API = os.getenv("GAIA_API_URL", "https://agents-course-unit4-scoring.hf.space")
|
| 12 |
+
SPACE_ID = os.getenv("SPACE_ID", "")
|
| 13 |
+
DEFAULT_SPACE_URL = f"https://huggingface.co/spaces/{SPACE_ID}/tree/main" if SPACE_ID else ""
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def fetch_questions():
|
| 17 |
+
response = requests.get(f"{SCORING_API}/questions", timeout=45)
|
| 18 |
+
response.raise_for_status()
|
| 19 |
+
payload = response.json()
|
| 20 |
+
if isinstance(payload, dict):
|
| 21 |
+
questions = payload.get("questions", payload.get("data", []))
|
| 22 |
+
elif isinstance(payload, list):
|
| 23 |
+
questions = payload
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
else:
|
| 25 |
+
questions = []
|
| 26 |
+
if not questions:
|
| 27 |
+
raise ValueError(f"A API não retornou questões em um formato reconhecido: {str(payload)[:500]}")
|
| 28 |
+
return questions
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
def question_text(item):
|
| 32 |
+
if isinstance(item, str):
|
| 33 |
+
return item
|
| 34 |
+
for key in ("question", "Question", "task", "prompt", "text"):
|
| 35 |
+
if item.get(key):
|
| 36 |
+
return str(item[key])
|
| 37 |
+
return ""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def task_id(item):
|
| 41 |
+
if isinstance(item, dict):
|
| 42 |
+
return str(item.get("task_id", item.get("id", "")))
|
| 43 |
+
return ""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def run_evaluation(username, space_url, run_all, progress=gr.Progress()):
|
| 47 |
+
username = (username or "").strip().lstrip("@")
|
| 48 |
+
space_url = (space_url or "").strip()
|
| 49 |
+
if not username:
|
| 50 |
+
raise gr.Error("Informe seu username da Hugging Face.")
|
| 51 |
+
if not space_url.startswith("https://huggingface.co/spaces/"):
|
| 52 |
+
raise gr.Error("Informe a URL pública do seu Space, no formato https://huggingface.co/spaces/USUARIO/NOME/tree/main")
|
| 53 |
+
|
| 54 |
+
if not os.getenv("GEMINI_API_KEY"):
|
| 55 |
+
raise gr.Error("Configure GEMINI_API_KEY em Settings → Secrets no seu Hugging Face Space.")
|
| 56 |
+
|
| 57 |
try:
|
| 58 |
+
questions = fetch_questions()
|
| 59 |
+
except Exception as exc:
|
| 60 |
+
raise gr.Error(f"Não foi possível obter as questões da API oficial: {exc}")
|
| 61 |
+
|
| 62 |
+
if not run_all:
|
| 63 |
+
# A API do curso oferece /random-question; usamos essa rota para um teste econômico.
|
| 64 |
+
try:
|
| 65 |
+
r = requests.get(f"{SCORING_API}/random-question", timeout=45)
|
| 66 |
+
r.raise_for_status()
|
| 67 |
+
random_item = r.json()
|
| 68 |
+
if isinstance(random_item, dict) and "question" not in random_item and "Question" not in random_item:
|
| 69 |
+
random_item = random_item.get("data", random_item)
|
| 70 |
+
questions = [random_item]
|
| 71 |
+
except Exception:
|
| 72 |
+
questions = [questions[0]]
|
| 73 |
+
|
| 74 |
+
agent = GaiaGeminiAgent()
|
| 75 |
+
answers = []
|
| 76 |
+
rows = []
|
| 77 |
+
logs = []
|
| 78 |
+
total = len(questions)
|
| 79 |
+
|
| 80 |
+
for index, item in enumerate(questions, start=1):
|
| 81 |
+
qid = task_id(item)
|
| 82 |
+
question = question_text(item)
|
| 83 |
+
if not qid or not question:
|
| 84 |
+
logs.append(f"Questão {index}: item sem task_id ou texto reconhecível; ignorado.")
|
| 85 |
continue
|
| 86 |
+
progress((index - 1) / total, desc=f"Resolvendo questão {index}/{total}")
|
| 87 |
try:
|
| 88 |
+
answer = clean_answer(agent.solve(question, qid))
|
| 89 |
+
if not answer:
|
| 90 |
+
answer = "Unable to determine"
|
| 91 |
+
answers.append({"task_id": qid, "submitted_answer": answer})
|
| 92 |
+
rows.append([index, qid, question, answer, "gerada"])
|
| 93 |
+
logs.append(f"[{index}/{total}] {qid}: {answer}")
|
| 94 |
+
except Exception as exc:
|
| 95 |
+
# Não fingimos ter uma resposta correta. O erro fica explícito e a resposta enviada é vazia.
|
| 96 |
+
answers.append({"task_id": qid, "submitted_answer": ""})
|
| 97 |
+
rows.append([index, qid, question, "", f"erro: {type(exc).__name__}"])
|
| 98 |
+
logs.append(f"[{index}/{total}] {qid}: FALHA — {exc}")
|
| 99 |
+
time.sleep(0.2)
|
| 100 |
+
|
| 101 |
+
result_json = json.dumps(answers, ensure_ascii=False, indent=2)
|
| 102 |
+
state = {
|
| 103 |
+
"username": username,
|
| 104 |
+
"agent_code": space_url,
|
| 105 |
+
"answers": answers,
|
| 106 |
+
}
|
| 107 |
+
summary = f"Execução concluída: {len(answers)} respostas geradas para {total} itens recebidos. Ainda NÃO submetido para pontuação."
|
| 108 |
+
return summary, rows, "\n".join(logs), result_json, state
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def submit_answers(state):
|
| 112 |
+
if not state or not state.get("answers"):
|
| 113 |
+
raise gr.Error("Execute o agente antes de submeter.")
|
| 114 |
+
payload = {
|
| 115 |
+
"username": state["username"],
|
| 116 |
+
"agent_code": state["agent_code"],
|
| 117 |
+
"answers": state["answers"],
|
| 118 |
+
}
|
| 119 |
try:
|
| 120 |
+
response = requests.post(f"{SCORING_API}/submit", json=payload, timeout=120)
|
| 121 |
response.raise_for_status()
|
| 122 |
+
data = response.json()
|
| 123 |
+
return "Resposta da API de avaliação (resultado real):\n" + json.dumps(data, ensure_ascii=False, indent=2)
|
| 124 |
+
except requests.HTTPError as exc:
|
| 125 |
+
body = exc.response.text[:2000] if exc.response is not None else str(exc)
|
| 126 |
+
raise gr.Error(f"A API recusou a submissão. HTTP {exc.response.status_code if exc.response else '?'}: {body}")
|
| 127 |
+
except Exception as exc:
|
| 128 |
+
raise gr.Error(f"Falha ao submeter: {exc}")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
with gr.Blocks(title="GAIA Agent — Gemini") as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
gr.Markdown(
|
| 133 |
"""
|
| 134 |
+
# 🤖 GAIA Agent — Gemini API
|
| 135 |
+
Agente experimental para o projeto final da Hugging Face Agents Course.
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
**Fluxo:** buscar questões da API oficial → executar o agente → revisar respostas → submeter para pontuação.
|
| 138 |
+
A execução não garante 30%: a pontuação só existe depois da resposta da API oficial.
|
|
|
|
|
|
|
| 139 |
"""
|
| 140 |
)
|
| 141 |
+
state = gr.State({})
|
| 142 |
+
with gr.Row():
|
| 143 |
+
username = gr.Textbox(label="Seu username Hugging Face", placeholder="ex.: meu-usuario")
|
| 144 |
+
space_url = gr.Textbox(label="URL pública do Space (código)", value=DEFAULT_SPACE_URL,
|
| 145 |
+
placeholder="https://huggingface.co/spaces/USUARIO/NOME/tree/main")
|
| 146 |
+
run_all = gr.Checkbox(value=False, label="Processar todas as 20 questões (desmarcado = teste com uma questão)")
|
| 147 |
+
run_button = gr.Button("🔎 Buscar questões e executar agente", variant="primary")
|
| 148 |
+
status = gr.Markdown()
|
| 149 |
+
results = gr.Dataframe(
|
| 150 |
+
headers=["#", "task_id", "Pergunta", "Resposta do agente", "Status"],
|
| 151 |
+
datatype=["number", "str", "str", "str", "str"],
|
| 152 |
+
label="Respostas geradas (revise antes de submeter)",
|
| 153 |
+
wrap=True,
|
| 154 |
+
)
|
| 155 |
+
logs = gr.Textbox(label="Log de execução", lines=10, interactive=False)
|
| 156 |
+
answers_json = gr.Code(label="Payload de respostas (JSON)", language="json")
|
| 157 |
+
submit_button = gr.Button("🚀 Submeter respostas à avaliação oficial", variant="primary")
|
| 158 |
+
submission_result = gr.Code(label="Retorno da API de avaliação", language="json")
|
| 159 |
|
| 160 |
run_button.click(
|
| 161 |
+
run_evaluation,
|
| 162 |
+
inputs=[username, space_url, run_all],
|
| 163 |
+
outputs=[status, results, logs, answers_json, state],
|
| 164 |
)
|
| 165 |
+
submit_button.click(submit_answers, inputs=[state], outputs=[submission_result])
|
| 166 |
|
| 167 |
+
demo.queue(default_concurrency_limit=1, max_size=10)
|
| 168 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,2 +1,3 @@
|
|
| 1 |
-
gradio
|
| 2 |
-
|
|
|
|
|
|
| 1 |
+
gradio>=5.20,<6
|
| 2 |
+
google-genai>=1.20.0
|
| 3 |
+
requests>=2.32.0
|