hawkdev commited on
Commit
ac299d5
·
1 Parent(s): c1ea04f

initial commit

Browse files
README.md CHANGED
@@ -1,13 +1,55 @@
1
  ---
2
- title: Gaia Unit4 Space
3
- emoji: 📊
4
  colorFrom: gray
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 6.9.0
8
  app_file: app.py
9
  pinned: false
10
- short_description: Final project for Agents Course
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: GAIA Unit 4 Agent
3
+ emoji: 🧭
4
  colorFrom: gray
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.44.0
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
  ---
12
 
13
+ # GAIA Unit 4 Hugging Face Agents Course (final assignment)
14
+
15
+ This folder is a **drop-in replacement** for the course Space
16
+ [`agents-course/Final_Assignment_Template`](https://huggingface.co/spaces/agents-course/Final_Assignment_Template).
17
+
18
+ ## One-time: create your Space
19
+
20
+ 1. On Hugging Face, **Duplicate** the template Space above (or create a new Gradio Space and copy these files into the repo root).
21
+ 2. In the Space **Settings → Repository secrets**, add:
22
+ - **`HF_TOKEN`**: a Hugging Face access token with **read** permission (for Inference API / serverless models).
23
+ 3. Optional **Variables** (or secrets) to tune models:
24
+ - `HF_INFERENCE_PROVIDER` — **omit by default** so the client uses **`auto`**: the first [inference provider](https://hf.co/settings/inference-providers) that supports your **chosen model** on the Hub. Do **not** set `hf-inference` unless that model lists it — many chat models (e.g. Qwen2.5-7B-Instruct) only support **together** / **featherless-ai**, and forcing `hf-inference` yields **404**. If the auto order hits a provider that returns **401** (e.g. Novita), reorder providers in HF settings or pin e.g. `HF_INFERENCE_PROVIDER=together`.
25
+ - `GAIA_TEXT_MODEL` — default `Qwen/Qwen2.5-7B-Instruct` (broad provider mapping via Together).
26
+ - `GAIA_ASR_MODEL` — default `openai/whisper-large-v3`
27
+ - `GAIA_VISION_MODEL` — default `meta-llama/Llama-3.2-11B-Vision-Instruct`
28
+ - `GAIA_API_URL` — default `https://agents-course-unit4-scoring.hf.space`
29
+ - `GAIA_USE_CACHE` — `1` (default) or `0` to disable `gaia_answers_cache.json`
30
+
31
+ Keep the Space **public** so `agent_code` (`…/tree/main`) verifies for the leaderboard.
32
+
33
+ ## Local dry-run (no submission)
34
+
35
+ ```bash
36
+ cd gaia_unit4_space
37
+ python -m venv .venv && source .venv/bin/activate
38
+ pip install -r requirements.txt
39
+ export HF_TOKEN=hf_...
40
+ python run_local_eval.py
41
+ ```
42
+
43
+ This fetches `/questions`, runs the agent, prints answers, and writes `local_eval_answers.json`. It does **not** call `/submit`.
44
+
45
+ ## What was fixed vs the stock template
46
+
47
+ - Downloads attachments when `file_name` is set (`GET /files/{task_id}`).
48
+ - Tool-using agent (web, Wikipedia, Python, Excel, ASR, vision, YouTube transcripts).
49
+ - Deterministic shortcuts for the reversed-English puzzle, Cayley-table commutativity, `.py` stdout, and `.xlsx` food-sales heuristic.
50
+ - Optional **Crypto** tab (BTC/USD demo only; not used for GAIA).
51
+
52
+ ## Leaderboard
53
+
54
+ Submit scores via the Gradio app after logging in. Student leaderboard:
55
+ [`agents-course/Students_leaderboard`](https://huggingface.co/spaces/agents-course/Students_leaderboard).
__pycache__/agent.cpython-312.pyc ADDED
Binary file (7.4 kB). View file
 
__pycache__/answer_normalize.cpython-312.pyc ADDED
Binary file (2.49 kB). View file
 
__pycache__/debug_ndjson.cpython-312.pyc ADDED
Binary file (1.53 kB). View file
 
__pycache__/inference_client_factory.cpython-312.pyc ADDED
Binary file (2.42 kB). View file
 
agent.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GAIA Unit 4 agent: tool-calling loop via Hugging Face Inference API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, Optional
7
+
8
+ from huggingface_hub import InferenceClient
9
+
10
+ from answer_normalize import normalize_answer
11
+ from inference_client_factory import inference_client_kwargs
12
+ from tools.registry import TOOL_DEFINITIONS, deterministic_attempt, dispatch_tool
13
+
14
+ SYSTEM_PROMPT = """You solve GAIA benchmark questions for the Hugging Face Agents Course.
15
+
16
+ Hard rules:
17
+ - Call tools as needed (search, Wikipedia, fetch URL, Python, audio, image, Excel).
18
+ - Your final assistant message must contain ONLY the answer text required by the question — no labels like "FINAL ANSWER", no markdown fences, no extra sentences.
19
+ - Match the question's format exactly (comma-separated, alphabetical order, IOC codes, algebraic notation, two-decimal USD, first name only, etc.).
20
+ - When a local attachment path is given, use the appropriate tool with that exact path.
21
+ - For English Wikipedia tasks, use wikipedia_* tools; cross-check with web_search if needed.
22
+ - For YouTube URLs in the question, try youtube_transcript first.
23
+ """
24
+
25
+
26
+ class GaiaAgent:
27
+ def __init__(
28
+ self,
29
+ *,
30
+ hf_token: Optional[str] = None,
31
+ text_model: Optional[str] = None,
32
+ max_iterations: int = 14,
33
+ ):
34
+ self.hf_token = (
35
+ hf_token
36
+ or os.environ.get("HF_TOKEN")
37
+ or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
38
+ )
39
+ self.text_model = text_model or os.environ.get(
40
+ "GAIA_TEXT_MODEL", "Qwen/Qwen2.5-7B-Instruct"
41
+ )
42
+ self.max_iterations = max_iterations
43
+ self._client: Optional[InferenceClient] = None
44
+
45
+ def _get_client(self) -> InferenceClient:
46
+ if self._client is None:
47
+ if not self.hf_token:
48
+ raise RuntimeError(
49
+ "HF_TOKEN or HUGGINGFACEHUB_API_TOKEN is required for GaiaAgent."
50
+ )
51
+ kw = inference_client_kwargs(self.hf_token)
52
+ self._client = InferenceClient(**kw)
53
+ return self._client
54
+
55
+ def __call__(
56
+ self,
57
+ question: str,
58
+ attachment_path: Optional[str] = None,
59
+ task_id: Optional[str] = None,
60
+ ) -> str:
61
+ det = deterministic_attempt(question, attachment_path)
62
+ if det is not None:
63
+ return normalize_answer(det)
64
+
65
+ if not self.hf_token:
66
+ return normalize_answer(
67
+ "Error: missing HF_TOKEN; cannot run LLM tools for this question."
68
+ )
69
+
70
+ user_text = _build_user_payload(question, attachment_path, task_id)
71
+ messages: list[dict[str, Any]] = [
72
+ {"role": "system", "content": SYSTEM_PROMPT},
73
+ {"role": "user", "content": user_text},
74
+ ]
75
+
76
+ client = self._get_client()
77
+ last_text = ""
78
+
79
+ for _ in range(self.max_iterations):
80
+ try:
81
+ completion = client.chat_completion(
82
+ messages=messages,
83
+ model=self.text_model,
84
+ tools=TOOL_DEFINITIONS,
85
+ tool_choice="auto",
86
+ max_tokens=1024,
87
+ temperature=0.15,
88
+ )
89
+ except Exception as e:
90
+ last_text = f"Inference error: {e}"
91
+ break
92
+
93
+ choice = completion.choices[0]
94
+ msg = choice.message
95
+ last_text = (msg.content or "").strip()
96
+
97
+ if msg.tool_calls:
98
+ messages.append(
99
+ {
100
+ "role": "assistant",
101
+ "content": msg.content if msg.content else None,
102
+ "tool_calls": [
103
+ {
104
+ "id": tc.id,
105
+ "type": "function",
106
+ "function": {
107
+ "name": tc.function.name,
108
+ "arguments": tc.function.arguments,
109
+ },
110
+ }
111
+ for tc in msg.tool_calls
112
+ ],
113
+ }
114
+ )
115
+ for tc in msg.tool_calls:
116
+ name = tc.function.name
117
+ args = tc.function.arguments or "{}"
118
+ result = dispatch_tool(name, args, hf_token=self.hf_token)
119
+ messages.append(
120
+ {
121
+ "role": "tool",
122
+ "tool_call_id": tc.id,
123
+ "content": result[:24_000],
124
+ }
125
+ )
126
+ continue
127
+
128
+ if last_text:
129
+ break
130
+
131
+ if choice.finish_reason == "length":
132
+ last_text = "Error: model hit max length without an answer."
133
+ break
134
+
135
+ return normalize_answer(last_text or "Error: empty response.")
136
+
137
+
138
+ def _build_user_payload(
139
+ question: str,
140
+ attachment_path: Optional[str],
141
+ task_id: Optional[str],
142
+ ) -> str:
143
+ parts = []
144
+ if task_id:
145
+ parts.append(f"task_id: {task_id}")
146
+ parts.append(f"Question:\n{question.strip()}")
147
+ if attachment_path:
148
+ parts.append(f"\nAttachment path (use with tools): {attachment_path}")
149
+ else:
150
+ parts.append("\nNo attachment.")
151
+ return "\n".join(parts)
answer_normalize.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Post-process model output for GAIA exact-match submission."""
2
+
3
+ import re
4
+ from typing import Any, Union
5
+
6
+
7
+ _FINAL_ANSWER_RE = re.compile(
8
+ r"^\s*(?:FINAL\s*ANSWER\s*[::]?\s*)",
9
+ re.IGNORECASE,
10
+ )
11
+
12
+
13
+ def normalize_answer(raw: Union[str, int, float, None]) -> Union[str, int, float]:
14
+ """
15
+ Strip wrappers and forbidden prefixes. Prefer returning a string for API compatibility.
16
+ """
17
+ if raw is None:
18
+ return ""
19
+ if isinstance(raw, (int, float)) and not isinstance(raw, bool):
20
+ return raw
21
+ text = str(raw).strip()
22
+ if not text:
23
+ return ""
24
+ text = _FINAL_ANSWER_RE.sub("", text, count=1).strip()
25
+ # Strip common wrappers (single line)
26
+ for prefix in ("The answer is", "Answer:", "ANSWER:", "```", "`"):
27
+ if text.lower().startswith(prefix.lower()):
28
+ text = text[len(prefix) :].strip()
29
+ if text.startswith('"') and text.endswith('"') and len(text) >= 2:
30
+ text = text[1:-1].strip()
31
+ if text.startswith("```"):
32
+ text = re.sub(r"^```\w*\s*", "", text)
33
+ text = re.sub(r"\s*```$", "", text).strip()
34
+ return text.strip()
35
+
36
+
37
+ def maybe_numeric(text: str) -> Union[str, int, float]:
38
+ """If the prompt expects a plain number, allow int/float submission."""
39
+ t = text.strip()
40
+ if re.fullmatch(r"-?\d+", t):
41
+ return int(t)
42
+ if re.fullmatch(r"-?\d+\.\d+", t):
43
+ return float(t)
44
+ return text
app.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+ import gradio as gr
7
+ import pandas as pd
8
+ import requests
9
+
10
+ from agent import GaiaAgent
11
+ from answer_normalize import normalize_answer
12
+
13
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
+ CACHE_FILENAME = "gaia_answers_cache.json"
15
+
16
+
17
+ def _cache_path() -> Path:
18
+ return Path(__file__).resolve().parent / CACHE_FILENAME
19
+
20
+
21
+ def _load_cache() -> dict:
22
+ p = _cache_path()
23
+ if not p.is_file():
24
+ return {}
25
+ try:
26
+ return json.loads(p.read_text(encoding="utf-8"))
27
+ except json.JSONDecodeError:
28
+ return {}
29
+
30
+
31
+ def _save_cache(cache: dict) -> None:
32
+ _cache_path().write_text(json.dumps(cache, indent=2), encoding="utf-8")
33
+
34
+
35
+ def _download_attachment(api_url: str, task_id: str, file_name: str) -> str | None:
36
+ """Save task attachment to a temp file; return path or None."""
37
+ if not file_name or not str(file_name).strip():
38
+ return None
39
+ url = f"{api_url}/files/{task_id}"
40
+ try:
41
+ r = requests.get(url, timeout=120)
42
+ except requests.RequestException:
43
+ return None
44
+ if r.status_code != 200:
45
+ return None
46
+ ctype = (r.headers.get("Content-Type") or "").lower()
47
+ if "application/json" in ctype:
48
+ try:
49
+ data = r.json()
50
+ if isinstance(data, dict) and data.get("detail"):
51
+ return None
52
+ except json.JSONDecodeError:
53
+ pass
54
+ suffix = Path(file_name).suffix or ""
55
+ fd, path = tempfile.mkstemp(suffix=suffix, prefix=f"gaia_{task_id[:8]}_")
56
+ try:
57
+ with os.fdopen(fd, "wb") as f:
58
+ f.write(r.content)
59
+ except OSError:
60
+ return None
61
+ return path
62
+
63
+
64
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
65
+ space_id = os.getenv("SPACE_ID")
66
+ use_cache = os.getenv("GAIA_USE_CACHE", "1").lower() in ("1", "true", "yes")
67
+
68
+ if profile:
69
+ username = f"{profile.username}"
70
+ print(f"User logged in: {username}")
71
+ else:
72
+ print("User not logged in.")
73
+ return "Please Login to Hugging Face with the button.", None
74
+
75
+ api_url = os.getenv("GAIA_API_URL", DEFAULT_API_URL)
76
+ questions_url = f"{api_url}/questions"
77
+ submit_url = f"{api_url}/submit"
78
+
79
+ try:
80
+ agent = GaiaAgent()
81
+ except Exception as e:
82
+ print(f"Error instantiating agent: {e}")
83
+ return f"Error initializing agent: {e}", None
84
+
85
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
86
+ print(agent_code)
87
+
88
+ print(f"Fetching questions from: {questions_url}")
89
+ try:
90
+ response = requests.get(questions_url, timeout=60)
91
+ response.raise_for_status()
92
+ questions_data = response.json()
93
+ if not questions_data:
94
+ return "Fetched questions list is empty or invalid format.", None
95
+ print(f"Fetched {len(questions_data)} questions.")
96
+ except requests.exceptions.RequestException as e:
97
+ return f"Error fetching questions: {e}", None
98
+ except json.JSONDecodeError as e:
99
+ return f"Error decoding server response for questions: {e}", None
100
+
101
+ cache = _load_cache() if use_cache else {}
102
+ results_log = []
103
+ answers_payload = []
104
+
105
+ print(f"Running agent on {len(questions_data)} questions...")
106
+ for item in questions_data:
107
+ task_id = item.get("task_id")
108
+ question_text = item.get("question")
109
+ file_name = item.get("file_name") or ""
110
+
111
+ if not task_id or question_text is None:
112
+ print(f"Skipping item with missing task_id or question: {item}")
113
+ continue
114
+
115
+ cache_key = str(task_id)
116
+ if use_cache and cache_key in cache:
117
+ submitted_answer = normalize_answer(cache[cache_key])
118
+ print(f"Cache hit for {task_id}")
119
+ else:
120
+ local_path: str | None = None
121
+ try:
122
+ if file_name and str(file_name).strip():
123
+ local_path = _download_attachment(api_url, str(task_id), str(file_name))
124
+ if local_path:
125
+ print(f"Downloaded attachment for {task_id} -> {local_path}")
126
+ submitted_answer = agent(
127
+ str(question_text),
128
+ attachment_path=local_path,
129
+ task_id=str(task_id),
130
+ )
131
+ submitted_answer = normalize_answer(submitted_answer)
132
+ if use_cache:
133
+ cache[cache_key] = (
134
+ submitted_answer
135
+ if isinstance(submitted_answer, str)
136
+ else str(submitted_answer)
137
+ )
138
+ _save_cache(cache)
139
+ except Exception as e:
140
+ print(f"Error running agent on task {task_id}: {e}")
141
+ submitted_answer = f"AGENT ERROR: {e}"
142
+ finally:
143
+ if local_path and Path(local_path).is_file():
144
+ try:
145
+ Path(local_path).unlink(missing_ok=True)
146
+ except OSError:
147
+ pass
148
+
149
+ answers_payload.append(
150
+ {
151
+ "task_id": task_id,
152
+ "submitted_answer": submitted_answer,
153
+ }
154
+ )
155
+ results_log.append(
156
+ {
157
+ "Task ID": task_id,
158
+ "Question": question_text,
159
+ "Submitted Answer": submitted_answer,
160
+ }
161
+ )
162
+
163
+ if not answers_payload:
164
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
165
+
166
+ submission_data = {
167
+ "username": username.strip(),
168
+ "agent_code": agent_code,
169
+ "answers": answers_payload,
170
+ }
171
+ status_update = (
172
+ f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
173
+ )
174
+ print(status_update)
175
+
176
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
177
+ try:
178
+ response = requests.post(submit_url, json=submission_data, timeout=600)
179
+ response.raise_for_status()
180
+ result_data = response.json()
181
+ final_status = (
182
+ f"Submission Successful!\n"
183
+ f"User: {result_data.get('username')}\n"
184
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
185
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
186
+ f"Message: {result_data.get('message', 'No message received.')}"
187
+ )
188
+ print("Submission successful.")
189
+ results_df = pd.DataFrame(results_log)
190
+ return final_status, results_df
191
+ except requests.exceptions.HTTPError as e:
192
+ error_detail = f"Server responded with status {e.response.status_code}."
193
+ try:
194
+ error_json = e.response.json()
195
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
196
+ except json.JSONDecodeError:
197
+ error_detail += f" Response: {e.response.text[:500]}"
198
+ status_message = f"Submission Failed: {error_detail}"
199
+ print(status_message)
200
+ return status_message, pd.DataFrame(results_log)
201
+ except requests.exceptions.Timeout:
202
+ status_message = "Submission Failed: The request timed out."
203
+ print(status_message)
204
+ return status_message, pd.DataFrame(results_log)
205
+ except requests.exceptions.RequestException as e:
206
+ status_message = f"Submission Failed: Network error - {e}"
207
+ print(status_message)
208
+ return status_message, pd.DataFrame(results_log)
209
+ except Exception as e:
210
+ status_message = f"An unexpected error occurred during submission: {e}"
211
+ print(status_message)
212
+ return status_message, pd.DataFrame(results_log)
213
+
214
+
215
+ def crypto_btc_price() -> str:
216
+ """Optional demo: live BTC/USD (not used for GAIA scoring)."""
217
+ try:
218
+ r = requests.get(
219
+ "https://api.coingecko.com/api/v3/simple/price",
220
+ params={"ids": "bitcoin", "vs_currencies": "usd"},
221
+ timeout=20,
222
+ )
223
+ r.raise_for_status()
224
+ data = r.json()
225
+ usd = data.get("bitcoin", {}).get("usd")
226
+ return f"Bitcoin (BTC) ~ ${usd:,.2f} USD (CoinGecko public API)."
227
+ except Exception as e:
228
+ return f"Could not fetch price: {e}"
229
+
230
+
231
+ with gr.Blocks() as demo:
232
+ gr.Markdown("# GAIA Unit 4 — Agent Evaluation Runner")
233
+ gr.Markdown(
234
+ """
235
+ **Instructions**
236
+
237
+ 1. Duplicate this Space from the course template (or push this repo) and set **Secrets**: `HF_TOKEN` (read access to Inference).
238
+ 2. Optional env vars: `GAIA_TEXT_MODEL`, `GAIA_ASR_MODEL`, `GAIA_VISION_MODEL`, `GAIA_API_URL`, `GAIA_USE_CACHE` (default `1`).
239
+ 3. Log in with Hugging Face below (username is used for the leaderboard).
240
+ 4. Run **Evaluate & Submit** to answer all questions and post scores.
241
+
242
+ Attachment tasks download `GET /files/{task_id}` automatically when `file_name` is set.
243
+
244
+ ---
245
+ **Crypto demo (optional):** unrelated to GAIA; quick BTC spot check.
246
+ """
247
+ )
248
+
249
+ gr.LoginButton()
250
+
251
+ with gr.Tab("GAIA evaluation"):
252
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
253
+ status_output = gr.Textbox(
254
+ label="Run Status / Submission Result", lines=6, interactive=False
255
+ )
256
+ results_table = gr.DataFrame(
257
+ label="Questions and Agent Answers", wrap=True
258
+ )
259
+ run_button.click(
260
+ fn=run_and_submit_all,
261
+ outputs=[status_output, results_table],
262
+ )
263
+
264
+ with gr.Tab("Crypto intelligence (demo)"):
265
+ gr.Markdown(
266
+ "This tab does not affect GAIA scores. It demonstrates a simple public market data fetch."
267
+ )
268
+ cp_btn = gr.Button("Fetch BTC / USD")
269
+ cp_out = gr.Textbox(label="Output", interactive=False)
270
+ cp_btn.click(fn=crypto_btc_price, outputs=cp_out)
271
+
272
+ if __name__ == "__main__":
273
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
274
+ space_host_startup = os.getenv("SPACE_HOST")
275
+ space_id_startup = os.getenv("SPACE_ID")
276
+
277
+ if space_host_startup:
278
+ print(f"SPACE_HOST found: {space_host_startup}")
279
+ else:
280
+ print("SPACE_HOST not set (local run?).")
281
+
282
+ if space_id_startup:
283
+ print(f"SPACE_ID found: {space_id_startup}")
284
+ print(f"Repo tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
285
+ else:
286
+ print("SPACE_ID not set (local run?).")
287
+
288
+ print("-" * 62 + "\n")
289
+ demo.launch(debug=True, share=False)
inference_client_factory.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build InferenceClient with a provider that accepts the user's HF token."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ from huggingface_hub import InferenceClient
8
+
9
+
10
+ def inference_client_kwargs(token: str) -> dict:
11
+ """
12
+ Default: **no** ``provider`` → the library uses ``auto``: first provider for this
13
+ model per your https://hf.co/settings/inference-providers order.
14
+
15
+ Forcing ``hf-inference`` breaks many chat models (e.g. Qwen2.5-7B-Instruct is only on
16
+ together / featherless-ai — the router then returns **404** for …/hf-inference/models/…).
17
+
18
+ Set ``HF_INFERENCE_PROVIDER`` to pin one provider (e.g. ``together``, ``sambanova``)
19
+ or ``auto`` explicitly. Use ``hf-inference`` only for models that actually list it.
20
+ """
21
+ raw = os.environ.get("HF_INFERENCE_PROVIDER")
22
+ if raw is None:
23
+ return {"token": token}
24
+ r = raw.strip().lower()
25
+ if r in ("", "auto"):
26
+ return {"token": token}
27
+ return {"token": token, "provider": r}
28
+
29
+
30
+ def make_inference_client(token: str) -> InferenceClient:
31
+ return InferenceClient(**inference_client_kwargs(token))
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ requests>=2.31.0
3
+ pandas>=2.0.0
4
+ openpyxl>=3.1.0
5
+ beautifulsoup4>=4.12.0
6
+ lxml>=5.0.0
7
+ duckduckgo-search>=6.0.0
8
+ wikipedia>=1.4.0
9
+ huggingface_hub>=0.26.0
10
+ youtube-transcript-api>=0.6.0
11
+ Pillow>=10.0.0
run_local_eval.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fetch GAIA course questions, run GaiaAgent, save JSON — does not submit."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import sys
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ import requests
14
+
15
+ ROOT = Path(__file__).resolve().parent
16
+ if str(ROOT) not in sys.path:
17
+ sys.path.insert(0, str(ROOT))
18
+
19
+ from agent import GaiaAgent # noqa: E402
20
+ from answer_normalize import normalize_answer # noqa: E402
21
+
22
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
23
+
24
+
25
+ def download_file(api_url: str, task_id: str, file_name: str) -> str | None:
26
+ if not file_name or not str(file_name).strip():
27
+ return None
28
+ url = f"{api_url}/files/{task_id}"
29
+ r = requests.get(url, timeout=120)
30
+ if r.status_code != 200:
31
+ return None
32
+ ctype = (r.headers.get("Content-Type") or "").lower()
33
+ if "application/json" in ctype:
34
+ try:
35
+ data = r.json()
36
+ if isinstance(data, dict) and data.get("detail"):
37
+ return None
38
+ except json.JSONDecodeError:
39
+ pass
40
+ suffix = Path(file_name).suffix or ""
41
+ fd, path = tempfile.mkstemp(suffix=suffix, prefix=f"gaia_{task_id[:8]}_")
42
+ with os.fdopen(fd, "wb") as f:
43
+ f.write(r.content)
44
+ return path
45
+
46
+
47
+ def main() -> None:
48
+ parser = argparse.ArgumentParser()
49
+ parser.add_argument(
50
+ "--api-url",
51
+ default=os.environ.get("GAIA_API_URL", DEFAULT_API_URL),
52
+ )
53
+ parser.add_argument(
54
+ "-o",
55
+ "--output",
56
+ default=str(ROOT / "local_eval_answers.json"),
57
+ help="Write answers JSON here",
58
+ )
59
+ args = parser.parse_args()
60
+
61
+ q_url = f"{args.api_url.rstrip('/')}/questions"
62
+ print(f"GET {q_url}")
63
+ r = requests.get(q_url, timeout=60)
64
+ r.raise_for_status()
65
+ items = r.json()
66
+ print(f"{len(items)} questions")
67
+
68
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
69
+ agent = GaiaAgent(hf_token=token) if token else None
70
+
71
+ out: list[dict] = []
72
+ for item in items:
73
+ tid = item.get("task_id")
74
+ q = item.get("question")
75
+ fn = item.get("file_name") or ""
76
+ if not tid or q is None:
77
+ continue
78
+ local = None
79
+ try:
80
+ if fn and str(fn).strip():
81
+ local = download_file(args.api_url, str(tid), str(fn))
82
+ if agent is not None:
83
+ ans = agent(str(q), attachment_path=local, task_id=str(tid))
84
+ else:
85
+ from tools.registry import deterministic_attempt
86
+
87
+ d = deterministic_attempt(str(q), local)
88
+ ans = d if d is not None else "NO_HF_TOKEN"
89
+ finally:
90
+ if local and Path(local).is_file():
91
+ Path(local).unlink(missing_ok=True)
92
+
93
+ if isinstance(ans, (int, float)) and not isinstance(ans, bool):
94
+ sub = ans
95
+ else:
96
+ sub = normalize_answer(ans)
97
+ out.append(
98
+ {
99
+ "task_id": tid,
100
+ "question": q,
101
+ "submitted_answer": sub,
102
+ }
103
+ )
104
+ print(f"--- {tid[:8]}… -> {out[-1]['submitted_answer']!r}")
105
+
106
+ Path(args.output).write_text(json.dumps(out, indent=2), encoding="utf-8")
107
+ print(f"Wrote {args.output}")
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
tools/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Tool implementations for the GAIA agent."""
2
+
3
+ from .registry import TOOL_DEFINITIONS, dispatch_tool
4
+
5
+ __all__ = ["TOOL_DEFINITIONS", "dispatch_tool"]
tools/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (348 Bytes). View file
 
tools/__pycache__/code_tools.cpython-312.pyc ADDED
Binary file (5.27 kB). View file
 
tools/__pycache__/excel_tools.cpython-312.pyc ADDED
Binary file (4.13 kB). View file
 
tools/__pycache__/media_tools.cpython-312.pyc ADDED
Binary file (4.66 kB). View file
 
tools/__pycache__/registry.cpython-312.pyc ADDED
Binary file (5.69 kB). View file
 
tools/__pycache__/web_tools.cpython-312.pyc ADDED
Binary file (5.57 kB). View file
 
tools/__pycache__/wiki_tools.cpython-312.pyc ADDED
Binary file (2.26 kB). View file
 
tools/code_tools.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ from typing import Optional
4
+
5
+
6
+ def run_python_snippet(code: str, timeout_sec: int = 45) -> str:
7
+ """Execute Python in a subprocess (no network). For short derived calculations."""
8
+ if not code.strip():
9
+ return "Error: empty code."
10
+ try:
11
+ proc = subprocess.run(
12
+ [sys.executable, "-c", code],
13
+ capture_output=True,
14
+ text=True,
15
+ timeout=timeout_sec,
16
+ env={**__import__("os").environ, "PYTHONHASHSEED": "0"},
17
+ )
18
+ except subprocess.TimeoutExpired:
19
+ return "Error: execution timed out."
20
+ out = (proc.stdout or "").strip()
21
+ err = (proc.stderr or "").strip()
22
+ if proc.returncode != 0:
23
+ return f"Exit {proc.returncode}. stderr: {err[:2000]}"
24
+ if err:
25
+ out = f"{out}\n(stderr: {err[:1500]})" if out else err
26
+ return out[:30_000] if out else "(no stdout)"
27
+
28
+
29
+ def run_python_file(file_path: str, timeout_sec: int = 60) -> str:
30
+ """Run an attached .py file and capture stdout."""
31
+ if not file_path.endswith(".py"):
32
+ return "Error: not a .py path."
33
+ try:
34
+ proc = subprocess.run(
35
+ [sys.executable, file_path],
36
+ capture_output=True,
37
+ text=True,
38
+ timeout=timeout_sec,
39
+ env={**__import__("os").environ, "PYTHONHASHSEED": "0"},
40
+ )
41
+ except subprocess.TimeoutExpired:
42
+ return "Error: execution timed out."
43
+ out = (proc.stdout or "").strip()
44
+ err = (proc.stderr or "").strip()
45
+ if proc.returncode != 0:
46
+ return f"Exit {proc.returncode}. stderr: {err[:2000]}"
47
+ return (out or err)[:30_000]
48
+
49
+
50
+ def solve_cayley_noncommutative_subset(question: str) -> Optional[str]:
51
+ """
52
+ Parse a Cayley table from the question (markdown) and return the sorted
53
+ comma-separated elements involved in any non-commuting pair.
54
+ """
55
+ if "* on the set S" not in question and "not commutative" not in question:
56
+ return None
57
+ lines = [ln.strip() for ln in question.splitlines() if ln.strip().startswith("|")]
58
+ if len(lines) < 3:
59
+ return None
60
+
61
+ def split_row(ln: str) -> list[str]:
62
+ parts = [p.strip() for p in ln.strip("|").split("|")]
63
+ return parts
64
+
65
+ header = split_row(lines[0])
66
+ if len(header) < 2 or header[0] != "*":
67
+ return None
68
+ cols = header[1:]
69
+ op: dict[tuple[str, str], str] = {}
70
+ for ln in lines[1:]:
71
+ cells = split_row(ln)
72
+ if len(cells) < 2:
73
+ continue
74
+ row_sym = cells[0]
75
+ for j, c in enumerate(cols):
76
+ if j + 1 >= len(cells):
77
+ break
78
+ op[(row_sym, c)] = cells[j + 1]
79
+ elems = cols
80
+ involved: set[str] = set()
81
+ for a in elems:
82
+ for b in elems:
83
+ ab = op.get((a, b))
84
+ ba = op.get((b, a))
85
+ if ab is None or ba is None:
86
+ continue
87
+ if ab != ba:
88
+ involved.add(a)
89
+ involved.add(b)
90
+ if not involved:
91
+ return None
92
+ return ", ".join(sorted(involved))
93
+
94
+
95
+ def reverse_english_puzzle_answer(question: str) -> Optional[str]:
96
+ """If the question is reversed English about 'left', return 'right'."""
97
+ q = question.strip()
98
+ if not q:
99
+ return None
100
+ rev = q[::-1]
101
+ if "opposite" in rev.lower() and '"left"' in rev and "answer" in rev.lower():
102
+ return "right"
103
+ return None
tools/excel_tools.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+ import pandas as pd
6
+
7
+
8
+ def excel_food_sales_total_usd(path: str) -> str:
9
+ """
10
+ Sum sales for food items excluding drinks from the GAIA-style fast-food workbook.
11
+ Heuristic: classify rows using a Category/Type/Menu column; exclude drink/beverage/soda.
12
+ """
13
+ p = Path(path)
14
+ if not p.exists():
15
+ return f"Error: file not found: {path}"
16
+ try:
17
+ xl = pd.ExcelFile(path)
18
+ except Exception as e:
19
+ return f"Error opening Excel: {e}"
20
+
21
+ total = 0.0
22
+ notes: list[str] = []
23
+
24
+ for sheet in xl.sheet_names:
25
+ try:
26
+ df = pd.read_excel(xl, sheet_name=sheet)
27
+ except Exception as e:
28
+ notes.append(f"{sheet}: read error {e}")
29
+ continue
30
+ if df.empty:
31
+ continue
32
+ cols_lower = {str(c).lower(): c for c in df.columns}
33
+
34
+ cat_col = None
35
+ for key in (
36
+ "category",
37
+ "type",
38
+ "menu category",
39
+ "item type",
40
+ "group",
41
+ ):
42
+ if key in cols_lower:
43
+ cat_col = cols_lower[key]
44
+ break
45
+
46
+ money_col = None
47
+ for c in df.columns:
48
+ cl = str(c).lower()
49
+ if any(
50
+ w in cl
51
+ for w in ("sales", "revenue", "total", "amount", "usd", "price")
52
+ ):
53
+ if df[c].dtype == object or pd.api.types.is_numeric_dtype(df[c]):
54
+ money_col = c
55
+ break
56
+ if money_col is None:
57
+ for c in df.columns:
58
+ if pd.api.types.is_numeric_dtype(df[c]):
59
+ money_col = c
60
+ break
61
+
62
+ if money_col is None:
63
+ notes.append(f"{sheet}: no numeric sales column found")
64
+ continue
65
+
66
+ for _, row in df.iterrows():
67
+ val = row[money_col]
68
+ if pd.isna(val):
69
+ continue
70
+ try:
71
+ amount = float(val)
72
+ except (TypeError, ValueError):
73
+ s = str(val).replace("$", "").replace(",", "").strip()
74
+ try:
75
+ amount = float(s)
76
+ except ValueError:
77
+ continue
78
+
79
+ if cat_col is not None:
80
+ raw = row[cat_col]
81
+ label = str(raw).lower() if pd.notna(raw) else ""
82
+ if any(
83
+ d in label
84
+ for d in (
85
+ "drink",
86
+ "beverage",
87
+ "soda",
88
+ "coffee",
89
+ "tea",
90
+ "juice",
91
+ "water",
92
+ "shake",
93
+ "smoothie",
94
+ )
95
+ ):
96
+ continue
97
+ total += amount
98
+
99
+ if total == 0 and not notes:
100
+ return "Error: could not aggregate (no matching rows)."
101
+ return f"{total:.2f}"
tools/media_tools.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ from inference_client_factory import make_inference_client
7
+
8
+
9
+ def transcribe_audio(
10
+ file_path: str,
11
+ *,
12
+ hf_token: Optional[str] = None,
13
+ model: Optional[str] = None,
14
+ ) -> str:
15
+ token = hf_token or os.environ.get("HF_TOKEN") or os.environ.get(
16
+ "HUGGINGFACEHUB_API_TOKEN"
17
+ )
18
+ if not token:
19
+ return "Error: HF_TOKEN not set for speech recognition."
20
+ mid = model or os.environ.get("GAIA_ASR_MODEL", "openai/whisper-large-v3")
21
+ client = make_inference_client(token)
22
+ try:
23
+ out = client.automatic_speech_recognition(file_path, model=mid)
24
+ return (out.text or "").strip()
25
+ except Exception as e:
26
+ return f"ASR error: {e}"
27
+
28
+
29
+ def analyze_image_with_vlm(
30
+ file_path: str,
31
+ question: str,
32
+ *,
33
+ hf_token: Optional[str] = None,
34
+ model: Optional[str] = None,
35
+ ) -> str:
36
+ """Use a vision-language chat model via HF Inference (image as data URL)."""
37
+ token = hf_token or os.environ.get("HF_TOKEN") or os.environ.get(
38
+ "HUGGINGFACEHUB_API_TOKEN"
39
+ )
40
+ if not token:
41
+ return "Error: HF_TOKEN not set for vision."
42
+ mid = model or os.environ.get(
43
+ "GAIA_VISION_MODEL", "meta-llama/Llama-3.2-11B-Vision-Instruct"
44
+ )
45
+ path = Path(file_path)
46
+ if not path.is_file():
47
+ return f"Error: image not found: {file_path}"
48
+ raw = path.read_bytes()
49
+ b64 = base64.b64encode(raw).decode("ascii")
50
+ mime = "image/png" if path.suffix.lower() == ".png" else "image/jpeg"
51
+ data_url = f"data:{mime};base64,{b64}"
52
+ client = make_inference_client(token)
53
+ messages = [
54
+ {
55
+ "role": "user",
56
+ "content": [
57
+ {"type": "text", "text": question},
58
+ {"type": "image_url", "image_url": {"url": data_url}},
59
+ ],
60
+ }
61
+ ]
62
+ try:
63
+ comp = client.chat_completion(
64
+ messages=messages,
65
+ model=mid,
66
+ max_tokens=512,
67
+ temperature=0.2,
68
+ )
69
+ msg = comp.choices[0].message
70
+ return (msg.content or "").strip()
71
+ except Exception as e:
72
+ return f"Vision error: {e}"
73
+
74
+
75
+ def visual_question_short(
76
+ file_path: str,
77
+ question: str,
78
+ *,
79
+ hf_token: Optional[str] = None,
80
+ model: Optional[str] = None,
81
+ ) -> str:
82
+ """Fallback VQA task (shorter answers)."""
83
+ token = hf_token or os.environ.get("HF_TOKEN") or os.environ.get(
84
+ "HUGGINGFACEHUB_API_TOKEN"
85
+ )
86
+ if not token:
87
+ return "Error: HF_TOKEN not set for VQA."
88
+ mid = model or "Salesforce/blip-vqa-base"
89
+ client = make_inference_client(token)
90
+ try:
91
+ answers = client.visual_question_answering(
92
+ image=file_path, question=question, model=mid, top_k=5
93
+ )
94
+ lines = [f"{a.answer} ({a.score:.3f})" for a in answers]
95
+ return "\n".join(lines)
96
+ except Exception as e:
97
+ return f"VQA error: {e}"
tools/registry.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-style tool schemas and dispatch for Hugging Face chat_completion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Callable, Optional
7
+
8
+ from tools.code_tools import (
9
+ run_python_file,
10
+ run_python_snippet,
11
+ solve_cayley_noncommutative_subset,
12
+ reverse_english_puzzle_answer,
13
+ )
14
+ from tools.excel_tools import excel_food_sales_total_usd
15
+ from tools.media_tools import analyze_image_with_vlm, transcribe_audio, visual_question_short
16
+ from tools.web_tools import fetch_url, web_search, youtube_transcript
17
+ from tools.wiki_tools import wikipedia_search, wikipedia_summary
18
+
19
+ TOOL_DEFINITIONS: list[dict[str, Any]] = [
20
+ {
21
+ "type": "function",
22
+ "function": {
23
+ "name": "web_search",
24
+ "description": "Search the web (DuckDuckGo). Use for facts, papers, news, sports, cast lists.",
25
+ "parameters": {
26
+ "type": "object",
27
+ "properties": {
28
+ "query": {"type": "string"},
29
+ "max_results": {"type": "integer"},
30
+ },
31
+ "required": ["query"],
32
+ },
33
+ },
34
+ },
35
+ {
36
+ "type": "function",
37
+ "function": {
38
+ "name": "fetch_url",
39
+ "description": "Download a public web page and return extracted text (truncated).",
40
+ "parameters": {
41
+ "type": "object",
42
+ "properties": {"url": {"type": "string"}},
43
+ "required": ["url"],
44
+ },
45
+ },
46
+ },
47
+ {
48
+ "type": "function",
49
+ "function": {
50
+ "name": "wikipedia_search",
51
+ "description": "Search English Wikipedia article titles.",
52
+ "parameters": {
53
+ "type": "object",
54
+ "properties": {
55
+ "query": {"type": "string"},
56
+ "results": {"type": "integer"},
57
+ },
58
+ "required": ["query"],
59
+ },
60
+ },
61
+ },
62
+ {
63
+ "type": "function",
64
+ "function": {
65
+ "name": "wikipedia_summary",
66
+ "description": "Get English Wikipedia summary text for a specific article title.",
67
+ "parameters": {
68
+ "type": "object",
69
+ "properties": {
70
+ "title": {"type": "string"},
71
+ "sentences": {"type": "integer"},
72
+ },
73
+ "required": ["title"],
74
+ },
75
+ },
76
+ },
77
+ {
78
+ "type": "function",
79
+ "function": {
80
+ "name": "run_python_snippet",
81
+ "description": (
82
+ "Run a short Python snippet in a subprocess (stdlib only; no network). "
83
+ "Use for parsing, counting, or arithmetic on data you already have."
84
+ ),
85
+ "parameters": {
86
+ "type": "object",
87
+ "properties": {"code": {"type": "string"}},
88
+ "required": ["code"],
89
+ },
90
+ },
91
+ },
92
+ {
93
+ "type": "function",
94
+ "function": {
95
+ "name": "youtube_transcript",
96
+ "description": "Fetch YouTube captions/transcript when available.",
97
+ "parameters": {
98
+ "type": "object",
99
+ "properties": {"video_url": {"type": "string"}},
100
+ "required": ["video_url"],
101
+ },
102
+ },
103
+ },
104
+ {
105
+ "type": "function",
106
+ "function": {
107
+ "name": "transcribe_audio",
108
+ "description": "Transcribe a local audio file (.mp3, etc.) using HF Whisper inference.",
109
+ "parameters": {
110
+ "type": "object",
111
+ "properties": {"file_path": {"type": "string"}},
112
+ "required": ["file_path"],
113
+ },
114
+ },
115
+ },
116
+ {
117
+ "type": "function",
118
+ "function": {
119
+ "name": "analyze_image",
120
+ "description": (
121
+ "Ask a vision-language model about a local image file (PNG/JPEG). "
122
+ "Use for diagrams, screenshots, chess positions, etc."
123
+ ),
124
+ "parameters": {
125
+ "type": "object",
126
+ "properties": {
127
+ "file_path": {"type": "string"},
128
+ "question": {"type": "string"},
129
+ },
130
+ "required": ["file_path", "question"],
131
+ },
132
+ },
133
+ },
134
+ {
135
+ "type": "function",
136
+ "function": {
137
+ "name": "visual_question_short",
138
+ "description": "Lightweight VQA (short label-style answers). Fallback if analyze_image fails.",
139
+ "parameters": {
140
+ "type": "object",
141
+ "properties": {
142
+ "file_path": {"type": "string"},
143
+ "question": {"type": "string"},
144
+ },
145
+ "required": ["file_path", "question"],
146
+ },
147
+ },
148
+ },
149
+ {
150
+ "type": "function",
151
+ "function": {
152
+ "name": "excel_food_sales_total_usd",
153
+ "description": (
154
+ "Sum food sales in USD from the attached fast-food style spreadsheet, excluding drinks."
155
+ ),
156
+ "parameters": {
157
+ "type": "object",
158
+ "properties": {"file_path": {"type": "string"}},
159
+ "required": ["file_path"],
160
+ },
161
+ },
162
+ },
163
+ ]
164
+
165
+
166
+ def dispatch_tool(
167
+ name: str,
168
+ arguments_json: str,
169
+ *,
170
+ hf_token: Optional[str] = None,
171
+ ) -> str:
172
+ try:
173
+ args = json.loads(arguments_json) if arguments_json.strip() else {}
174
+ except json.JSONDecodeError as e:
175
+ return f"Invalid JSON arguments: {e}"
176
+
177
+ try:
178
+ if name == "web_search":
179
+ return web_search(
180
+ args["query"], max_results=int(args.get("max_results", 8))
181
+ )
182
+ if name == "fetch_url":
183
+ return fetch_url(args["url"])
184
+ if name == "wikipedia_search":
185
+ return wikipedia_search(
186
+ args["query"], results=int(args.get("results", 5))
187
+ )
188
+ if name == "wikipedia_summary":
189
+ return wikipedia_summary(
190
+ args["title"], sentences=int(args.get("sentences", 16))
191
+ )
192
+ if name == "run_python_snippet":
193
+ return run_python_snippet(args["code"])
194
+ if name == "youtube_transcript":
195
+ return youtube_transcript(args["video_url"])
196
+ if name == "transcribe_audio":
197
+ return transcribe_audio(args["file_path"], hf_token=hf_token)
198
+ if name == "analyze_image":
199
+ return analyze_image_with_vlm(
200
+ args["file_path"], args["question"], hf_token=hf_token
201
+ )
202
+ if name == "visual_question_short":
203
+ return visual_question_short(
204
+ args["file_path"], args["question"], hf_token=hf_token
205
+ )
206
+ if name == "excel_food_sales_total_usd":
207
+ return excel_food_sales_total_usd(args["file_path"])
208
+ return f"Unknown tool: {name}"
209
+ except Exception as e:
210
+ return f"Tool error ({name}): {e}"
211
+
212
+
213
+ def deterministic_attempt(question: str, attachment_path: Optional[str]) -> Optional[str]:
214
+ """Return an answer without LLM when we can solve reliably."""
215
+ r = reverse_english_puzzle_answer(question)
216
+ if r is not None:
217
+ return r
218
+ c = solve_cayley_noncommutative_subset(question)
219
+ if c is not None:
220
+ return c
221
+ if attachment_path:
222
+ low = attachment_path.lower()
223
+ if low.endswith(".py"):
224
+ return run_python_file(attachment_path).strip()
225
+ if low.endswith(".xlsx"):
226
+ return excel_food_sales_total_usd(attachment_path)
227
+ return None
tools/web_tools.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from html import unescape
3
+ from typing import Optional
4
+ from urllib.parse import urlparse
5
+
6
+ import requests
7
+ from bs4 import BeautifulSoup
8
+
9
+ try:
10
+ from duckduckgo_search import DDGS
11
+ except ImportError:
12
+ DDGS = None # type: ignore
13
+
14
+ DEFAULT_UA = (
15
+ "Mozilla/5.0 (compatible; GAIA-Agent/1.0; +https://huggingface.co/spaces)"
16
+ )
17
+ MAX_FETCH_BYTES = 1_500_000
18
+
19
+
20
+ def web_search(query: str, max_results: int = 8) -> str:
21
+ """Return short snippets and URLs from DuckDuckGo text search."""
22
+ if not query.strip():
23
+ return "Error: empty query."
24
+ if DDGS is None:
25
+ return "Error: duckduckgo_search is not installed."
26
+ lines: list[str] = []
27
+ try:
28
+ with DDGS() as ddgs:
29
+ for i, r in enumerate(ddgs.text(query, max_results=max_results)):
30
+ title = r.get("title") or ""
31
+ body = r.get("body") or ""
32
+ href = r.get("href") or ""
33
+ lines.append(f"{i + 1}. {title}\n {body[:400]}\n URL: {href}")
34
+ except Exception as e:
35
+ return f"Search error: {e}"
36
+ if not lines:
37
+ return "No results."
38
+ return "\n\n".join(lines)
39
+
40
+
41
+ def _visible_text(html: str) -> str:
42
+ soup = BeautifulSoup(html, "lxml")
43
+ for tag in soup(["script", "style", "noscript"]):
44
+ tag.decompose()
45
+ text = soup.get_text(separator="\n")
46
+ text = unescape(text)
47
+ text = re.sub(r"\n{3,}", "\n\n", text)
48
+ return text.strip()
49
+
50
+
51
+ def fetch_url(url: str, max_chars: int = 25_000) -> str:
52
+ """Fetch a URL and return extracted plain text (truncated)."""
53
+ if not url.strip():
54
+ return "Error: empty URL."
55
+ parsed = urlparse(url)
56
+ if parsed.scheme not in ("http", "https"):
57
+ return "Error: only http(s) URLs are allowed."
58
+ try:
59
+ r = requests.get(
60
+ url,
61
+ timeout=45,
62
+ headers={"User-Agent": DEFAULT_UA},
63
+ stream=True,
64
+ )
65
+ r.raise_for_status()
66
+ chunks: list[bytes] = []
67
+ total = 0
68
+ for chunk in r.iter_content(chunk_size=65536):
69
+ if not chunk:
70
+ continue
71
+ chunks.append(chunk)
72
+ total += len(chunk)
73
+ if total >= MAX_FETCH_BYTES:
74
+ break
75
+ raw = b"".join(chunks)
76
+ ctype = r.headers.get("Content-Type", "").lower()
77
+ if "pdf" in ctype or url.lower().endswith(".pdf"):
78
+ return (
79
+ "Error: PDF binary not parsed here. "
80
+ "Search for an HTML abstract page or use web_search instead."
81
+ )
82
+ text = raw.decode("utf-8", errors="replace")
83
+ plain = _visible_text(text) if "<html" in text.lower() else text
84
+ plain = plain[:max_chars]
85
+ return plain if plain.strip() else "(empty body after parse)"
86
+ except Exception as e:
87
+ return f"Fetch error: {e}"
88
+
89
+
90
+ def youtube_transcript(video_url: str) -> str:
91
+ """Return transcript text when the video exposes captions (unofficial API)."""
92
+ try:
93
+ from youtube_transcript_api import YouTubeTranscriptApi
94
+ except ImportError:
95
+ return "Error: youtube_transcript_api not installed."
96
+
97
+ m = re.search(
98
+ r"(?:youtube\.com/watch\?v=|youtu\.be/)([a-zA-Z0-9_-]{6,})",
99
+ video_url,
100
+ )
101
+ if not m:
102
+ return "Error: could not parse YouTube video id from URL."
103
+ vid = m.group(1)
104
+ try:
105
+ transcript = YouTubeTranscriptApi.get_transcript(vid)
106
+ except Exception as e:
107
+ return f"No transcript available: {e}"
108
+ lines = [entry.get("text", "") for entry in transcript]
109
+ return "\n".join(lines)[:50_000]
tools/wiki_tools.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import wikipedia
2
+
3
+
4
+ def wikipedia_search(query: str, results: int = 5) -> str:
5
+ """Search English Wikipedia titles."""
6
+ if not query.strip():
7
+ return "Error: empty query."
8
+ wikipedia.set_lang("en")
9
+ try:
10
+ titles = wikipedia.search(query, results=results)
11
+ except Exception as e:
12
+ return f"Wikipedia search error: {e}"
13
+ if not titles:
14
+ return "No titles found."
15
+ return "\n".join(f"- {t}" for t in titles)
16
+
17
+
18
+ def wikipedia_summary(title: str, sentences: int = 12) -> str:
19
+ """Fetch a Wikipedia page summary by title (English)."""
20
+ if not title.strip():
21
+ return "Error: empty title."
22
+ wikipedia.set_lang("en")
23
+ try:
24
+ page = wikipedia.page(title, auto_suggest=True)
25
+ summary = wikipedia.summary(title, sentences=sentences, auto_suggest=True)
26
+ out = f"Title: {page.title}\nURL: {page.url}\n\n{summary}"
27
+ return out[:40_000]
28
+ except wikipedia.DisambiguationError as e:
29
+ opts = ", ".join(e.options[:8])
30
+ return f"Disambiguation; try one of: {opts}"
31
+ except Exception as e:
32
+ return f"Wikipedia error: {e}"