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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import base64
|
| 3 |
+
import json
|
| 4 |
+
import mimetypes
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
from urllib.parse import urlparse
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import requests
|
| 14 |
+
from bs4 import BeautifulSoup
|
| 15 |
+
from ddgs import DDGS
|
| 16 |
+
from huggingface_hub import InferenceClient
|
| 17 |
+
from openai import OpenAI
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 21 |
+
TEXT_MODEL = os.getenv("TEXT_MODEL", "openai/gpt-oss-120b:cerebras")
|
| 22 |
+
VISION_MODEL = os.getenv("VISION_MODEL", "Qwen/Qwen2.5-VL-72B-Instruct")
|
| 23 |
+
ASR_MODEL = os.getenv("ASR_MODEL", "openai/whisper-large-v3")
|
| 24 |
+
HTTP_HEADERS = {
|
| 25 |
+
"User-Agent": (
|
| 26 |
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
| 27 |
+
"Chrome/131.0 Safari/537.36"
|
| 28 |
+
)
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
SYSTEM_PROMPT = """
|
| 32 |
+
You are solving one GAIA Level 1 benchmark question. Work carefully from the
|
| 33 |
+
question and supplied evidence. The answer is checked using exact matching.
|
| 34 |
+
|
| 35 |
+
Return ONLY the final answer: no reasoning, citations, markdown, labels,
|
| 36 |
+
greetings, or phrase such as "FINAL ANSWER" or "The answer is".
|
| 37 |
+
Follow every requested formatting instruction exactly. Preserve required units.
|
| 38 |
+
For lists, use the delimiter and ordering requested. If evidence conflicts,
|
| 39 |
+
choose the best-supported answer and double-check spelling, capitalization,
|
| 40 |
+
dates, calculations, and punctuation.
|
| 41 |
+
""".strip()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def clean_answer(value: Any) -> str:
|
| 45 |
+
answer = "" if value is None else str(value)
|
| 46 |
+
answer = answer.strip().strip("`").strip()
|
| 47 |
+
answer = re.sub(
|
| 48 |
+
r"^\s*(?:final\s+answer|answer)\s*:\s*",
|
| 49 |
+
"",
|
| 50 |
+
answer,
|
| 51 |
+
flags=re.IGNORECASE,
|
| 52 |
+
).strip()
|
| 53 |
+
if len(answer) >= 2 and answer[0] == answer[-1] and answer[0] in "\"'":
|
| 54 |
+
answer = answer[1:-1].strip()
|
| 55 |
+
return answer
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def reverse_hint(question: str) -> str:
|
| 59 |
+
reversed_text = question[::-1]
|
| 60 |
+
common = ("the", "this", "answer", "write", "word", "opposite")
|
| 61 |
+
score = sum(token in reversed_text.lower() for token in common)
|
| 62 |
+
if score >= 3:
|
| 63 |
+
return f"The question appears character-reversed. Decoded text:\n{reversed_text}"
|
| 64 |
+
return ""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def commutativity_analysis(question: str) -> str:
|
| 68 |
+
"""Analyze a Markdown Cayley table without hard-coding benchmark values."""
|
| 69 |
+
lines = [line.strip() for line in question.splitlines() if line.strip().startswith("|")]
|
| 70 |
+
if len(lines) < 4 or "commut" not in question.lower():
|
| 71 |
+
return ""
|
| 72 |
+
try:
|
| 73 |
+
rows = [[cell.strip() for cell in line.strip("|").split("|")] for line in lines]
|
| 74 |
+
header = rows[0][1:]
|
| 75 |
+
body = rows[2:]
|
| 76 |
+
table = {row[0]: dict(zip(header, row[1:])) for row in body if len(row) == len(header) + 1}
|
| 77 |
+
involved = set()
|
| 78 |
+
counterexamples = []
|
| 79 |
+
for i, left in enumerate(header):
|
| 80 |
+
for right in header[i + 1 :]:
|
| 81 |
+
lr = table[left][right]
|
| 82 |
+
rl = table[right][left]
|
| 83 |
+
if lr != rl:
|
| 84 |
+
involved.update((left, right))
|
| 85 |
+
counterexamples.append(f"{left}*{right}={lr}, {right}*{left}={rl}")
|
| 86 |
+
if counterexamples:
|
| 87 |
+
return (
|
| 88 |
+
"Computed directly from the supplied operation table. "
|
| 89 |
+
f"Counterexamples: {'; '.join(counterexamples)}. "
|
| 90 |
+
f"Elements involved (sorted): {', '.join(sorted(involved))}."
|
| 91 |
+
)
|
| 92 |
+
except Exception as error:
|
| 93 |
+
return f"Table parser could not finish: {error}"
|
| 94 |
+
return ""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def extract_youtube_id(question: str) -> str | None:
|
| 98 |
+
match = re.search(
|
| 99 |
+
r"(?:youtube\.com/watch\?v=|youtu\.be/)([A-Za-z0-9_-]{11})",
|
| 100 |
+
question,
|
| 101 |
+
)
|
| 102 |
+
return match.group(1) if match else None
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def youtube_transcript(video_id: str) -> str:
|
| 106 |
+
try:
|
| 107 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 108 |
+
|
| 109 |
+
api = YouTubeTranscriptApi()
|
| 110 |
+
try:
|
| 111 |
+
transcript = api.fetch(video_id)
|
| 112 |
+
except AttributeError:
|
| 113 |
+
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
| 114 |
+
chunks = []
|
| 115 |
+
for item in transcript:
|
| 116 |
+
if hasattr(item, "text"):
|
| 117 |
+
chunks.append(item.text)
|
| 118 |
+
elif isinstance(item, dict):
|
| 119 |
+
chunks.append(str(item.get("text", "")))
|
| 120 |
+
text = " ".join(chunks).strip()
|
| 121 |
+
return text[:30000]
|
| 122 |
+
except Exception as error:
|
| 123 |
+
return f"YouTube transcript unavailable: {error}"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def safe_page_text(url: str, limit: int = 9000) -> str:
|
| 127 |
+
parsed = urlparse(url)
|
| 128 |
+
if parsed.scheme not in {"http", "https"}:
|
| 129 |
+
return ""
|
| 130 |
+
try:
|
| 131 |
+
response = requests.get(url, headers=HTTP_HEADERS, timeout=15)
|
| 132 |
+
response.raise_for_status()
|
| 133 |
+
content_type = response.headers.get("content-type", "")
|
| 134 |
+
if "html" not in content_type and "text" not in content_type and "json" not in content_type:
|
| 135 |
+
return ""
|
| 136 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 137 |
+
for node in soup(["script", "style", "noscript", "svg"]):
|
| 138 |
+
node.decompose()
|
| 139 |
+
text = " ".join(soup.get_text(" ", strip=True).split())
|
| 140 |
+
return text[:limit]
|
| 141 |
+
except Exception:
|
| 142 |
+
return ""
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def search_web(queries: list[str], max_results: int = 6) -> str:
|
| 146 |
+
seen_urls: set[str] = set()
|
| 147 |
+
records: list[str] = []
|
| 148 |
+
for query in queries[:4]:
|
| 149 |
+
if not query.strip():
|
| 150 |
+
continue
|
| 151 |
+
try:
|
| 152 |
+
results = DDGS().text(query, max_results=max_results)
|
| 153 |
+
except Exception as error:
|
| 154 |
+
records.append(f"SEARCH ERROR for {query!r}: {error}")
|
| 155 |
+
continue
|
| 156 |
+
for result in results or []:
|
| 157 |
+
url = str(result.get("href") or result.get("url") or "")
|
| 158 |
+
if not url or url in seen_urls:
|
| 159 |
+
continue
|
| 160 |
+
seen_urls.add(url)
|
| 161 |
+
title = str(result.get("title") or "")
|
| 162 |
+
snippet = str(result.get("body") or result.get("snippet") or "")
|
| 163 |
+
page = safe_page_text(url)
|
| 164 |
+
records.append(
|
| 165 |
+
f"QUERY: {query}\nTITLE: {title}\nURL: {url}\n"
|
| 166 |
+
f"SNIPPET: {snippet}\nPAGE TEXT: {page}"
|
| 167 |
+
)
|
| 168 |
+
if len("\n\n".join(records)) > 52000:
|
| 169 |
+
return "\n\n---\n\n".join(records)[:52000]
|
| 170 |
+
return "\n\n---\n\n".join(records)[:52000]
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def parse_json_object(text: str) -> dict[str, Any]:
|
| 174 |
+
text = (text or "").strip().strip("`")
|
| 175 |
+
match = re.search(r"\{.*\}", text, flags=re.DOTALL)
|
| 176 |
+
if match:
|
| 177 |
+
text = match.group(0)
|
| 178 |
+
try:
|
| 179 |
+
value = json.loads(text)
|
| 180 |
+
return value if isinstance(value, dict) else {}
|
| 181 |
+
except Exception:
|
| 182 |
+
return {}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def spreadsheet_context(path: Path) -> str:
|
| 186 |
+
workbook = pd.ExcelFile(path)
|
| 187 |
+
parts: list[str] = []
|
| 188 |
+
for sheet_name in workbook.sheet_names:
|
| 189 |
+
frame = pd.read_excel(path, sheet_name=sheet_name)
|
| 190 |
+
parts.append(f"SHEET {sheet_name!r}; shape={frame.shape}; columns={list(frame.columns)!r}")
|
| 191 |
+
if len(frame) <= 250 and len(frame.columns) <= 25:
|
| 192 |
+
parts.append(frame.to_csv(index=False))
|
| 193 |
+
else:
|
| 194 |
+
parts.append(frame.head(100).to_csv(index=False))
|
| 195 |
+
|
| 196 |
+
numeric = frame.select_dtypes(include="number")
|
| 197 |
+
if not numeric.empty:
|
| 198 |
+
parts.append("NUMERIC COLUMN SUMS:\n" + numeric.sum(numeric_only=True).to_string())
|
| 199 |
+
|
| 200 |
+
categorical = [column for column in frame.columns if column not in numeric.columns]
|
| 201 |
+
for category in categorical[:6]:
|
| 202 |
+
if frame[category].nunique(dropna=True) <= 30 and not numeric.empty:
|
| 203 |
+
grouped = frame.groupby(category, dropna=False)[list(numeric.columns)].sum(numeric_only=True)
|
| 204 |
+
parts.append(f"SUMS GROUPED BY {category!r}:\n{grouped.to_string()}")
|
| 205 |
+
return "\n\n".join(parts)[:60000]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def python_context(path: Path) -> str:
|
| 209 |
+
source = path.read_text(encoding="utf-8", errors="replace")
|
| 210 |
+
try:
|
| 211 |
+
ast.parse(source)
|
| 212 |
+
parse_note = "The file is syntactically valid Python. Analyze it; do not assume random paths are impossible."
|
| 213 |
+
except SyntaxError as error:
|
| 214 |
+
parse_note = f"Python parse warning: {error}"
|
| 215 |
+
return f"{parse_note}\n\nPYTHON SOURCE:\n{source[:50000]}"
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class ResearchAgent:
|
| 219 |
+
def __init__(self) -> None:
|
| 220 |
+
token = os.getenv("HF_TOKEN")
|
| 221 |
+
if not token:
|
| 222 |
+
raise RuntimeError(
|
| 223 |
+
"HF_TOKEN is missing. Add a paid-inference-capable Hugging Face token "
|
| 224 |
+
"under Space Settings > Variables and secrets."
|
| 225 |
+
)
|
| 226 |
+
self.openai = OpenAI(
|
| 227 |
+
base_url="https://router.huggingface.co/v1",
|
| 228 |
+
api_key=token,
|
| 229 |
+
timeout=120,
|
| 230 |
+
max_retries=2,
|
| 231 |
+
)
|
| 232 |
+
self.hf = InferenceClient(provider="fal-ai", api_key=token)
|
| 233 |
+
print(f"ResearchAgent ready; text={TEXT_MODEL}, vision={VISION_MODEL}, asr={ASR_MODEL}")
|
| 234 |
+
|
| 235 |
+
def chat(self, messages: list[dict[str, Any]], model: str = TEXT_MODEL, max_tokens: int = 600) -> str:
|
| 236 |
+
last_error: Exception | None = None
|
| 237 |
+
for attempt in range(3):
|
| 238 |
+
try:
|
| 239 |
+
completion = self.openai.chat.completions.create(
|
| 240 |
+
model=model,
|
| 241 |
+
messages=messages,
|
| 242 |
+
temperature=0,
|
| 243 |
+
max_tokens=max_tokens,
|
| 244 |
+
)
|
| 245 |
+
return completion.choices[0].message.content or ""
|
| 246 |
+
except Exception as error:
|
| 247 |
+
last_error = error
|
| 248 |
+
if attempt < 2:
|
| 249 |
+
time.sleep(3 * (attempt + 1))
|
| 250 |
+
raise RuntimeError(f"Inference failed after three attempts: {last_error}")
|
| 251 |
+
|
| 252 |
+
def plan_queries(self, question: str) -> list[str]:
|
| 253 |
+
prompt = (
|
| 254 |
+
"Create 3 concise, distinct web-search queries that would find authoritative "
|
| 255 |
+
"evidence for the question below. Preserve exact names, dates, quoted phrases, "
|
| 256 |
+
"and source/version constraints. Return JSON only as "
|
| 257 |
+
"{\"queries\":[\"...\",\"...\",\"...\"]}.\n\nQUESTION:\n" + question
|
| 258 |
+
)
|
| 259 |
+
try:
|
| 260 |
+
result = self.chat(
|
| 261 |
+
[
|
| 262 |
+
{"role": "system", "content": "You produce focused search queries as strict JSON."},
|
| 263 |
+
{"role": "user", "content": prompt},
|
| 264 |
+
],
|
| 265 |
+
max_tokens=350,
|
| 266 |
+
)
|
| 267 |
+
queries = parse_json_object(result).get("queries", [])
|
| 268 |
+
queries = [str(item).strip() for item in queries if str(item).strip()]
|
| 269 |
+
except Exception:
|
| 270 |
+
queries = []
|
| 271 |
+
fallback = " ".join(question.split())[:500]
|
| 272 |
+
if fallback and fallback not in queries:
|
| 273 |
+
queries.append(fallback)
|
| 274 |
+
return queries[:4]
|
| 275 |
+
|
| 276 |
+
def transcribe(self, path: Path) -> str:
|
| 277 |
+
last_error: Exception | None = None
|
| 278 |
+
for attempt in range(3):
|
| 279 |
+
try:
|
| 280 |
+
result = self.hf.automatic_speech_recognition(
|
| 281 |
+
str(path),
|
| 282 |
+
model=ASR_MODEL,
|
| 283 |
+
)
|
| 284 |
+
text = result.text if hasattr(result, "text") else str(result)
|
| 285 |
+
if text.strip():
|
| 286 |
+
return text.strip()
|
| 287 |
+
except Exception as error:
|
| 288 |
+
last_error = error
|
| 289 |
+
if attempt < 2:
|
| 290 |
+
time.sleep(3 * (attempt + 1))
|
| 291 |
+
return f"Audio transcription unavailable: {last_error}"
|
| 292 |
+
|
| 293 |
+
def inspect_attachment(self, path: Path, question: str) -> str:
|
| 294 |
+
suffix = path.suffix.lower()
|
| 295 |
+
if suffix in {".mp3", ".wav", ".m4a", ".flac", ".ogg"}:
|
| 296 |
+
return "AUDIO TRANSCRIPT:\n" + self.transcribe(path)
|
| 297 |
+
if suffix in {".xlsx", ".xls"}:
|
| 298 |
+
return "SPREADSHEET ANALYSIS:\n" + spreadsheet_context(path)
|
| 299 |
+
if suffix == ".py":
|
| 300 |
+
return python_context(path)
|
| 301 |
+
if suffix in {".png", ".jpg", ".jpeg", ".webp"}:
|
| 302 |
+
mime = mimetypes.guess_type(path.name)[0] or "image/png"
|
| 303 |
+
encoded = base64.b64encode(path.read_bytes()).decode("ascii")
|
| 304 |
+
image_question = (
|
| 305 |
+
f"{SYSTEM_PROMPT}\n\nQUESTION:\n{question}\n\n"
|
| 306 |
+
"Inspect the attached image precisely. If it is a chess position, identify "
|
| 307 |
+
"the board orientation and every piece before calculating the winning move."
|
| 308 |
+
)
|
| 309 |
+
try:
|
| 310 |
+
return "VISION MODEL RESULT:\n" + self.chat(
|
| 311 |
+
[
|
| 312 |
+
{
|
| 313 |
+
"role": "user",
|
| 314 |
+
"content": [
|
| 315 |
+
{"type": "text", "text": image_question},
|
| 316 |
+
{
|
| 317 |
+
"type": "image_url",
|
| 318 |
+
"image_url": {"url": f"data:{mime};base64,{encoded}"},
|
| 319 |
+
},
|
| 320 |
+
],
|
| 321 |
+
}
|
| 322 |
+
],
|
| 323 |
+
model=VISION_MODEL,
|
| 324 |
+
max_tokens=800,
|
| 325 |
+
)
|
| 326 |
+
except Exception as error:
|
| 327 |
+
return f"Vision analysis unavailable: {error}"
|
| 328 |
+
return f"ATTACHMENT TEXT/BYTES METADATA: name={path.name}, size={path.stat().st_size}"
|
| 329 |
+
|
| 330 |
+
def answer(self, task_id: str, question: str, attachment: Path | None = None) -> str:
|
| 331 |
+
evidence: list[str] = []
|
| 332 |
+
|
| 333 |
+
hint = reverse_hint(question)
|
| 334 |
+
if hint:
|
| 335 |
+
evidence.append(hint)
|
| 336 |
+
|
| 337 |
+
table_analysis = commutativity_analysis(question)
|
| 338 |
+
if table_analysis:
|
| 339 |
+
evidence.append(table_analysis)
|
| 340 |
+
|
| 341 |
+
video_id = extract_youtube_id(question)
|
| 342 |
+
if video_id:
|
| 343 |
+
evidence.append("YOUTUBE TRANSCRIPT:\n" + youtube_transcript(video_id))
|
| 344 |
+
|
| 345 |
+
if attachment and attachment.exists():
|
| 346 |
+
evidence.append(self.inspect_attachment(attachment, question))
|
| 347 |
+
|
| 348 |
+
needs_web = not attachment or any(
|
| 349 |
+
token in question.lower()
|
| 350 |
+
for token in ("wikipedia", "article", "paper", "who ", "what country", "how many", "as of")
|
| 351 |
+
)
|
| 352 |
+
if needs_web:
|
| 353 |
+
queries = self.plan_queries(question)
|
| 354 |
+
evidence.append("WEB RESEARCH:\n" + search_web(queries))
|
| 355 |
+
|
| 356 |
+
evidence_text = "\n\n=====\n\n".join(item for item in evidence if item)[:70000]
|
| 357 |
+
user_prompt = (
|
| 358 |
+
f"QUESTION:\n{question}\n\n"
|
| 359 |
+
f"EVIDENCE AND TOOL OUTPUT:\n{evidence_text or 'No external evidence was available.'}\n\n"
|
| 360 |
+
"Solve the question. Return only the exact requested answer."
|
| 361 |
+
)
|
| 362 |
+
raw = self.chat(
|
| 363 |
+
[
|
| 364 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 365 |
+
{"role": "user", "content": user_prompt},
|
| 366 |
+
],
|
| 367 |
+
max_tokens=500,
|
| 368 |
+
)
|
| 369 |
+
answer = clean_answer(raw)
|
| 370 |
+
if not answer:
|
| 371 |
+
raise RuntimeError(f"Model returned an empty answer for task {task_id}")
|
| 372 |
+
return answer
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def download_attachment(task_id: str, file_name: str, directory: Path) -> Path | None:
|
| 376 |
+
if not file_name:
|
| 377 |
+
return None
|
| 378 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 379 |
+
safe_name = Path(file_name).name
|
| 380 |
+
path = directory / safe_name
|
| 381 |
+
if path.exists() and path.stat().st_size > 0:
|
| 382 |
+
return path
|
| 383 |
+
response = requests.get(
|
| 384 |
+
f"{API_URL}/files/{task_id}",
|
| 385 |
+
headers=HTTP_HEADERS,
|
| 386 |
+
timeout=90,
|
| 387 |
+
)
|
| 388 |
+
response.raise_for_status()
|
| 389 |
+
path.write_bytes(response.content)
|
| 390 |
+
return path
|
app.py
CHANGED
|
@@ -1,196 +1,165 @@
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# (Keep Constants as is)
|
| 8 |
-
# --- Constants ---
|
| 9 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
-
|
| 11 |
-
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
-
class BasicAgent:
|
| 14 |
-
def __init__(self):
|
| 15 |
-
print("BasicAgent initialized.")
|
| 16 |
-
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
fixed_answer = "This is a default answer."
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 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 |
-
print("User not logged in.")
|
| 35 |
-
return "Please Login to Hugging Face with the button.", None
|
| 36 |
-
|
| 37 |
-
api_url = DEFAULT_API_URL
|
| 38 |
-
questions_url = f"{api_url}/questions"
|
| 39 |
-
submit_url = f"{api_url}/submit"
|
| 40 |
-
|
| 41 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
-
agent =
|
| 44 |
-
except Exception as
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 48 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
-
print(agent_code)
|
| 50 |
-
|
| 51 |
-
# 2. Fetch Questions
|
| 52 |
-
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
-
response = requests.get(
|
| 55 |
response.raise_for_status()
|
| 56 |
-
|
| 57 |
-
if not
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
answers_payload = []
|
| 75 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 76 |
-
for item in questions_data:
|
| 77 |
-
task_id = item.get("task_id")
|
| 78 |
-
question_text = item.get("question")
|
| 79 |
-
if not task_id or question_text is None:
|
| 80 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 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 |
-
f"User: {
|
| 108 |
-
f"Overall
|
| 109 |
-
f"({
|
| 110 |
-
f"Message: {
|
| 111 |
)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
except
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
return
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 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 |
-
|
| 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.LoginButton()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
-
run_button
|
| 164 |
-
|
| 165 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
|
| 169 |
-
run_button.click(
|
| 170 |
-
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 172 |
-
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 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 |
+
from datetime import datetime, timezone
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
import gradio as gr
|
|
|
|
|
|
|
| 7 |
import pandas as pd
|
| 8 |
+
import requests
|
| 9 |
+
|
| 10 |
+
from agent import API_URL, ResearchAgent, download_attachment
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
CACHE_DIR = Path(".gaia_cache")
|
| 14 |
+
CACHE_FILE = CACHE_DIR / "latest_answers.json"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None, progress=gr.Progress()):
|
| 18 |
+
if not profile:
|
| 19 |
+
return "Please log in to Hugging Face with the login button.", None
|
| 20 |
+
|
| 21 |
+
space_id = os.getenv("SPACE_ID")
|
| 22 |
+
if not space_id:
|
| 23 |
+
return "SPACE_ID is missing from the Space environment.", None
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
try:
|
| 26 |
+
agent = ResearchAgent()
|
| 27 |
+
except Exception as error:
|
| 28 |
+
return f"Agent initialization failed: {error}", None
|
| 29 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
+
response = requests.get(f"{API_URL}/questions", timeout=45)
|
| 32 |
response.raise_for_status()
|
| 33 |
+
questions = response.json()
|
| 34 |
+
if not isinstance(questions, list) or not questions:
|
| 35 |
+
raise RuntimeError("Question API returned an empty or invalid list.")
|
| 36 |
+
except Exception as error:
|
| 37 |
+
return f"Could not fetch evaluation questions: {error}", None
|
| 38 |
+
|
| 39 |
+
answers = []
|
| 40 |
+
rows = []
|
| 41 |
+
attachments_dir = CACHE_DIR / "files"
|
| 42 |
+
|
| 43 |
+
for index, item in enumerate(questions, start=1):
|
| 44 |
+
task_id = str(item.get("task_id") or "")
|
| 45 |
+
question = str(item.get("question") or "")
|
| 46 |
+
file_name = str(item.get("file_name") or "")
|
| 47 |
+
progress((index - 1, len(questions)), desc=f"Solving question {index}/{len(questions)}")
|
| 48 |
+
|
| 49 |
+
answer = ""
|
| 50 |
+
status = "Answered"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
+
attachment = download_attachment(task_id, file_name, attachments_dir)
|
| 53 |
+
answer = agent.answer(task_id, question, attachment)
|
| 54 |
+
except Exception as error:
|
| 55 |
+
status = f"ERROR: {error}"
|
| 56 |
+
print(f"Task {task_id} failed: {error}")
|
| 57 |
+
|
| 58 |
+
answers.append({"task_id": task_id, "submitted_answer": answer})
|
| 59 |
+
rows.append(
|
| 60 |
+
{
|
| 61 |
+
"#": index,
|
| 62 |
+
"Task ID": task_id,
|
| 63 |
+
"Question": question,
|
| 64 |
+
"File": file_name,
|
| 65 |
+
"Submitted Answer": answer,
|
| 66 |
+
"Status": status,
|
| 67 |
+
}
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
| 71 |
+
CACHE_FILE.write_text(
|
| 72 |
+
json.dumps(
|
| 73 |
+
{
|
| 74 |
+
"username": profile.username,
|
| 75 |
+
"space_id": space_id,
|
| 76 |
+
"saved_at": datetime.now(timezone.utc).isoformat(),
|
| 77 |
+
"answers": answers,
|
| 78 |
+
"rows": rows,
|
| 79 |
+
},
|
| 80 |
+
indent=2,
|
| 81 |
+
ensure_ascii=False,
|
| 82 |
+
),
|
| 83 |
+
encoding="utf-8",
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
progress((len(questions), len(questions)), desc="Submitting answers")
|
| 87 |
+
submission = {
|
| 88 |
+
"username": profile.username.strip(),
|
| 89 |
+
"agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
|
| 90 |
+
"answers": answers,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
try:
|
| 94 |
+
response = requests.post(f"{API_URL}/submit", json=submission, timeout=180)
|
| 95 |
response.raise_for_status()
|
| 96 |
+
result = response.json()
|
| 97 |
+
status = (
|
| 98 |
+
"Submission successful!\n"
|
| 99 |
+
f"User: {result.get('username')}\n"
|
| 100 |
+
f"Overall score: {result.get('score', 'N/A')}% "
|
| 101 |
+
f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
|
| 102 |
+
f"Message: {result.get('message', '')}"
|
| 103 |
)
|
| 104 |
+
except requests.exceptions.HTTPError as error:
|
| 105 |
+
detail = error.response.text[:1000] if error.response is not None else str(error)
|
| 106 |
+
status = f"Submission failed with HTTP error: {detail}"
|
| 107 |
+
except Exception as error:
|
| 108 |
+
status = f"Submission failed: {error}"
|
| 109 |
+
|
| 110 |
+
return status, pd.DataFrame(rows)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def submit_cached(profile: gr.OAuthProfile | None):
|
| 114 |
+
if not profile:
|
| 115 |
+
return "Please log in to Hugging Face with the login button.", None
|
| 116 |
+
if not CACHE_FILE.exists():
|
| 117 |
+
return "No cached run exists yet. Run the evaluation first.", None
|
| 118 |
+
|
| 119 |
+
data = json.loads(CACHE_FILE.read_text(encoding="utf-8"))
|
| 120 |
+
space_id = os.getenv("SPACE_ID") or data.get("space_id")
|
| 121 |
+
submission = {
|
| 122 |
+
"username": profile.username.strip(),
|
| 123 |
+
"agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
|
| 124 |
+
"answers": data.get("answers", []),
|
| 125 |
+
}
|
| 126 |
+
try:
|
| 127 |
+
response = requests.post(f"{API_URL}/submit", json=submission, timeout=180)
|
| 128 |
+
response.raise_for_status()
|
| 129 |
+
result = response.json()
|
| 130 |
+
status = (
|
| 131 |
+
"Cached answers submitted successfully!\n"
|
| 132 |
+
f"Overall score: {result.get('score', 'N/A')}% "
|
| 133 |
+
f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
|
| 134 |
+
f"Message: {result.get('message', '')}"
|
| 135 |
+
)
|
| 136 |
+
except Exception as error:
|
| 137 |
+
status = f"Cached submission failed: {error}"
|
| 138 |
+
return status, pd.DataFrame(data.get("rows", []))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
with gr.Blocks() as demo:
|
| 142 |
+
gr.Markdown("# GAIA Multimodal Research Agent")
|
| 143 |
gr.Markdown(
|
| 144 |
"""
|
| 145 |
+
This public Space uses paid Hugging Face Inference Providers plus web,
|
| 146 |
+
spreadsheet, Python, image, video-transcript, and audio tools.
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
+
1. Log in with the Hugging Face account that should receive the score.
|
| 149 |
+
2. Click **Run Evaluation & Submit All Answers** once and wait.
|
| 150 |
+
3. If only the final submission times out, use **Resubmit Cached Answers**.
|
|
|
|
| 151 |
"""
|
| 152 |
)
|
|
|
|
| 153 |
gr.LoginButton()
|
| 154 |
+
with gr.Row():
|
| 155 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 156 |
+
cached_button = gr.Button("Resubmit Cached Answers")
|
| 157 |
+
status_output = gr.Textbox(label="Run / submission status", lines=6, interactive=False)
|
| 158 |
+
results_table = gr.DataFrame(label="Questions and answers", wrap=True)
|
| 159 |
|
| 160 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 161 |
+
cached_button.click(fn=submit_cached, outputs=[status_output, results_table])
|
|
|
|
|
|
|
|
|
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
if __name__ == "__main__":
|
| 165 |
+
demo.queue(default_concurrency_limit=1).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,2 +1,10 @@
|
|
| 1 |
-
gradio
|
| 2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=5.23,<7
|
| 2 |
+
requests>=2.32
|
| 3 |
+
pandas>=2.2
|
| 4 |
+
openpyxl>=3.1
|
| 5 |
+
xlrd>=2.0
|
| 6 |
+
openai>=1.68
|
| 7 |
+
huggingface_hub>=0.30
|
| 8 |
+
ddgs>=9.0
|
| 9 |
+
beautifulsoup4>=4.13
|
| 10 |
+
youtube-transcript-api>=1.0
|