InacioPina's picture
Upload 4 files
6904ffa verified
Raw History Blame
6.92 kB
import json
import os
import time
from urllib.parse import quote
import gradio as gr
import requests
from agent import GaiaGeminiAgent, clean_answer
SCORING_API = os.getenv("GAIA_API_URL", "https://agents-course-unit4-scoring.hf.space")
SPACE_ID = os.getenv("SPACE_ID", "")
DEFAULT_SPACE_URL = f"https://huggingface.co/spaces/{SPACE_ID}/tree/main" if SPACE_ID else ""
def fetch_questions():
response = requests.get(f"{SCORING_API}/questions", timeout=45)
response.raise_for_status()
payload = response.json()
if isinstance(payload, dict):
questions = payload.get("questions", payload.get("data", []))
elif isinstance(payload, list):
questions = payload
else:
questions = []
if not questions:
raise ValueError(f"A API não retornou questões em um formato reconhecido: {str(payload)[:500]}")
return questions
def question_text(item):
if isinstance(item, str):
return item
for key in ("question", "Question", "task", "prompt", "text"):
if item.get(key):
return str(item[key])
return ""
def task_id(item):
if isinstance(item, dict):
return str(item.get("task_id", item.get("id", "")))
return ""
def run_evaluation(username, space_url, run_all, progress=gr.Progress()):
username = (username or "").strip().lstrip("@")
space_url = (space_url or "").strip()
if not username:
raise gr.Error("Informe seu username da Hugging Face.")
if not space_url.startswith("https://huggingface.co/spaces/"):
raise gr.Error("Informe a URL pública do seu Space, no formato https://huggingface.co/spaces/USUARIO/NOME/tree/main")
if not os.getenv("GEMINI_API_KEY"):
raise gr.Error("Configure GEMINI_API_KEY em Settings → Secrets no seu Hugging Face Space.")
try:
questions = fetch_questions()
except Exception as exc:
raise gr.Error(f"Não foi possível obter as questões da API oficial: {exc}")
if not run_all:
# A API do curso oferece /random-question; usamos essa rota para um teste econômico.
try:
r = requests.get(f"{SCORING_API}/random-question", timeout=45)
r.raise_for_status()
random_item = r.json()
if isinstance(random_item, dict) and "question" not in random_item and "Question" not in random_item:
random_item = random_item.get("data", random_item)
questions = [random_item]
except Exception:
questions = [questions[0]]
agent = GaiaGeminiAgent()
answers = []
rows = []
logs = []
total = len(questions)
for index, item in enumerate(questions, start=1):
qid = task_id(item)
question = question_text(item)
if not qid or not question:
logs.append(f"Questão {index}: item sem task_id ou texto reconhecível; ignorado.")
continue
progress((index - 1) / total, desc=f"Resolvendo questão {index}/{total}")
try:
answer = clean_answer(agent.solve(question, qid))
if not answer:
answer = "Unable to determine"
answers.append({"task_id": qid, "submitted_answer": answer})
rows.append([index, qid, question, answer, "gerada"])
logs.append(f"[{index}/{total}] {qid}: {answer}")
except Exception as exc:
# Não fingimos ter uma resposta correta. O erro fica explícito e a resposta enviada é vazia.
answers.append({"task_id": qid, "submitted_answer": ""})
rows.append([index, qid, question, "", f"erro: {type(exc).__name__}"])
logs.append(f"[{index}/{total}] {qid}: FALHA — {exc}")
time.sleep(0.2)
result_json = json.dumps(answers, ensure_ascii=False, indent=2)
state = {
"username": username,
"agent_code": space_url,
"answers": answers,
}
summary = f"Execução concluída: {len(answers)} respostas geradas para {total} itens recebidos. Ainda NÃO submetido para pontuação."
return summary, rows, "\n".join(logs), result_json, state
def submit_answers(state):
if not state or not state.get("answers"):
raise gr.Error("Execute o agente antes de submeter.")
payload = {
"username": state["username"],
"agent_code": state["agent_code"],
"answers": state["answers"],
}
try:
response = requests.post(f"{SCORING_API}/submit", json=payload, timeout=120)
response.raise_for_status()
data = response.json()
return "Resposta da API de avaliação (resultado real):\n" + json.dumps(data, ensure_ascii=False, indent=2)
except requests.HTTPError as exc:
body = exc.response.text[:2000] if exc.response is not None else str(exc)
raise gr.Error(f"A API recusou a submissão. HTTP {exc.response.status_code if exc.response else '?'}: {body}")
except Exception as exc:
raise gr.Error(f"Falha ao submeter: {exc}")
with gr.Blocks(title="GAIA Agent — Gemini") as demo:
gr.Markdown(
"""
# 🤖 GAIA Agent — Gemini API
Agente experimental para o projeto final da Hugging Face Agents Course.
**Fluxo:** buscar questões da API oficial → executar o agente → revisar respostas → submeter para pontuação.
A execução não garante 30%: a pontuação só existe depois da resposta da API oficial.
"""
)
state = gr.State({})
with gr.Row():
username = gr.Textbox(label="Seu username Hugging Face", placeholder="ex.: meu-usuario")
space_url = gr.Textbox(label="URL pública do Space (código)", value=DEFAULT_SPACE_URL,
placeholder="https://huggingface.co/spaces/USUARIO/NOME/tree/main")
run_all = gr.Checkbox(value=False, label="Processar todas as 20 questões (desmarcado = teste com uma questão)")
run_button = gr.Button("🔎 Buscar questões e executar agente", variant="primary")
status = gr.Markdown()
results = gr.Dataframe(
headers=["#", "task_id", "Pergunta", "Resposta do agente", "Status"],
datatype=["number", "str", "str", "str", "str"],
label="Respostas geradas (revise antes de submeter)",
wrap=True,
)
logs = gr.Textbox(label="Log de execução", lines=10, interactive=False)
answers_json = gr.Code(label="Payload de respostas (JSON)", language="json")
submit_button = gr.Button("🚀 Submeter respostas à avaliação oficial", variant="primary")
submission_result = gr.Code(label="Retorno da API de avaliação", language="json")
run_button.click(
run_evaluation,
inputs=[username, space_url, run_all],
outputs=[status, results, logs, answers_json, state],
)
submit_button.click(submit_answers, inputs=[state], outputs=[submission_result])
demo.queue(default_concurrency_limit=1, max_size=10)
demo.launch()