avi080704 commited on
Commit
3c8ec60
Β·
verified Β·
1 Parent(s): e56b672

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -85
app.py CHANGED
@@ -19,8 +19,8 @@ from smolagents import CodeAgent, InferenceClientModel, tool, VisitWebpageTool,
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.
@@ -41,11 +41,9 @@ def download_task_file(task_id: str) -> str:
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
@@ -60,7 +58,6 @@ def download_task_file(task_id: str) -> str:
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
@@ -69,23 +66,20 @@ def download_task_file(task_id: str) -> str:
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:
@@ -99,11 +93,10 @@ 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.
@@ -111,15 +104,9 @@ def calculate(expression: str) -> str:
111
  try:
112
  import math as _math
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:
@@ -129,43 +116,27 @@ def calculate(expression: str) -> str:
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", "")
@@ -174,73 +145,103 @@ def search_wikipedia(query: str) -> str:
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=[
184
- DuckDuckGoSearchTool(),
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()
 
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,
23
+ spreadsheet, 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.
 
41
  filename = disposition.split("filename=")[-1].strip().strip('"')
42
  ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
43
 
 
44
  if "text" in content_type or ext in ("txt", "csv", "tsv", "md", "py", "js", "json", "xml", "yaml", "yml", "html"):
45
  return f"[File: {filename}]\n" + resp.text[:8000]
46
 
 
47
  if ext in ("xlsx", "xls"):
48
  try:
49
  import io, openpyxl
 
58
  except Exception as e:
59
  return f"Could not parse Excel file {filename}: {e}"
60
 
 
61
  if "pdf" in content_type or ext == "pdf":
62
  try:
63
  import io, pdfminer.high_level
 
66
  except Exception as e:
67
  return f"Could not parse PDF {filename}: {e}"
68
 
 
69
  if ext in ("mp3", "wav", "m4a", "flac", "ogg") or "audio" in content_type:
70
  return (
71
  f"[Audio file: {filename}]\n"
72
+ "This is an audio file β€” transcription not available. "
73
+ "Search the web for the answer based on the question context."
74
  )
75
 
 
76
  if ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp") or "image" in content_type:
77
  return (
78
  f"[Image file: {filename}]\n"
79
+ "This is an image file β€” visual reading not available. "
80
+ "Search the web for the answer based on the question context."
81
  )
82
 
 
83
  try:
84
  return f"[File: {filename}]\n" + resp.content.decode("utf-8")[:8000]
85
  except Exception:
 
93
  """
94
  Safely evaluates a mathematical expression and returns the result.
95
  Use this for ANY arithmetic, counting, percentages, or numeric calculation.
 
96
 
97
  Args:
98
  expression: A valid Python math expression.
99
+ Examples: "2 ** 10", "round(100 * 1.07 ** 3, 2)", "sum([1,2,3])"
100
 
101
  Returns:
102
  The numeric result as a string, or an error message.
 
104
  try:
105
  import math as _math
106
  allowed = {k: v for k, v in _math.__dict__.items() if not k.startswith("_")}
107
+ allowed.update({"round": round, "abs": abs, "sum": sum, "min": min,
108
+ "max": max, "len": len, "sorted": sorted,
109
+ "list": list, "range": range})
 
 
 
 
 
 
110
  result = eval(expression, {"__builtins__": {}}, allowed)
111
  return str(result)
112
  except Exception as e:
 
116
  @tool
117
  def search_wikipedia(query: str) -> str:
118
  """
119
+ Searches Wikipedia and returns the full page text.
120
+ Best for: people, places, history, science, albums, films, sports stats.
 
121
 
122
  Args:
123
+ query: The Wikipedia article title or search phrase.
124
 
125
  Returns:
126
+ Wikipedia page text (up to 6000 chars).
127
  """
128
  try:
 
129
  search_url = "https://en.wikipedia.org/w/api.php"
130
+ params = {"action": "query", "list": "search", "srsearch": query,
131
+ "format": "json", "srlimit": 1}
 
 
 
 
 
132
  resp = requests.get(search_url, params=params, timeout=10)
133
  results = resp.json().get("query", {}).get("search", [])
134
  if not results:
135
  return f"No Wikipedia results for: {query}"
 
136
  title = results[0]["title"]
137
+ page_params = {"action": "query", "titles": title, "prop": "extracts",
138
+ "exintro": False, "explaintext": True, "format": "json"}
139
+ page_resp = requests.get(search_url, params=page_params, timeout=10)
 
 
 
 
 
 
 
 
140
  pages = page_resp.json().get("query", {}).get("pages", {})
141
  page = next(iter(pages.values()))
142
  text = page.get("extract", "")
 
145
  return f"Wikipedia search error: {e}"
146
 
147
 
148
+ def _make_agent(model_id: str, hf_token: str) -> CodeAgent:
149
+ return CodeAgent(
150
+ tools=[
151
+ DuckDuckGoSearchTool(),
152
+ VisitWebpageTool(),
153
+ download_task_file,
154
+ calculate,
155
+ search_wikipedia,
156
+ ],
157
+ model=InferenceClientModel(model_id=model_id, token=hf_token),
158
+ max_steps=15,
159
+ )
160
+
161
+
162
+ # Models in priority order β€” free tier first, bigger/better after
163
+ CANDIDATE_MODELS = [
164
+ "Qwen/Qwen2.5-7B-Instruct",
165
+ "Qwen/Qwen2.5-72B-Instruct", # Pro only, kept as fallback
166
+ "mistralai/Mistral-7B-Instruct-v0.3",
167
+ "HuggingFaceTB/SmolLM2-1.7B-Instruct",
168
+ ]
169
+
170
+
171
  class BasicAgent:
172
  def __init__(self):
173
  hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
174
  print(f"HF_TOKEN present: {bool(hf_token)}")
175
 
176
+ # Pick the first model that responds without a payment error
177
+ self.agent = None
178
+ self.model_id = None
179
+ for model_id in CANDIDATE_MODELS:
180
+ try:
181
+ print(f"Trying model: {model_id}")
182
+ agent = _make_agent(model_id, hf_token)
183
+ # Quick smoke test
184
+ test = agent.run("Reply with just the number 42.")
185
+ print(f"βœ… Model OK: {model_id} β†’ {str(test)[:30]}")
186
+ self.agent = agent
187
+ self.model_id = model_id
188
+ break
189
+ except Exception as e:
190
+ msg = str(e)
191
+ if "402" in msg or "Payment" in msg:
192
+ print(f"β›” {model_id} requires payment, trying next...")
193
+ else:
194
+ print(f"⚠️ {model_id} failed: {msg[:80]}, trying next...")
195
+
196
+ if self.agent is None:
197
+ raise RuntimeError("No working model found. Check HF_TOKEN and account tier.")
198
+
199
+ print(f"BasicAgent initialized with model: {self.model_id}")
200
 
201
  def __call__(self, question: str) -> str:
202
  print(f"Agent received question (first 50 chars): {question[:50]}...")
203
 
 
204
  task_id = ""
205
  task_id_match = re.match(r"\[task_id:\s*([^\]]+)\]", question)
206
  if task_id_match:
207
  task_id = task_id_match.group(1).strip()
208
 
209
+ prompt = f"""You are an expert GAIA benchmark solving agent.
210
 
211
+ task_id: {task_id}
212
 
213
  STRICT OUTPUT RULES:
214
+ - Output ONLY the bare final answer. Nothing else.
215
  - No explanation. No "The answer is". No "FINAL ANSWER". No markdown.
216
  - Just the raw answer: a number, a name, a date, a word, or comma-separated values.
217
  - Never output an empty string β€” always give your best answer.
218
 
219
+ STRATEGY:
220
  1. Read the question carefully.
221
+ 2. If it mentions a file, spreadsheet, audio, image β†’ call download_task_file("{task_id}") FIRST.
222
+ 3. For encyclopedia/factual questions β†’ call search_wikipedia first.
223
+ 4. For web research β†’ DuckDuckGo search, then visit URLs with VisitWebpageTool.
224
+ 5. For math/counting β†’ use calculate tool.
225
+ 6. For YouTube videos β†’ search web for the video title + transcript/description.
226
+ 7. For reversed text β†’ decode it yourself before answering.
227
+ 8. Think carefully, then output ONLY the final answer.
228
+
229
+ ANSWER FORMAT EXAMPLES:
230
+ - Count β†’ "3"
231
+ - Name β†’ "Marie Curie"
232
+ - Yes/No β†’ "Yes"
233
+ - List β†’ "apple, banana, cherry"
234
+ - Currency β†’ "$12345.67"
235
+ - Chess move β†’ "Qd5"
236
 
237
  Question:
238
  {question}
239
 
240
+ Output ONLY the final answer:"""
241
 
242
  try:
243
  response = self.agent.run(prompt)
244
  final_answer = str(response).strip()
 
245
  for prefix in ["FINAL ANSWER:", "FINAL ANSWER", "Answer:", "The answer is:", "Result:"]:
246
  if final_answer.upper().startswith(prefix.upper()):
247
  final_answer = final_answer[len(prefix):].strip()