Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,271 +1,128 @@
|
|
| 1 |
-
|
| 2 |
-
import re
|
| 3 |
-
import time
|
| 4 |
-
import tempfile
|
| 5 |
-
import gradio as gr
|
| 6 |
-
import requests
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import spaces
|
| 9 |
-
from smolagents import (
|
| 10 |
-
CodeAgent,
|
| 11 |
-
DuckDuckGoSearchTool,
|
| 12 |
-
LiteLLMModel,
|
| 13 |
-
VisitWebpageTool,
|
| 14 |
-
tool,
|
| 15 |
-
)
|
| 16 |
|
| 17 |
-
# Required so ZeroGPU hardware keeps the Space running
|
| 18 |
-
@spaces.GPU
|
| 19 |
-
def dummy_gpu():
|
| 20 |
-
pass
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
|
| 25 |
-
@tool
|
| 26 |
-
def download_task_file(task_id: str) -> str:
|
| 27 |
-
"""
|
| 28 |
-
Downloads the attached file for a given GAIA task_id from the scoring server
|
| 29 |
-
and returns the local file path so Python code can read/parse it.
|
| 30 |
-
Args:
|
| 31 |
-
task_id: The task ID string associated with the question.
|
| 32 |
-
"""
|
| 33 |
-
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 34 |
-
response = requests.get(url, timeout=30)
|
| 35 |
-
response.raise_for_status()
|
| 36 |
-
content_disp = response.headers.get("content-disposition", "")
|
| 37 |
-
filename_match = re.search(r'filename="?([^"]+)"?', content_disp)
|
| 38 |
-
filename = filename_match.group(1) if filename_match else f"{task_id}.bin"
|
| 39 |
-
save_path = os.path.join(tempfile.gettempdir(), filename)
|
| 40 |
-
with open(save_path, "wb") as f:
|
| 41 |
-
f.write(response.content)
|
| 42 |
-
return save_path
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
api_key=os.getenv("GEMINI_API_KEY"),
|
| 50 |
-
)
|
| 51 |
-
self.agent = CodeAgent(
|
| 52 |
-
tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), download_task_file],
|
| 53 |
-
model=model,
|
| 54 |
-
max_steps=10,
|
| 55 |
-
additional_authorized_imports=[
|
| 56 |
-
"math",
|
| 57 |
-
"re",
|
| 58 |
-
"json",
|
| 59 |
-
"datetime",
|
| 60 |
-
"csv",
|
| 61 |
-
"os",
|
| 62 |
-
"pandas",
|
| 63 |
-
"openpyxl",
|
| 64 |
-
"pypdf",
|
| 65 |
-
],
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
def __call__(self, question: str, task_id: str = "") -> str:
|
| 69 |
-
task_hint = (
|
| 70 |
-
f"\nTask ID (call download_task_file('{task_id}') if a file is referenced): {task_id}"
|
| 71 |
-
if task_id
|
| 72 |
-
else ""
|
| 73 |
-
)
|
| 74 |
-
prompt = (
|
| 75 |
-
f"{question}{task_hint}\n\n"
|
| 76 |
-
"CRITICAL FORMATTING RULES:\n"
|
| 77 |
-
"- Reply with ONLY the exact final answer (a number, word, or short comma-separated list).\n"
|
| 78 |
-
"- Do NOT write full sentences, explanations, or 'FINAL ANSWER:'.\n"
|
| 79 |
-
"- Do NOT add trailing periods or units unless explicitly requested."
|
| 80 |
-
)
|
| 81 |
-
try:
|
| 82 |
-
raw = str(self.agent.run(prompt)).strip()
|
| 83 |
-
cleaned = re.sub(r"^(final answer\s*:?\s*)", "", raw, flags=re.IGNORECASE).strip()
|
| 84 |
-
time.sleep(2)
|
| 85 |
-
return cleaned.rstrip(".")
|
| 86 |
-
except Exception as e:
|
| 87 |
-
print(f"Agent error: {e}")
|
| 88 |
-
return f"Error: {e}"
|
| 89 |
|
| 90 |
|
| 91 |
-
def
|
| 92 |
-
""
|
| 93 |
-
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 94 |
-
and displays the results.
|
| 95 |
-
"""
|
| 96 |
-
space_id = os.getenv("SPACE_ID")
|
| 97 |
|
| 98 |
-
if profile:
|
| 99 |
-
username = f"{profile.username}"
|
| 100 |
-
print(f"User logged in: {username}")
|
| 101 |
-
else:
|
| 102 |
-
print("User not logged in.")
|
| 103 |
-
return "Please Login to Hugging Face with the button.", None
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
# 1. Instantiate Agent
|
| 110 |
try:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
try:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
return f"Error fetching questions: {e}", None
|
| 132 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 133 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 134 |
-
return f"Error decoding server response for questions: {e}", None
|
| 135 |
-
except Exception as e:
|
| 136 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 137 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 138 |
-
|
| 139 |
-
# 3. Run your Agent
|
| 140 |
-
results_log = []
|
| 141 |
-
answers_payload = []
|
| 142 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 143 |
-
for item in questions_data:
|
| 144 |
-
task_id = item.get("task_id")
|
| 145 |
-
question_text = item.get("question")
|
| 146 |
-
if not task_id or question_text is None:
|
| 147 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 148 |
continue
|
|
|
|
| 149 |
try:
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
)
|
| 168 |
-
|
| 169 |
-
if not answers_payload:
|
| 170 |
-
print("Agent did not produce any answers to submit.")
|
| 171 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 172 |
-
|
| 173 |
-
# 4. Prepare Submission
|
| 174 |
-
submission_data = {
|
| 175 |
-
"username": username.strip(),
|
| 176 |
-
"agent_code": agent_code,
|
| 177 |
-
"answers": answers_payload,
|
| 178 |
-
}
|
| 179 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 180 |
-
print(status_update)
|
| 181 |
-
|
| 182 |
-
# 5. Submit
|
| 183 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 184 |
try:
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
except
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 216 |
-
print(status_message)
|
| 217 |
-
results_df = pd.DataFrame(results_log)
|
| 218 |
-
return status_message, results_df
|
| 219 |
-
except Exception as e:
|
| 220 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 221 |
-
print(status_message)
|
| 222 |
-
results_df = pd.DataFrame(results_log)
|
| 223 |
-
return status_message, results_df
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
# --- Build Gradio Interface using Blocks ---
|
| 227 |
-
with gr.Blocks() as demo:
|
| 228 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 229 |
gr.Markdown(
|
| 230 |
-
""
|
| 231 |
-
**
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 235 |
-
"""
|
| 236 |
)
|
| 237 |
-
|
| 238 |
gr.LoginButton()
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
)
|
| 249 |
|
| 250 |
if __name__ == "__main__":
|
| 251 |
-
|
| 252 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 253 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 254 |
-
|
| 255 |
-
if space_host_startup:
|
| 256 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 257 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 258 |
-
else:
|
| 259 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally).")
|
| 260 |
-
|
| 261 |
-
if space_id_startup:
|
| 262 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 263 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 264 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 265 |
-
else:
|
| 266 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally). Repo URL cannot be determined.")
|
| 267 |
-
|
| 268 |
-
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 269 |
-
|
| 270 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 271 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
+
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
def write_saved(username, answers):
|
| 5 |
+
saved_path(username).write_text(json.dumps(answers, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
def make_table(questions, answers):
|
| 9 |
+
return [
|
| 10 |
+
[item["task_id"][:8], str(item["question"]).replace("\n", " ")[:170], answers.get(item["task_id"], "(not run)")]
|
| 11 |
+
for item in questions
|
| 12 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
+
def get_profile_name(profile):
|
| 16 |
+
return getattr(profile, "username", None) if profile else None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
def test_one(profile: gr.OAuthProfile | None):
|
| 20 |
+
username = get_profile_name(profile)
|
| 21 |
+
if not username:
|
| 22 |
+
return "Sign in with Hugging Face first.", []
|
|
|
|
| 23 |
try:
|
| 24 |
+
questions = get_questions()
|
| 25 |
+
answers = read_saved(username)
|
| 26 |
+
# Test the first not-yet-answered task; avoid running the same one twice.
|
| 27 |
+
item = next((x for x in questions if x["task_id"] not in answers), questions[0])
|
| 28 |
+
result = GAIAAgent()(item["question"], item["task_id"], item.get("file_name") or "")
|
| 29 |
+
answers[item["task_id"]] = result
|
| 30 |
+
write_saved(username, answers)
|
| 31 |
+
return f"Test complete! Agent answer: {result}\nCached: {len(answers)}/{len(questions)}. No leaderboard submission yet.", make_table(questions, answers)
|
| 32 |
+
except Exception as exc:
|
| 33 |
+
return "Test failed: " + str(exc)[:500], []
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def run_all(profile: gr.OAuthProfile | None):
|
| 37 |
+
username = get_profile_name(profile)
|
| 38 |
+
if not username:
|
| 39 |
+
yield "Sign in with Hugging Face first.", []
|
| 40 |
+
return
|
| 41 |
try:
|
| 42 |
+
questions = get_questions()
|
| 43 |
+
answers = read_saved(username)
|
| 44 |
+
agent = GAIAAgent()
|
| 45 |
+
except Exception as exc:
|
| 46 |
+
yield "Setup failed: " + str(exc)[:500], []
|
| 47 |
+
return
|
| 48 |
+
for n, item in enumerate(questions, 1):
|
| 49 |
+
task_id = item["task_id"]
|
| 50 |
+
if task_id in answers:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
continue
|
| 52 |
+
yield f"Researching question {n}/{len(questions)}. Completed {len(answers)}. Not submitted yet.", make_table(questions, answers)
|
| 53 |
try:
|
| 54 |
+
answer = agent(item["question"], task_id, item.get("file_name") or "")
|
| 55 |
+
answers[task_id] = answer
|
| 56 |
+
write_saved(username, answers)
|
| 57 |
+
except Exception as exc:
|
| 58 |
+
message = str(exc)
|
| 59 |
+
print(f"Question {n} failed: {message[:400]}")
|
| 60 |
+
yield f"Stopped at question {n}: {message[:250]}\nSaved {len(answers)}/{len(questions)} so far. Retry later to resume.", make_table(questions, answers)
|
| 61 |
+
return
|
| 62 |
+
# Small gap to reduce bursts against provider free-tier request limits.
|
| 63 |
+
time.sleep(2)
|
| 64 |
+
yield f"Finished! {len(answers)}/{len(questions)} real agent answers are saved. Review the table, then click Submit.", make_table(questions, answers)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def submit_saved(profile: gr.OAuthProfile | None):
|
| 68 |
+
username = get_profile_name(profile)
|
| 69 |
+
if not username:
|
| 70 |
+
return "Sign in with Hugging Face first.", []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
try:
|
| 72 |
+
questions = get_questions()
|
| 73 |
+
answers = read_saved(username)
|
| 74 |
+
if not answers:
|
| 75 |
+
return "No generated answers yet. Use Test or Run All first.", []
|
| 76 |
+
space_id = os.getenv("SPACE_ID", "").strip()
|
| 77 |
+
if not space_id or "/" not in space_id:
|
| 78 |
+
return "Submission needs a deployed Hugging Face Space (SPACE_ID missing).", make_table(questions, answers)
|
| 79 |
+
payload = {
|
| 80 |
+
"username": username,
|
| 81 |
+
"agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
|
| 82 |
+
"answers": [
|
| 83 |
+
{"task_id": item["task_id"], "submitted_answer": answers[item["task_id"]]}
|
| 84 |
+
for item in questions if item["task_id"] in answers
|
| 85 |
+
],
|
| 86 |
+
}
|
| 87 |
+
r = requests.post(f"{API}/submit", json=payload, timeout=120)
|
| 88 |
+
r.raise_for_status()
|
| 89 |
+
score = r.json()
|
| 90 |
+
return (
|
| 91 |
+
f"Official submission recorded for {username}.\n"
|
| 92 |
+
f"Score: {score.get('score', 'N/A')}% | "
|
| 93 |
+
f"Correct: {score.get('correct_count', '?')} / 20\n"
|
| 94 |
+
f"{score.get('message', '')}"
|
| 95 |
+
), make_table(questions, answers)
|
| 96 |
+
except Exception as exc:
|
| 97 |
+
return "Submission failed: " + str(exc)[:500], []
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
with gr.Blocks(title="GAIA Research Agent | HF Agents Course") as demo:
|
| 101 |
+
gr.Markdown("# 🕵️ GAIA Research Agent — Unit 4")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
gr.Markdown(
|
| 103 |
+
"A real research-and-reasoning agent for the official Hugging Face Agents Course. "
|
| 104 |
+
"**Sign in**, test one question, run all questions, then submit your saved answers. "
|
| 105 |
+
"Results are saved temporarily on this Space, but may disappear if the Space restarts. "
|
| 106 |
+
"The agent does not access the benchmark's hidden answers."
|
|
|
|
|
|
|
| 107 |
)
|
|
|
|
| 108 |
gr.LoginButton()
|
| 109 |
+
gr.Markdown(f"**Model:** `{MODEL}` · **Search:** DDGS · **Math:** Gemini code execution · **Files:** Images/audio/Excel/Python/PDF")
|
| 110 |
+
with gr.Row():
|
| 111 |
+
test_button = gr.Button("1. Test one question")
|
| 112 |
+
run_button = gr.Button("2. Run / resume all questions", variant="primary")
|
| 113 |
+
submit_button = gr.Button("3. Submit saved answers")
|
| 114 |
+
status = gr.Textbox(label="Status and official score", lines=5, interactive=False)
|
| 115 |
+
results = gr.Dataframe(headers=["Task ID", "Question", "Agent answer"], interactive=False, wrap=True)
|
| 116 |
+
test_button.click(test_one, outputs=[status, results])
|
| 117 |
+
run_button.click(run_all, outputs=[status, results])
|
| 118 |
+
submit_button.click(submit_saved, outputs=[status, results])
|
| 119 |
+
gr.Markdown(
|
| 120 |
+
"**Troubleshooting:** A 429 error means your Gemini rate limit was reached; "
|
| 121 |
+
"you can resume later without losing already saved answers (unless the Space restarts). "
|
| 122 |
+
"If attachments report 404, the official scoring API may be missing files. "
|
| 123 |
+
"Optionally accept the `gaia-benchmark/GAIA` dataset terms and add an `HF_TOKEN` "
|
| 124 |
+
"read token as a Secret to enable the attachment fallback."
|
| 125 |
)
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
+
demo.queue().launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|