Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,6 +11,7 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 11 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 12 |
|
| 13 |
import re
|
|
|
|
| 14 |
from smolagents import CodeAgent, InferenceClientModel, tool, VisitWebpageTool, DuckDuckGoSearchTool
|
| 15 |
|
| 16 |
|
|
@@ -18,10 +19,11 @@ from smolagents import CodeAgent, InferenceClientModel, tool, VisitWebpageTool,
|
|
| 18 |
def download_task_file(task_id: str) -> str:
|
| 19 |
"""
|
| 20 |
Downloads the file attached to a GAIA task and returns its text content.
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
Args:
|
| 24 |
-
task_id: The task_id string from
|
| 25 |
|
| 26 |
Returns:
|
| 27 |
The text content of the file, or a descriptive note if unreadable.
|
|
@@ -39,8 +41,11 @@ def download_task_file(task_id: str) -> str:
|
|
| 39 |
filename = disposition.split("filename=")[-1].strip().strip('"')
|
| 40 |
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
if ext in ("xlsx", "xls"):
|
| 45 |
try:
|
| 46 |
import io, openpyxl
|
|
@@ -51,24 +56,40 @@ def download_task_file(task_id: str) -> str:
|
|
| 51 |
lines.append(f"=== Sheet: {sheet} ===")
|
| 52 |
for row in ws.iter_rows(values_only=True):
|
| 53 |
lines.append("\t".join(str(c) if c is not None else "" for c in row))
|
| 54 |
-
return "\n".join(lines)[:
|
| 55 |
except Exception as e:
|
| 56 |
-
return f"Could not parse Excel: {e}"
|
|
|
|
|
|
|
| 57 |
if "pdf" in content_type or ext == "pdf":
|
| 58 |
try:
|
| 59 |
import io, pdfminer.high_level
|
| 60 |
text = pdfminer.high_level.extract_text(io.BytesIO(resp.content))
|
| 61 |
-
return (text or "No text in PDF.")[:
|
| 62 |
except Exception as e:
|
| 63 |
-
return f"Could not parse PDF: {e}"
|
|
|
|
|
|
|
| 64 |
if ext in ("mp3", "wav", "m4a", "flac", "ogg") or "audio" in content_type:
|
| 65 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
if ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp") or "image" in content_type:
|
| 67 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
try:
|
| 69 |
-
return resp.content.decode("utf-8")[:
|
| 70 |
except Exception:
|
| 71 |
-
return f"Binary file ({filename}) β cannot extract text."
|
| 72 |
except Exception as e:
|
| 73 |
return f"Error downloading file for task {task_id}: {e}"
|
| 74 |
|
|
@@ -77,11 +98,12 @@ def download_task_file(task_id: str) -> str:
|
|
| 77 |
def calculate(expression: str) -> str:
|
| 78 |
"""
|
| 79 |
Safely evaluates a mathematical expression and returns the result.
|
| 80 |
-
Use this for
|
|
|
|
| 81 |
|
| 82 |
Args:
|
| 83 |
-
expression: A valid Python math expression
|
| 84 |
-
Examples: "2 ** 10", "round(100 * 1.07 ** 3, 2)"
|
| 85 |
|
| 86 |
Returns:
|
| 87 |
The numeric result as a string, or an error message.
|
|
@@ -91,17 +113,71 @@ def calculate(expression: str) -> str:
|
|
| 91 |
allowed = {k: v for k, v in _math.__dict__.items() if not k.startswith("_")}
|
| 92 |
allowed["round"] = round
|
| 93 |
allowed["abs"] = abs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
result = eval(expression, {"__builtins__": {}}, allowed)
|
| 95 |
return str(result)
|
| 96 |
except Exception as e:
|
| 97 |
return f"Calculation error: {e}"
|
| 98 |
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
class BasicAgent:
|
| 101 |
def __init__(self):
|
| 102 |
-
# HF_TOKEN is automatically available in HF Spaces when the space owner is logged in.
|
| 103 |
-
# Passing it explicitly ensures the InferenceClient can authenticate.
|
| 104 |
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
|
|
|
|
| 105 |
|
| 106 |
self.agent = CodeAgent(
|
| 107 |
tools=[
|
|
@@ -109,44 +185,71 @@ class BasicAgent:
|
|
| 109 |
VisitWebpageTool(),
|
| 110 |
download_task_file,
|
| 111 |
calculate,
|
|
|
|
| 112 |
],
|
| 113 |
model=InferenceClientModel(
|
| 114 |
model_id="Qwen/Qwen2.5-72B-Instruct",
|
| 115 |
token=hf_token,
|
| 116 |
),
|
| 117 |
-
max_steps=
|
| 118 |
)
|
| 119 |
print("BasicAgent initialized.")
|
| 120 |
|
| 121 |
def __call__(self, question: str) -> str:
|
| 122 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
Question:
|
| 136 |
-
{question}
|
|
|
|
|
|
|
| 137 |
|
| 138 |
try:
|
| 139 |
response = self.agent.run(prompt)
|
| 140 |
final_answer = str(response).strip()
|
| 141 |
-
# Strip any accidental prefix
|
| 142 |
-
for prefix in ["FINAL ANSWER:", "FINAL ANSWER", "Answer:", "The answer is:"]:
|
| 143 |
if final_answer.upper().startswith(prefix.upper()):
|
| 144 |
final_answer = final_answer[len(prefix):].strip()
|
| 145 |
print(f"Agent returning answer: {final_answer}")
|
| 146 |
return final_answer
|
| 147 |
except Exception as e:
|
| 148 |
-
|
| 149 |
-
|
|
|
|
| 150 |
|
| 151 |
|
| 152 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
@@ -210,7 +313,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 210 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 211 |
continue
|
| 212 |
try:
|
| 213 |
-
# Prepend task_id so agent can use it for file downloads
|
| 214 |
augmented_question = f"[task_id: {task_id}]\n{question_text}"
|
| 215 |
submitted_answer = agent(augmented_question)
|
| 216 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
|
|
|
| 11 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 12 |
|
| 13 |
import re
|
| 14 |
+
import traceback
|
| 15 |
from smolagents import CodeAgent, InferenceClientModel, tool, VisitWebpageTool, DuckDuckGoSearchTool
|
| 16 |
|
| 17 |
|
|
|
|
| 19 |
def download_task_file(task_id: str) -> str:
|
| 20 |
"""
|
| 21 |
Downloads the file attached to a GAIA task and returns its text content.
|
| 22 |
+
ALWAYS call this first if the question mentions any file, attachment, spreadsheet,
|
| 23 |
+
audio, PDF, image, or code file.
|
| 24 |
|
| 25 |
Args:
|
| 26 |
+
task_id: The task_id string from [task_id: ...] at the top of the question.
|
| 27 |
|
| 28 |
Returns:
|
| 29 |
The text content of the file, or a descriptive note if unreadable.
|
|
|
|
| 41 |
filename = disposition.split("filename=")[-1].strip().strip('"')
|
| 42 |
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
| 43 |
|
| 44 |
+
# Plain text / code / CSV
|
| 45 |
+
if "text" in content_type or ext in ("txt", "csv", "tsv", "md", "py", "js", "json", "xml", "yaml", "yml", "html"):
|
| 46 |
+
return f"[File: {filename}]\n" + resp.text[:8000]
|
| 47 |
+
|
| 48 |
+
# Excel
|
| 49 |
if ext in ("xlsx", "xls"):
|
| 50 |
try:
|
| 51 |
import io, openpyxl
|
|
|
|
| 56 |
lines.append(f"=== Sheet: {sheet} ===")
|
| 57 |
for row in ws.iter_rows(values_only=True):
|
| 58 |
lines.append("\t".join(str(c) if c is not None else "" for c in row))
|
| 59 |
+
return f"[File: {filename}]\n" + "\n".join(lines)[:8000]
|
| 60 |
except Exception as e:
|
| 61 |
+
return f"Could not parse Excel file {filename}: {e}"
|
| 62 |
+
|
| 63 |
+
# PDF
|
| 64 |
if "pdf" in content_type or ext == "pdf":
|
| 65 |
try:
|
| 66 |
import io, pdfminer.high_level
|
| 67 |
text = pdfminer.high_level.extract_text(io.BytesIO(resp.content))
|
| 68 |
+
return f"[File: {filename}]\n" + (text or "No extractable text in PDF.")[:8000]
|
| 69 |
except Exception as e:
|
| 70 |
+
return f"Could not parse PDF {filename}: {e}"
|
| 71 |
+
|
| 72 |
+
# Audio β return filename so agent knows what to search for
|
| 73 |
if ext in ("mp3", "wav", "m4a", "flac", "ogg") or "audio" in content_type:
|
| 74 |
+
return (
|
| 75 |
+
f"[Audio file: {filename}]\n"
|
| 76 |
+
"This is an audio file that cannot be transcribed directly.\n"
|
| 77 |
+
"Search the web for the content described in the question to find the answer."
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# Image
|
| 81 |
if ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp") or "image" in content_type:
|
| 82 |
+
return (
|
| 83 |
+
f"[Image file: {filename}]\n"
|
| 84 |
+
"This is an image file. Analyze the question carefully and search the web "
|
| 85 |
+
"for any relevant context to answer without seeing the image."
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Fallback
|
| 89 |
try:
|
| 90 |
+
return f"[File: {filename}]\n" + resp.content.decode("utf-8")[:8000]
|
| 91 |
except Exception:
|
| 92 |
+
return f"Binary file ({filename}, type={content_type}) β cannot extract text."
|
| 93 |
except Exception as e:
|
| 94 |
return f"Error downloading file for task {task_id}: {e}"
|
| 95 |
|
|
|
|
| 98 |
def calculate(expression: str) -> str:
|
| 99 |
"""
|
| 100 |
Safely evaluates a mathematical expression and returns the result.
|
| 101 |
+
Use this for ANY arithmetic, counting, percentages, or numeric calculation.
|
| 102 |
+
Always prefer this over mental math.
|
| 103 |
|
| 104 |
Args:
|
| 105 |
+
expression: A valid Python math expression.
|
| 106 |
+
Examples: "2 ** 10", "round(100 * 1.07 ** 3, 2)", "sum([1,2,3,4,5])"
|
| 107 |
|
| 108 |
Returns:
|
| 109 |
The numeric result as a string, or an error message.
|
|
|
|
| 113 |
allowed = {k: v for k, v in _math.__dict__.items() if not k.startswith("_")}
|
| 114 |
allowed["round"] = round
|
| 115 |
allowed["abs"] = abs
|
| 116 |
+
allowed["sum"] = sum
|
| 117 |
+
allowed["min"] = min
|
| 118 |
+
allowed["max"] = max
|
| 119 |
+
allowed["len"] = len
|
| 120 |
+
allowed["sorted"] = sorted
|
| 121 |
+
allowed["list"] = list
|
| 122 |
+
allowed["range"] = range
|
| 123 |
result = eval(expression, {"__builtins__": {}}, allowed)
|
| 124 |
return str(result)
|
| 125 |
except Exception as e:
|
| 126 |
return f"Calculation error: {e}"
|
| 127 |
|
| 128 |
|
| 129 |
+
@tool
|
| 130 |
+
def search_wikipedia(query: str) -> str:
|
| 131 |
+
"""
|
| 132 |
+
Searches Wikipedia directly and returns the page summary.
|
| 133 |
+
Use this for factual questions about people, places, history, science, etc.
|
| 134 |
+
Much more reliable than general web search for encyclopedia-style facts.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
query: The Wikipedia article title or search query.
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
The Wikipedia page text (first 6000 chars), or an error message.
|
| 141 |
+
"""
|
| 142 |
+
try:
|
| 143 |
+
# Try direct article fetch first
|
| 144 |
+
search_url = "https://en.wikipedia.org/w/api.php"
|
| 145 |
+
params = {
|
| 146 |
+
"action": "query",
|
| 147 |
+
"list": "search",
|
| 148 |
+
"srsearch": query,
|
| 149 |
+
"format": "json",
|
| 150 |
+
"srlimit": 1,
|
| 151 |
+
}
|
| 152 |
+
resp = requests.get(search_url, params=params, timeout=10)
|
| 153 |
+
results = resp.json().get("query", {}).get("search", [])
|
| 154 |
+
if not results:
|
| 155 |
+
return f"No Wikipedia results for: {query}"
|
| 156 |
+
|
| 157 |
+
title = results[0]["title"]
|
| 158 |
+
# Fetch page content
|
| 159 |
+
page_url = "https://en.wikipedia.org/w/api.php"
|
| 160 |
+
page_params = {
|
| 161 |
+
"action": "query",
|
| 162 |
+
"titles": title,
|
| 163 |
+
"prop": "extracts",
|
| 164 |
+
"exintro": False,
|
| 165 |
+
"explaintext": True,
|
| 166 |
+
"format": "json",
|
| 167 |
+
}
|
| 168 |
+
page_resp = requests.get(page_url, params=page_params, timeout=10)
|
| 169 |
+
pages = page_resp.json().get("query", {}).get("pages", {})
|
| 170 |
+
page = next(iter(pages.values()))
|
| 171 |
+
text = page.get("extract", "")
|
| 172 |
+
return f"=== Wikipedia: {title} ===\n{text[:6000]}"
|
| 173 |
+
except Exception as e:
|
| 174 |
+
return f"Wikipedia search error: {e}"
|
| 175 |
+
|
| 176 |
+
|
| 177 |
class BasicAgent:
|
| 178 |
def __init__(self):
|
|
|
|
|
|
|
| 179 |
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
|
| 180 |
+
print(f"HF_TOKEN present: {bool(hf_token)}")
|
| 181 |
|
| 182 |
self.agent = CodeAgent(
|
| 183 |
tools=[
|
|
|
|
| 185 |
VisitWebpageTool(),
|
| 186 |
download_task_file,
|
| 187 |
calculate,
|
| 188 |
+
search_wikipedia,
|
| 189 |
],
|
| 190 |
model=InferenceClientModel(
|
| 191 |
model_id="Qwen/Qwen2.5-72B-Instruct",
|
| 192 |
token=hf_token,
|
| 193 |
),
|
| 194 |
+
max_steps=15,
|
| 195 |
)
|
| 196 |
print("BasicAgent initialized.")
|
| 197 |
|
| 198 |
def __call__(self, question: str) -> str:
|
| 199 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 200 |
|
| 201 |
+
# Extract task_id from the prepended tag
|
| 202 |
+
task_id = ""
|
| 203 |
+
task_id_match = re.match(r"\[task_id:\s*([^\]]+)\]", question)
|
| 204 |
+
if task_id_match:
|
| 205 |
+
task_id = task_id_match.group(1).strip()
|
| 206 |
+
|
| 207 |
+
prompt = f"""You are an expert GAIA benchmark solving agent. Your goal is to answer correctly.
|
| 208 |
+
|
| 209 |
+
The question has a task_id: {task_id}
|
| 210 |
+
|
| 211 |
+
STRICT OUTPUT RULES:
|
| 212 |
+
- Your final output must be ONLY the bare answer itself.
|
| 213 |
+
- No explanation. No "The answer is". No "FINAL ANSWER". No markdown.
|
| 214 |
+
- Just the raw answer: a number, a name, a date, a word, or comma-separated values.
|
| 215 |
+
- Never output an empty string β always give your best answer.
|
| 216 |
+
|
| 217 |
+
STRATEGY β follow these steps:
|
| 218 |
+
1. Read the question carefully.
|
| 219 |
+
2. If it mentions a file, spreadsheet, audio, image, or attachment β call download_task_file("{task_id}") FIRST.
|
| 220 |
+
3. For factual/encyclopedia questions β call search_wikipedia first, then DuckDuckGo if needed.
|
| 221 |
+
4. For web research β search DuckDuckGo, then visit the most relevant URLs with VisitWebpageTool.
|
| 222 |
+
5. For math/counting β use the calculate tool.
|
| 223 |
+
6. For YouTube video questions β search for the video title + transcript or description on the web.
|
| 224 |
+
7. For reversed/encoded text β decode it yourself before answering.
|
| 225 |
+
8. Think step by step, then output ONLY the final answer.
|
| 226 |
+
|
| 227 |
+
COMMON ANSWER FORMATS (match exactly):
|
| 228 |
+
- Counts: just the integer e.g. "3"
|
| 229 |
+
- Names: just the name e.g. "Marie Curie"
|
| 230 |
+
- Yes/No: just "Yes" or "No"
|
| 231 |
+
- Lists: comma-separated e.g. "apple, banana, cherry"
|
| 232 |
+
- Currency: with symbol and decimals e.g. "$12345.67"
|
| 233 |
+
- Algebraic notation: e.g. "Qd5"
|
| 234 |
|
| 235 |
Question:
|
| 236 |
+
{question}
|
| 237 |
+
|
| 238 |
+
Remember: output ONLY the final answer. Nothing else."""
|
| 239 |
|
| 240 |
try:
|
| 241 |
response = self.agent.run(prompt)
|
| 242 |
final_answer = str(response).strip()
|
| 243 |
+
# Strip any accidental prefix the model adds
|
| 244 |
+
for prefix in ["FINAL ANSWER:", "FINAL ANSWER", "Answer:", "The answer is:", "Result:"]:
|
| 245 |
if final_answer.upper().startswith(prefix.upper()):
|
| 246 |
final_answer = final_answer[len(prefix):].strip()
|
| 247 |
print(f"Agent returning answer: {final_answer}")
|
| 248 |
return final_answer
|
| 249 |
except Exception as e:
|
| 250 |
+
err_msg = f"ERROR: {type(e).__name__}: {str(e)[:200]}"
|
| 251 |
+
print(f"Agent error: {traceback.format_exc()}")
|
| 252 |
+
return err_msg
|
| 253 |
|
| 254 |
|
| 255 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
|
|
| 313 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 314 |
continue
|
| 315 |
try:
|
|
|
|
| 316 |
augmented_question = f"[task_id: {task_id}]\n{question_text}"
|
| 317 |
submitted_answer = agent(augmented_question)
|
| 318 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|