File size: 6,924 Bytes
ca3462f
10e9b7d
ca3462f
 
 
10e9b7d
eccf8e4
ca3462f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e4a06b
ca3462f
 
 
 
3c4371f
e80aab9
ca3462f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eccf8e4
ca3462f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31243f4
ca3462f
31243f4
ca3462f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
ca3462f
e80aab9
ca3462f
 
 
 
 
 
 
 
 
 
0ee0419
e514fd7
ca3462f
 
e514fd7
ca3462f
 
e514fd7
e80aab9
ca3462f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
31243f4
ca3462f
 
 
e80aab9
ca3462f
e80aab9
ca3462f
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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()