Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,81 +1,272 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
|
|
|
| 5 |
|
| 6 |
-
from smolagents import CodeAgent, HfApiModel
|
| 7 |
from smolagents.tools import DuckDuckGoSearchTool
|
| 8 |
|
| 9 |
-
#
|
|
|
|
|
|
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
|
| 13 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
class BasicAgent:
|
| 15 |
|
| 16 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
self.agent = CodeAgent(
|
| 19 |
tools=[
|
| 20 |
-
DuckDuckGoSearchTool()
|
|
|
|
|
|
|
|
|
|
| 21 |
],
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
),
|
| 26 |
-
|
| 27 |
-
max_steps=5
|
| 28 |
)
|
| 29 |
|
| 30 |
-
print("BasicAgent initialized.")
|
| 31 |
|
| 32 |
def __call__(self, question: str) -> str:
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
prompt = f"""
|
| 37 |
-
You are a GAIA benchmark solving agent.
|
| 38 |
-
|
| 39 |
-
Solve the question correctly.
|
| 40 |
-
|
| 41 |
-
IMPORTANT:
|
| 42 |
-
- Return ONLY the final answer
|
| 43 |
-
- No explanations
|
| 44 |
-
- No reasoning
|
| 45 |
-
- No markdown
|
| 46 |
-
- No extra words
|
| 47 |
-
- No 'FINAL ANSWER'
|
| 48 |
-
- Output must exactly match the expected answer format
|
| 49 |
|
| 50 |
Question:
|
| 51 |
{question}
|
| 52 |
-
"""
|
| 53 |
|
| 54 |
-
|
| 55 |
|
|
|
|
| 56 |
response = self.agent.run(prompt)
|
| 57 |
-
|
| 58 |
final_answer = str(response).strip()
|
| 59 |
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
| 62 |
return final_answer
|
| 63 |
|
| 64 |
except Exception as e:
|
| 65 |
-
|
| 66 |
-
print(f"Agent Error: {e}")
|
| 67 |
-
|
| 68 |
return ""
|
| 69 |
|
| 70 |
|
| 71 |
-
|
|
|
|
|
|
|
| 72 |
|
|
|
|
| 73 |
"""
|
| 74 |
-
Fetches all questions, runs the
|
| 75 |
submits all answers, and displays the results.
|
| 76 |
"""
|
| 77 |
-
|
| 78 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 79 |
space_id = os.getenv("SPACE_ID")
|
| 80 |
|
| 81 |
if profile:
|
|
@@ -89,94 +280,65 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 89 |
questions_url = f"{api_url}/questions"
|
| 90 |
submit_url = f"{api_url}/submit"
|
| 91 |
|
| 92 |
-
#
|
| 93 |
try:
|
| 94 |
agent = BasicAgent()
|
| 95 |
-
|
| 96 |
except Exception as e:
|
| 97 |
-
|
| 98 |
print(f"Error instantiating agent: {e}")
|
| 99 |
-
|
| 100 |
return f"Error initializing agent: {e}", None
|
| 101 |
|
| 102 |
-
# --- Hugging Face Space Repo Link ---
|
| 103 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 104 |
-
|
| 105 |
print(agent_code)
|
| 106 |
|
| 107 |
-
#
|
| 108 |
print(f"Fetching questions from: {questions_url}")
|
| 109 |
-
|
| 110 |
try:
|
| 111 |
-
|
| 112 |
response = requests.get(questions_url, timeout=15)
|
| 113 |
-
|
| 114 |
response.raise_for_status()
|
| 115 |
-
|
| 116 |
questions_data = response.json()
|
| 117 |
-
|
| 118 |
if not questions_data:
|
| 119 |
-
|
| 120 |
print("Fetched questions list is empty.")
|
| 121 |
-
|
| 122 |
return "Fetched questions list is empty or invalid format.", None
|
| 123 |
-
|
| 124 |
print(f"Fetched {len(questions_data)} questions.")
|
| 125 |
-
|
| 126 |
except requests.exceptions.RequestException as e:
|
| 127 |
-
|
| 128 |
print(f"Error fetching questions: {e}")
|
| 129 |
-
|
| 130 |
return f"Error fetching questions: {e}", None
|
| 131 |
-
|
| 132 |
except requests.exceptions.JSONDecodeError as e:
|
| 133 |
-
|
| 134 |
print(f"Error decoding JSON response: {e}")
|
| 135 |
-
|
| 136 |
return f"Error decoding server response: {e}", None
|
| 137 |
-
|
| 138 |
except Exception as e:
|
| 139 |
-
|
| 140 |
print(f"Unexpected error fetching questions: {e}")
|
| 141 |
-
|
| 142 |
return f"Unexpected error fetching questions: {e}", None
|
| 143 |
|
| 144 |
-
#
|
| 145 |
results_log = []
|
| 146 |
answers_payload = []
|
| 147 |
-
|
| 148 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 149 |
|
| 150 |
for item in questions_data:
|
| 151 |
-
|
| 152 |
task_id = item.get("task_id")
|
| 153 |
question_text = item.get("question")
|
| 154 |
|
| 155 |
if not task_id or question_text is None:
|
| 156 |
-
|
| 157 |
print(f"Skipping invalid item: {item}")
|
| 158 |
-
|
| 159 |
continue
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
submitted_answer = agent(question_text)
|
| 164 |
|
|
|
|
|
|
|
| 165 |
answers_payload.append({
|
| 166 |
"task_id": task_id,
|
| 167 |
"submitted_answer": submitted_answer
|
| 168 |
})
|
| 169 |
-
|
| 170 |
results_log.append({
|
| 171 |
"Task ID": task_id,
|
| 172 |
"Question": question_text,
|
| 173 |
"Submitted Answer": submitted_answer
|
| 174 |
})
|
| 175 |
-
|
| 176 |
except Exception as e:
|
| 177 |
-
|
| 178 |
print(f"Error running agent on task {task_id}: {e}")
|
| 179 |
-
|
| 180 |
results_log.append({
|
| 181 |
"Task ID": task_id,
|
| 182 |
"Question": question_text,
|
|
@@ -184,33 +346,22 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 184 |
})
|
| 185 |
|
| 186 |
if not answers_payload:
|
| 187 |
-
|
| 188 |
print("Agent did not produce any answers.")
|
| 189 |
-
|
| 190 |
return "Agent did not produce any answers.", pd.DataFrame(results_log)
|
| 191 |
|
| 192 |
-
#
|
| 193 |
submission_data = {
|
| 194 |
"username": username.strip(),
|
| 195 |
"agent_code": agent_code,
|
| 196 |
"answers": answers_payload
|
| 197 |
}
|
| 198 |
-
|
| 199 |
print(f"Submitting {len(answers_payload)} answers...")
|
| 200 |
|
| 201 |
-
#
|
| 202 |
try:
|
| 203 |
-
|
| 204 |
-
response = requests.post(
|
| 205 |
-
submit_url,
|
| 206 |
-
json=submission_data,
|
| 207 |
-
timeout=60
|
| 208 |
-
)
|
| 209 |
-
|
| 210 |
response.raise_for_status()
|
| 211 |
-
|
| 212 |
result_data = response.json()
|
| 213 |
-
|
| 214 |
final_status = (
|
| 215 |
f"Submission Successful!\n"
|
| 216 |
f"User: {result_data.get('username')}\n"
|
|
@@ -219,88 +370,61 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 219 |
f"{result_data.get('total_attempted', '?')} correct)\n"
|
| 220 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 221 |
)
|
| 222 |
-
|
| 223 |
print("Submission successful.")
|
| 224 |
-
|
| 225 |
-
results_df = pd.DataFrame(results_log)
|
| 226 |
-
|
| 227 |
-
return final_status, results_df
|
| 228 |
|
| 229 |
except requests.exceptions.HTTPError as e:
|
| 230 |
-
|
| 231 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 232 |
-
|
| 233 |
try:
|
| 234 |
-
|
| 235 |
error_json = e.response.json()
|
| 236 |
-
|
| 237 |
-
error_detail += (
|
| 238 |
-
f" Detail: {error_json.get('detail', e.response.text)}"
|
| 239 |
-
)
|
| 240 |
-
|
| 241 |
except requests.exceptions.JSONDecodeError:
|
| 242 |
-
|
| 243 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 244 |
-
|
| 245 |
status_message = f"Submission Failed: {error_detail}"
|
| 246 |
-
|
| 247 |
print(status_message)
|
| 248 |
-
|
| 249 |
-
results_df = pd.DataFrame(results_log)
|
| 250 |
-
|
| 251 |
-
return status_message, results_df
|
| 252 |
|
| 253 |
except requests.exceptions.Timeout:
|
| 254 |
-
|
| 255 |
status_message = "Submission Failed: Request timed out."
|
| 256 |
-
|
| 257 |
print(status_message)
|
| 258 |
-
|
| 259 |
-
results_df = pd.DataFrame(results_log)
|
| 260 |
-
|
| 261 |
-
return status_message, results_df
|
| 262 |
|
| 263 |
except requests.exceptions.RequestException as e:
|
| 264 |
-
|
| 265 |
status_message = f"Submission Failed: Network error - {e}"
|
| 266 |
-
|
| 267 |
print(status_message)
|
| 268 |
-
|
| 269 |
-
results_df = pd.DataFrame(results_log)
|
| 270 |
-
|
| 271 |
-
return status_message, results_df
|
| 272 |
|
| 273 |
except Exception as e:
|
| 274 |
-
|
| 275 |
status_message = f"Unexpected submission error: {e}"
|
| 276 |
-
|
| 277 |
print(status_message)
|
|
|
|
| 278 |
|
| 279 |
-
results_df = pd.DataFrame(results_log)
|
| 280 |
-
|
| 281 |
-
return status_message, results_df
|
| 282 |
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
-
# --- Build Gradio Interface ---
|
| 285 |
with gr.Blocks() as demo:
|
| 286 |
|
| 287 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 288 |
-
|
| 289 |
gr.Markdown(
|
| 290 |
"""
|
| 291 |
## Instructions
|
| 292 |
|
| 293 |
-
1.
|
| 294 |
-
2.
|
| 295 |
-
3.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
"""
|
| 297 |
)
|
| 298 |
|
| 299 |
gr.LoginButton()
|
| 300 |
|
| 301 |
-
run_button = gr.Button(
|
| 302 |
-
"Run Evaluation & Submit All Answers"
|
| 303 |
-
)
|
| 304 |
|
| 305 |
status_output = gr.Textbox(
|
| 306 |
label="Run Status / Submission Result",
|
|
@@ -320,44 +444,24 @@ with gr.Blocks() as demo:
|
|
| 320 |
|
| 321 |
|
| 322 |
if __name__ == "__main__":
|
| 323 |
-
|
| 324 |
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 325 |
|
| 326 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 327 |
space_id_startup = os.getenv("SPACE_ID")
|
| 328 |
|
| 329 |
if space_host_startup:
|
| 330 |
-
|
| 331 |
print(f"β
SPACE_HOST found: {space_host_startup}")
|
| 332 |
-
|
| 333 |
-
print(
|
| 334 |
-
f"Runtime URL: https://{space_host_startup}.hf.space"
|
| 335 |
-
)
|
| 336 |
-
|
| 337 |
else:
|
| 338 |
-
|
| 339 |
-
print("SPACE_HOST not found.")
|
| 340 |
|
| 341 |
if space_id_startup:
|
| 342 |
-
|
| 343 |
print(f"β
SPACE_ID found: {space_id_startup}")
|
| 344 |
-
|
| 345 |
-
print(
|
| 346 |
-
f"Repo URL: https://huggingface.co/spaces/{space_id_startup}"
|
| 347 |
-
)
|
| 348 |
-
|
| 349 |
-
print(
|
| 350 |
-
f"Repo Tree URL: "
|
| 351 |
-
f"https://huggingface.co/spaces/"
|
| 352 |
-
f"{space_id_startup}/tree/main"
|
| 353 |
-
)
|
| 354 |
-
|
| 355 |
else:
|
| 356 |
-
|
| 357 |
-
print("SPACE_ID not found.")
|
| 358 |
|
| 359 |
print("-" * 80 + "\n")
|
| 360 |
-
|
| 361 |
print("Launching Gradio Interface...")
|
| 362 |
-
|
| 363 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
+
import gradio as gr
|
| 6 |
|
| 7 |
+
from smolagents import CodeAgent, HfApiModel, tool
|
| 8 |
from smolagents.tools import DuckDuckGoSearchTool
|
| 9 |
|
| 10 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
# Constants
|
| 12 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
| 15 |
|
| 16 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 17 |
+
# Custom Tools
|
| 18 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 19 |
+
|
| 20 |
+
@tool
|
| 21 |
+
def visit_webpage(url: str) -> str:
|
| 22 |
+
"""
|
| 23 |
+
Fetches and returns the visible text content of any webpage.
|
| 24 |
+
Use this to read Wikipedia articles, news pages, official sites, etc.
|
| 25 |
+
Always use this after a web search to get full details from a URL.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
url: The full URL to fetch (must start with http:// or https://)
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
The visible text of the page, truncated to ~8000 characters.
|
| 32 |
+
"""
|
| 33 |
+
try:
|
| 34 |
+
headers = {
|
| 35 |
+
"User-Agent": (
|
| 36 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 37 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 38 |
+
"Chrome/120.0.0.0 Safari/537.36"
|
| 39 |
+
)
|
| 40 |
+
}
|
| 41 |
+
resp = requests.get(url, headers=headers, timeout=15)
|
| 42 |
+
resp.raise_for_status()
|
| 43 |
+
content = resp.text
|
| 44 |
+
# Strip HTML tags
|
| 45 |
+
clean = re.sub(r"<style[^>]*>.*?</style>", " ", content, flags=re.DOTALL)
|
| 46 |
+
clean = re.sub(r"<script[^>]*>.*?</script>", " ", clean, flags=re.DOTALL)
|
| 47 |
+
clean = re.sub(r"<[^>]+>", " ", clean)
|
| 48 |
+
clean = re.sub(r"\s+", " ", clean).strip()
|
| 49 |
+
return clean[:8000]
|
| 50 |
+
except Exception as e:
|
| 51 |
+
return f"Error fetching {url}: {e}"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@tool
|
| 55 |
+
def download_task_file(task_id: str) -> str:
|
| 56 |
+
"""
|
| 57 |
+
Downloads the file attached to a GAIA task and returns its text content.
|
| 58 |
+
Use this whenever the question mentions or implies an attached file
|
| 59 |
+
(e.g. a spreadsheet, PDF, image, audio, CSV, etc.)
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
task_id: The task_id string from the [task_id: ...] tag in the question.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
The text content extracted from the file, or a descriptive note.
|
| 66 |
+
"""
|
| 67 |
+
try:
|
| 68 |
+
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
| 69 |
+
resp = requests.get(url, timeout=30)
|
| 70 |
+
if resp.status_code == 404:
|
| 71 |
+
return "No file is associated with this task."
|
| 72 |
+
resp.raise_for_status()
|
| 73 |
+
|
| 74 |
+
content_type = resp.headers.get("Content-Type", "")
|
| 75 |
+
content_disposition = resp.headers.get("Content-Disposition", "")
|
| 76 |
+
|
| 77 |
+
# Detect filename from headers
|
| 78 |
+
filename = ""
|
| 79 |
+
if "filename=" in content_disposition:
|
| 80 |
+
filename = content_disposition.split("filename=")[-1].strip().strip('"')
|
| 81 |
+
|
| 82 |
+
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
| 83 |
+
|
| 84 |
+
# Plain text / CSV / TSV
|
| 85 |
+
if "text" in content_type or ext in ("txt", "csv", "tsv", "md"):
|
| 86 |
+
return resp.text[:6000]
|
| 87 |
+
|
| 88 |
+
# JSON
|
| 89 |
+
if "json" in content_type or ext == "json":
|
| 90 |
+
return resp.text[:6000]
|
| 91 |
+
|
| 92 |
+
# Code files
|
| 93 |
+
if ext in ("py", "js", "html", "xml", "yaml", "yml"):
|
| 94 |
+
return resp.text[:6000]
|
| 95 |
+
|
| 96 |
+
# Excel / spreadsheet
|
| 97 |
+
if ext in ("xlsx", "xls"):
|
| 98 |
+
try:
|
| 99 |
+
import io
|
| 100 |
+
import openpyxl
|
| 101 |
+
wb = openpyxl.load_workbook(io.BytesIO(resp.content), data_only=True)
|
| 102 |
+
lines = []
|
| 103 |
+
for sheet in wb.sheetnames:
|
| 104 |
+
ws = wb[sheet]
|
| 105 |
+
lines.append(f"=== Sheet: {sheet} ===")
|
| 106 |
+
for row in ws.iter_rows(values_only=True):
|
| 107 |
+
lines.append("\t".join(str(c) if c is not None else "" for c in row))
|
| 108 |
+
return "\n".join(lines)[:6000]
|
| 109 |
+
except Exception as e:
|
| 110 |
+
return f"Could not parse Excel file: {e}"
|
| 111 |
+
|
| 112 |
+
# PDF
|
| 113 |
+
if "pdf" in content_type or ext == "pdf":
|
| 114 |
+
try:
|
| 115 |
+
import io
|
| 116 |
+
import pdfminer.high_level
|
| 117 |
+
text = pdfminer.high_level.extract_text(io.BytesIO(resp.content))
|
| 118 |
+
return (text or "PDF had no extractable text.")[:6000]
|
| 119 |
+
except Exception as e:
|
| 120 |
+
return f"Could not parse PDF: {e}"
|
| 121 |
+
|
| 122 |
+
# Audio
|
| 123 |
+
if ext in ("mp3", "wav", "m4a", "flac", "ogg") or "audio" in content_type:
|
| 124 |
+
return (
|
| 125 |
+
f"Audio file detected ({filename or content_type}). "
|
| 126 |
+
"Audio transcription is not available in this environment. "
|
| 127 |
+
"Try to answer based on the question context alone."
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Image
|
| 131 |
+
if ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp") or "image" in content_type:
|
| 132 |
+
return (
|
| 133 |
+
f"Image file detected ({filename or content_type}). "
|
| 134 |
+
"Image content cannot be read as text here. "
|
| 135 |
+
"Try to answer based on the question context alone."
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Fallback: try UTF-8 decode
|
| 139 |
+
try:
|
| 140 |
+
return resp.content.decode("utf-8")[:6000]
|
| 141 |
+
except Exception:
|
| 142 |
+
return f"Binary file ({filename or content_type}) β cannot extract text."
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
return f"Error downloading file for task {task_id}: {e}"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@tool
|
| 149 |
+
def calculate(expression: str) -> str:
|
| 150 |
+
"""
|
| 151 |
+
Safely evaluates a mathematical expression and returns the result.
|
| 152 |
+
Use this for arithmetic, percentages, unit conversions, or any numeric calculation.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
expression: A valid Python math expression.
|
| 156 |
+
Examples: "2 ** 10", "round(3.14159 * 5**2, 2)", "100 * 1.07 ** 3"
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
The numeric result as a string, or an error message.
|
| 160 |
+
"""
|
| 161 |
+
try:
|
| 162 |
+
import math as _math
|
| 163 |
+
allowed_names = {k: v for k, v in _math.__dict__.items() if not k.startswith("_")}
|
| 164 |
+
allowed_names["round"] = round
|
| 165 |
+
allowed_names["abs"] = abs
|
| 166 |
+
allowed_names["__builtins__"] = {}
|
| 167 |
+
result = eval(expression, {"__builtins__": {}}, allowed_names) # noqa: S307
|
| 168 |
+
return str(result)
|
| 169 |
+
except Exception as e:
|
| 170 |
+
return f"Calculation error for '{expression}': {e}"
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 174 |
+
# System Prompt
|
| 175 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 176 |
+
|
| 177 |
+
SYSTEM_PROMPT = """You are an expert AI assistant specialised in solving GAIA benchmark questions.
|
| 178 |
+
|
| 179 |
+
GAIA questions require multi-step reasoning, web search, reading webpages, file analysis, and precise calculation.
|
| 180 |
+
|
| 181 |
+
STRICT OUTPUT RULES β never break these:
|
| 182 |
+
1. Your FINAL output must be ONLY the bare answer itself.
|
| 183 |
+
2. No explanations. No reasoning. No preamble. No "The answer is...".
|
| 184 |
+
3. No markdown. No bullet points. No code blocks.
|
| 185 |
+
4. NEVER include the words "FINAL ANSWER" anywhere.
|
| 186 |
+
5. Match the exact expected format:
|
| 187 |
+
- If the answer is a number β output just the number (e.g. "42" or "3.14")
|
| 188 |
+
- If the answer is a name β output just the name (e.g. "Marie Curie")
|
| 189 |
+
- If the answer is a list β output comma-separated values (e.g. "apple, banana, cherry")
|
| 190 |
+
- If the answer is a date β output just the date in the format implied by the question
|
| 191 |
+
6. Never output an empty string β always give your best answer.
|
| 192 |
+
|
| 193 |
+
STRATEGY (follow these steps in order):
|
| 194 |
+
1. Read the question carefully. Note the [task_id: ...] at the top.
|
| 195 |
+
2. If the question references a file, immediately call download_task_file(task_id).
|
| 196 |
+
3. Search the web using DuckDuckGoSearchTool for key facts.
|
| 197 |
+
4. Call visit_webpage on the most relevant URLs to get full page content.
|
| 198 |
+
5. Use calculate for any arithmetic needed.
|
| 199 |
+
6. Synthesise all gathered information.
|
| 200 |
+
7. Output ONLY the final answer β nothing else.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 205 |
+
# Agent Definition
|
| 206 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 207 |
+
|
| 208 |
class BasicAgent:
|
| 209 |
|
| 210 |
def __init__(self):
|
| 211 |
+
model = HfApiModel(
|
| 212 |
+
model_id="Qwen/Qwen2.5-72B-Instruct",
|
| 213 |
+
)
|
| 214 |
|
| 215 |
self.agent = CodeAgent(
|
| 216 |
tools=[
|
| 217 |
+
DuckDuckGoSearchTool(),
|
| 218 |
+
visit_webpage,
|
| 219 |
+
download_task_file,
|
| 220 |
+
calculate,
|
| 221 |
],
|
| 222 |
+
model=model,
|
| 223 |
+
max_steps=10,
|
| 224 |
+
verbosity_level=1,
|
|
|
|
|
|
|
|
|
|
| 225 |
)
|
| 226 |
|
| 227 |
+
print("BasicAgent initialized with Qwen2.5-72B + web search + file reader + calculator.")
|
| 228 |
|
| 229 |
def __call__(self, question: str) -> str:
|
| 230 |
+
print(f"\n{'='*60}")
|
| 231 |
+
print(f"Question: {question[:300]}")
|
| 232 |
+
print(f"{'='*60}")
|
| 233 |
|
| 234 |
+
prompt = f"""{SYSTEM_PROMPT}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
Question:
|
| 237 |
{question}
|
|
|
|
| 238 |
|
| 239 |
+
Output ONLY the exact final answer. Nothing else."""
|
| 240 |
|
| 241 |
+
try:
|
| 242 |
response = self.agent.run(prompt)
|
|
|
|
| 243 |
final_answer = str(response).strip()
|
| 244 |
|
| 245 |
+
# Strip any accidental "FINAL ANSWER:" prefix the model might add
|
| 246 |
+
for prefix in [
|
| 247 |
+
"FINAL ANSWER:", "FINAL ANSWER", "Answer:", "answer:",
|
| 248 |
+
"The answer is:", "The answer is"
|
| 249 |
+
]:
|
| 250 |
+
if final_answer.upper().startswith(prefix.upper()):
|
| 251 |
+
final_answer = final_answer[len(prefix):].strip()
|
| 252 |
|
| 253 |
+
print(f"\nβ
Final Answer: {final_answer}")
|
| 254 |
return final_answer
|
| 255 |
|
| 256 |
except Exception as e:
|
| 257 |
+
print(f"β Agent error: {e}")
|
|
|
|
|
|
|
| 258 |
return ""
|
| 259 |
|
| 260 |
|
| 261 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 262 |
+
# Submission Logic (from template β do not modify)
|
| 263 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 264 |
|
| 265 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 266 |
"""
|
| 267 |
+
Fetches all questions, runs the BasicAgent on them,
|
| 268 |
submits all answers, and displays the results.
|
| 269 |
"""
|
|
|
|
|
|
|
| 270 |
space_id = os.getenv("SPACE_ID")
|
| 271 |
|
| 272 |
if profile:
|
|
|
|
| 280 |
questions_url = f"{api_url}/questions"
|
| 281 |
submit_url = f"{api_url}/submit"
|
| 282 |
|
| 283 |
+
# Instantiate Agent
|
| 284 |
try:
|
| 285 |
agent = BasicAgent()
|
|
|
|
| 286 |
except Exception as e:
|
|
|
|
| 287 |
print(f"Error instantiating agent: {e}")
|
|
|
|
| 288 |
return f"Error initializing agent: {e}", None
|
| 289 |
|
|
|
|
| 290 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 291 |
print(agent_code)
|
| 292 |
|
| 293 |
+
# Fetch Questions
|
| 294 |
print(f"Fetching questions from: {questions_url}")
|
|
|
|
| 295 |
try:
|
|
|
|
| 296 |
response = requests.get(questions_url, timeout=15)
|
|
|
|
| 297 |
response.raise_for_status()
|
|
|
|
| 298 |
questions_data = response.json()
|
|
|
|
| 299 |
if not questions_data:
|
|
|
|
| 300 |
print("Fetched questions list is empty.")
|
|
|
|
| 301 |
return "Fetched questions list is empty or invalid format.", None
|
|
|
|
| 302 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
| 303 |
except requests.exceptions.RequestException as e:
|
|
|
|
| 304 |
print(f"Error fetching questions: {e}")
|
|
|
|
| 305 |
return f"Error fetching questions: {e}", None
|
|
|
|
| 306 |
except requests.exceptions.JSONDecodeError as e:
|
|
|
|
| 307 |
print(f"Error decoding JSON response: {e}")
|
|
|
|
| 308 |
return f"Error decoding server response: {e}", None
|
|
|
|
| 309 |
except Exception as e:
|
|
|
|
| 310 |
print(f"Unexpected error fetching questions: {e}")
|
|
|
|
| 311 |
return f"Unexpected error fetching questions: {e}", None
|
| 312 |
|
| 313 |
+
# Run Agent
|
| 314 |
results_log = []
|
| 315 |
answers_payload = []
|
|
|
|
| 316 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 317 |
|
| 318 |
for item in questions_data:
|
|
|
|
| 319 |
task_id = item.get("task_id")
|
| 320 |
question_text = item.get("question")
|
| 321 |
|
| 322 |
if not task_id or question_text is None:
|
|
|
|
| 323 |
print(f"Skipping invalid item: {item}")
|
|
|
|
| 324 |
continue
|
| 325 |
|
| 326 |
+
# Prepend task_id so the agent can use it for file downloads
|
| 327 |
+
augmented_question = f"[task_id: {task_id}]\n{question_text}"
|
|
|
|
| 328 |
|
| 329 |
+
try:
|
| 330 |
+
submitted_answer = agent(augmented_question)
|
| 331 |
answers_payload.append({
|
| 332 |
"task_id": task_id,
|
| 333 |
"submitted_answer": submitted_answer
|
| 334 |
})
|
|
|
|
| 335 |
results_log.append({
|
| 336 |
"Task ID": task_id,
|
| 337 |
"Question": question_text,
|
| 338 |
"Submitted Answer": submitted_answer
|
| 339 |
})
|
|
|
|
| 340 |
except Exception as e:
|
|
|
|
| 341 |
print(f"Error running agent on task {task_id}: {e}")
|
|
|
|
| 342 |
results_log.append({
|
| 343 |
"Task ID": task_id,
|
| 344 |
"Question": question_text,
|
|
|
|
| 346 |
})
|
| 347 |
|
| 348 |
if not answers_payload:
|
|
|
|
| 349 |
print("Agent did not produce any answers.")
|
|
|
|
| 350 |
return "Agent did not produce any answers.", pd.DataFrame(results_log)
|
| 351 |
|
| 352 |
+
# Prepare Submission
|
| 353 |
submission_data = {
|
| 354 |
"username": username.strip(),
|
| 355 |
"agent_code": agent_code,
|
| 356 |
"answers": answers_payload
|
| 357 |
}
|
|
|
|
| 358 |
print(f"Submitting {len(answers_payload)} answers...")
|
| 359 |
|
| 360 |
+
# Submit
|
| 361 |
try:
|
| 362 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
response.raise_for_status()
|
|
|
|
| 364 |
result_data = response.json()
|
|
|
|
| 365 |
final_status = (
|
| 366 |
f"Submission Successful!\n"
|
| 367 |
f"User: {result_data.get('username')}\n"
|
|
|
|
| 370 |
f"{result_data.get('total_attempted', '?')} correct)\n"
|
| 371 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 372 |
)
|
|
|
|
| 373 |
print("Submission successful.")
|
| 374 |
+
return final_status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
except requests.exceptions.HTTPError as e:
|
|
|
|
| 377 |
error_detail = f"Server responded with status {e.response.status_code}."
|
|
|
|
| 378 |
try:
|
|
|
|
| 379 |
error_json = e.response.json()
|
| 380 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
except requests.exceptions.JSONDecodeError:
|
|
|
|
| 382 |
error_detail += f" Response: {e.response.text[:500]}"
|
|
|
|
| 383 |
status_message = f"Submission Failed: {error_detail}"
|
|
|
|
| 384 |
print(status_message)
|
| 385 |
+
return status_message, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
except requests.exceptions.Timeout:
|
|
|
|
| 388 |
status_message = "Submission Failed: Request timed out."
|
|
|
|
| 389 |
print(status_message)
|
| 390 |
+
return status_message, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 391 |
|
| 392 |
except requests.exceptions.RequestException as e:
|
|
|
|
| 393 |
status_message = f"Submission Failed: Network error - {e}"
|
|
|
|
| 394 |
print(status_message)
|
| 395 |
+
return status_message, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
except Exception as e:
|
|
|
|
| 398 |
status_message = f"Unexpected submission error: {e}"
|
|
|
|
| 399 |
print(status_message)
|
| 400 |
+
return status_message, pd.DataFrame(results_log)
|
| 401 |
|
|
|
|
|
|
|
|
|
|
| 402 |
|
| 403 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 404 |
+
# Gradio Interface
|
| 405 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 406 |
|
|
|
|
| 407 |
with gr.Blocks() as demo:
|
| 408 |
|
| 409 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
|
|
|
| 410 |
gr.Markdown(
|
| 411 |
"""
|
| 412 |
## Instructions
|
| 413 |
|
| 414 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc.
|
| 415 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 416 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 417 |
+
|
| 418 |
+
---
|
| 419 |
+
**Disclaimers:**
|
| 420 |
+
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).
|
| 421 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
|
| 422 |
"""
|
| 423 |
)
|
| 424 |
|
| 425 |
gr.LoginButton()
|
| 426 |
|
| 427 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
|
|
|
| 428 |
|
| 429 |
status_output = gr.Textbox(
|
| 430 |
label="Run Status / Submission Result",
|
|
|
|
| 444 |
|
| 445 |
|
| 446 |
if __name__ == "__main__":
|
|
|
|
| 447 |
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 448 |
|
| 449 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 450 |
space_id_startup = os.getenv("SPACE_ID")
|
| 451 |
|
| 452 |
if space_host_startup:
|
|
|
|
| 453 |
print(f"β
SPACE_HOST found: {space_host_startup}")
|
| 454 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
else:
|
| 456 |
+
print("βΉοΈ SPACE_HOST not found (running locally?).")
|
|
|
|
| 457 |
|
| 458 |
if space_id_startup:
|
|
|
|
| 459 |
print(f"β
SPACE_ID found: {space_id_startup}")
|
| 460 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 461 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
else:
|
| 463 |
+
print("βΉοΈ SPACE_ID not found (running locally?).")
|
|
|
|
| 464 |
|
| 465 |
print("-" * 80 + "\n")
|
|
|
|
| 466 |
print("Launching Gradio Interface...")
|
|
|
|
| 467 |
demo.launch(debug=True, share=False)
|