Files changed (7) hide show
  1. README.md +42 -3
  2. agent.py +143 -0
  3. app.py +114 -176
  4. gaia_api.py +50 -0
  5. requirements.txt +11 -1
  6. run_local.py +58 -0
  7. tools.py +287 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Template Final Assignment
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
@@ -8,8 +8,47 @@ sdk_version: 5.25.2
8
  app_file: app.py
9
  pinned: false
10
  hf_oauth: true
11
- # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
  hf_oauth_expiration_minutes: 480
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: GAIA Agent Final Assignment
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
 
8
  app_file: app.py
9
  pinned: false
10
  hf_oauth: true
 
11
  hf_oauth_expiration_minutes: 480
12
  ---
13
 
14
+ # GAIA agent (Hugging Face Agents Course, Unit 4)
15
+
16
+ A `smolagents` CodeAgent that answers the 20 GAIA level-1 questions from the course
17
+ scoring API. Target: 30% or more.
18
+
19
+ ## Files
20
+
21
+ | File | What it does |
22
+ |---|---|
23
+ | `app.py` | Gradio UI: log in, run the agent (answers cached), submit separately |
24
+ | `agent.py` | Model selection, agent instructions, answer clean-up for exact match |
25
+ | `tools.py` | Web search, webpage reader, Wikipedia (tables kept), YouTube transcript, file reader, Whisper transcription, Python script runner |
26
+ | `gaia_api.py` | Scoring API client and the `answers_cache.json` cache |
27
+ | `run_local.py` | Test single questions on a laptop or Colab without submitting |
28
+
29
+ ## Set up the Space
30
+
31
+ 1. Create a new Gradio Space (or duplicate the course template) and upload these files.
32
+ Keep the Space **public**: the submission includes a link to its code.
33
+ 2. In **Settings → Variables and secrets** add:
34
+ - `MODEL_ID` (variable), for example:
35
+ - `gemini/gemini-2.5-flash` plus secret `GEMINI_API_KEY`
36
+ - `openai/gpt-4.1-mini` plus secret `OPENAI_API_KEY`
37
+ - `openrouter/<model>` plus secret `OPENROUTER_API_KEY`
38
+ - a Hugging Face model id plus secret `HF_TOKEN` (optional variable `HF_PROVIDER`)
39
+ - `TAVILY_API_KEY` (optional secret): more reliable search than DuckDuckGo, which
40
+ often rate-limits shared Space IPs.
41
+ - `MAX_STEPS` (optional, default 12), `WHISPER_MODEL` (optional, default `base`).
42
+ 3. Open the app, log in, press **Run agent**, check the table, press **Submit cached answers**.
43
+
44
+ For questions with an image attached, the model must accept images
45
+ (Gemini and GPT-4.1 models do). Otherwise the agent retries without the image.
46
+
47
+ ## Test locally first
48
+
49
+ ```bash
50
+ pip install -r requirements.txt
51
+ export MODEL_ID=gemini/gemini-2.5-flash GEMINI_API_KEY=...
52
+ python run_local.py --list
53
+ python run_local.py --task <task-id-prefix>
54
+ ```
agent.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The GAIA agent: a smolagents CodeAgent with a provider-agnostic model.
2
+
3
+ Choose the LLM with environment variables (Space secrets/variables):
4
+
5
+ MODEL_ID a LiteLLM id such as "gemini/gemini-2.5-flash" or "openai/gpt-4.1-mini"
6
+ (format: "<provider>/<model>"), or a Hugging Face model id such as
7
+ "Qwen/Qwen3-Coder-480B-A35B-Instruct".
8
+ MODEL_BACKEND optional: "litellm" or "hf". Auto-detected from MODEL_ID if unset.
9
+ HF_PROVIDER optional Hugging Face inference provider, e.g. "together", "nebius".
10
+ MAX_STEPS optional, default 12.
11
+
12
+ API keys are read from the usual variables: HF_TOKEN, GEMINI_API_KEY, OPENAI_API_KEY,
13
+ ANTHROPIC_API_KEY, OPENROUTER_API_KEY, ... (LiteLLM picks them up automatically).
14
+ """
15
+
16
+ import os
17
+ import re
18
+ from pathlib import Path
19
+
20
+ from smolagents import CodeAgent, InferenceClientModel, LiteLLMModel
21
+
22
+ from tools import IMAGE_EXT, get_tools
23
+
24
+ # Model-id prefixes that mean "route through LiteLLM" rather than Hugging Face.
25
+ LITELLM_PREFIXES = {
26
+ "gemini", "openai", "anthropic", "openrouter", "groq", "mistral", "deepseek",
27
+ "together_ai", "xai", "ollama", "ollama_chat", "azure", "bedrock", "vertex_ai", "cohere",
28
+ }
29
+
30
+ INSTRUCTIONS = """You are solving questions from the GAIA benchmark. Your final answer is graded by EXACT string match against the ground truth, so its form matters as much as its content.
31
+
32
+ How to work:
33
+ - Plan briefly, then verify facts with tools. Do not answer from memory when a source can be checked.
34
+ - For encyclopedic facts (discographies, results tables, biographies) prefer wikipedia_page, which keeps tables. If the question names a Wikipedia version or year, pass as_of="YYYY-MM-DD".
35
+ - For everything else: web_search to find a page, then visit_webpage to read it. Snippets are often incomplete.
36
+ - Do every calculation, count, sort or text manipulation in Python code, never in your head.
37
+ - If the question text looks scrambled (for example written backwards), decode it in Python first, then answer what it actually asks.
38
+ - If a file is attached, its path is given in the task. Use read_file (text, code, spreadsheets, PDFs, audio) or run_python_file (to get the output of a .py file). For spreadsheets you may also load them with pandas directly.
39
+ - If a tool fails, try a different route instead of repeating the same call.
40
+
41
+ Rules for the value you pass to final_answer:
42
+ - Only the answer itself: no explanation, no full sentence, no "FINAL ANSWER", no trailing period.
43
+ - A number: digits only, no thousands separators, no units, no "$" or "%", unless the question explicitly asks for them. Respect any requested rounding or decimal places.
44
+ - A string: as few words as possible, no articles, no abbreviations unless asked, exact spelling and capitalisation of the name as given in the source.
45
+ - A list: comma-separated with one space after each comma ("a, b, c"), ordered as the question asks (alphabetical, chronological, ...).
46
+ - Obey every formatting instruction in the question (e.g. "first name only", "IOC country code", "in algebraic notation", "plural form").
47
+ - If after real effort you still cannot be sure, give your single best guess rather than an apology."""
48
+
49
+
50
+ def build_model():
51
+ """Return a smolagents Model chosen by environment variables."""
52
+ model_id = os.getenv("MODEL_ID", "").strip()
53
+ backend = os.getenv("MODEL_BACKEND", "").strip().lower()
54
+ if not backend:
55
+ prefix = model_id.split("/", 1)[0].lower() if "/" in model_id else ""
56
+ backend = "litellm" if prefix in LITELLM_PREFIXES else "hf"
57
+
58
+ if backend == "litellm":
59
+ if not model_id:
60
+ raise ValueError("MODEL_BACKEND=litellm needs MODEL_ID, e.g. 'gemini/gemini-2.5-flash'.")
61
+ return LiteLLMModel(model_id=model_id, api_base=os.getenv("API_BASE") or None)
62
+
63
+ kwargs = {"token": os.getenv("HF_TOKEN"), "timeout": 180}
64
+ if model_id:
65
+ kwargs["model_id"] = model_id
66
+ if os.getenv("HF_PROVIDER"):
67
+ kwargs["provider"] = os.getenv("HF_PROVIDER")
68
+ return InferenceClientModel(**kwargs) # without MODEL_ID, smolagents' default model
69
+
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # Answer clean-up (the scorer does exact match)
73
+ # ---------------------------------------------------------------------------
74
+ _THOUSANDS = re.compile(r"-?\d{1,3}(,\d{3})+(\.\d+)?")
75
+
76
+
77
+ def clean_answer(answer) -> str:
78
+ s = str(answer).strip()
79
+ s = re.sub(r"^\s*(final\s+answer|answer)\s*[::-]\s*", "", s, flags=re.I)
80
+ s = s.replace("**", "").replace("`", "").strip()
81
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'": # surrounding quotes
82
+ s = s[1:-1].strip()
83
+ s = re.sub(r"\s+", " ", s)
84
+ # Drop a sentence-ending period, but keep abbreviations ("D.C.", "Jr.").
85
+ if s.endswith(".") and not re.search(r"(\b[A-Za-z]|\b(Jr|Sr|St|Inc|Ltd|Co|Corp|etc|vs))\.$", s):
86
+ s = s[:-1].rstrip()
87
+ if _THOUSANDS.fullmatch(s): # "1,234,567" -> "1234567"
88
+ s = s.replace(",", "")
89
+ elif "," in s: # list: normalise to "a, b, c"
90
+ s = re.sub(r"\s*,\s*", ", ", s)
91
+ return s
92
+
93
+
94
+ def check_answer_format(final_answer, memory, agent=None) -> bool:
95
+ """Final-answer check: makes the agent retry if it answers with an essay."""
96
+ text = str(final_answer)
97
+ if "final answer" in text.lower():
98
+ raise ValueError("Pass only the bare answer to final_answer, without the words 'FINAL ANSWER'.")
99
+ if len(text) > 300:
100
+ raise ValueError("The answer is far too long. Pass only the exact answer value, not an explanation.")
101
+ return True
102
+
103
+
104
+ class GaiaAgent:
105
+ """Callable used by app.py: agent(question, file_path) -> answer string."""
106
+
107
+ def __init__(self):
108
+ self.model = build_model()
109
+ self.agent = CodeAgent(
110
+ tools=get_tools(),
111
+ model=self.model,
112
+ instructions=INSTRUCTIONS,
113
+ max_steps=int(os.getenv("MAX_STEPS", "12")),
114
+ additional_authorized_imports=[
115
+ "pandas", "numpy", "math", "re", "json", "csv", "datetime", "statistics",
116
+ "itertools", "collections", "unicodedata", "fractions", "decimal", "openpyxl",
117
+ ],
118
+ final_answer_checks=[check_answer_format],
119
+ verbosity_level=1,
120
+ )
121
+
122
+ def __call__(self, question: str, file_path: str | None = None) -> str:
123
+ task = question
124
+ images = None
125
+ if file_path:
126
+ ext = Path(file_path).suffix.lower()
127
+ task += f"\n\nAttached file: {file_path}"
128
+ if ext in IMAGE_EXT:
129
+ from PIL import Image
130
+
131
+ images = [Image.open(file_path).convert("RGB")]
132
+ task += "\n(The image is attached to this message; look at it directly.)"
133
+ else:
134
+ task += f"\n(Open it with read_file{' or run_python_file' if ext == '.py' else ''}.)"
135
+ try:
136
+ result = self.agent.run(task, images=images)
137
+ except Exception as e:
138
+ if images is None:
139
+ raise
140
+ # Model may not accept images: retry text-only so the run still produces an answer.
141
+ print(f"Run with image failed ({e}); retrying without the image.")
142
+ result = self.agent.run(task + "\n(The image could not be shown; work from the question.)")
143
+ return clean_answer(result)
app.py CHANGED
@@ -1,196 +1,134 @@
 
 
 
 
 
 
 
 
 
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 = BasicAgent()
44
  except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
- return f"Error initializing agent: {e}", None
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(questions_url, timeout=15)
55
- response.raise_for_status()
56
- questions_data = response.json()
57
- if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
-
72
- # 3. Run your Agent
73
- results_log = []
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
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
-
90
- if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
-
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
 
 
 
 
 
 
 
101
  try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
103
- response.raise_for_status()
104
- result_data = response.json()
105
- final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
- )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
- except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
- try:
118
- error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
- print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
  except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
-
142
-
143
- # --- Build Gradio Interface using Blocks ---
144
- with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
- gr.Markdown(
147
- """
148
- **Instructions:**
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
- **Disclaimers:**
156
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
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 = gr.Button("Run Evaluation & Submit All Answers")
 
 
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
- print("\n" + "-"*30 + " App Starting " + "-"*30)
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
+ """Gradio app for the Agents Course final assignment.
2
+
3
+ Changes from the course template:
4
+ - The agent also gets the file attached to each question (GET /files/{task_id}).
5
+ - Answers are cached to disk after every question, so a crash or timeout does not
6
+ lose earlier work, and re-running only processes what is missing.
7
+ - Running and submitting are separate buttons: inspect the answers, then submit.
8
+ """
9
+
10
  import os
11
+ import traceback
12
+
13
  import gradio as gr
 
 
14
  import pandas as pd
15
 
16
+ import gaia_api as api
17
+
18
+ AGENT = None # built lazily so the UI loads even if the model config is wrong
19
+
20
+
21
+ def get_agent():
22
+ global AGENT
23
+ if AGENT is None:
24
+ from agent import GaiaAgent
25
+
26
+ AGENT = GaiaAgent()
27
+ return AGENT
28
+
29
+
30
+ def cache_table(cache: dict) -> pd.DataFrame:
31
+ rows = [
32
+ {"Task ID": tid, "Question": v.get("question", "")[:150],
33
+ "File": v.get("file_name", ""), "Answer": v.get("submitted_answer", ""),
34
+ "Error": v.get("error", "")}
35
+ for tid, v in cache.items()
36
+ ]
37
+ return pd.DataFrame(rows, columns=["Task ID", "Question", "File", "Answer", "Error"])
38
+
39
+
40
+ def run_agent(rerun_errors: bool, profile: gr.OAuthProfile | None):
41
+ """Generator: answers every uncached question, streaming progress to the UI."""
42
+ if not profile:
43
+ yield "Please log in with the Hugging Face button first.", None
44
+ return
 
 
 
 
 
 
45
  try:
46
+ questions = api.fetch_questions()
47
  except Exception as e:
48
+ yield f"Could not fetch questions: {e}", None
49
+ return
 
 
 
 
 
 
50
  try:
51
+ agent = get_agent()
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  except Exception as e:
53
+ yield f"Could not build the agent (check MODEL_ID and API key secrets): {e}", None
54
+ return
55
+
56
+ cache = api.load_cache()
57
+ todo = [
58
+ q for q in questions
59
+ if q["task_id"] not in cache or (rerun_errors and cache[q["task_id"]].get("error"))
60
+ ]
61
+ yield f"{len(questions)} questions, {len(questions) - len(todo)} cached, running {len(todo)}...", cache_table(cache)
62
+
63
+ for i, q in enumerate(todo, 1):
64
+ tid, question, file_name = q["task_id"], q["question"], q.get("file_name", "")
65
+ entry = {"question": question, "file_name": file_name}
66
  try:
67
+ file_path = api.download_task_file(tid, file_name)
68
+ entry["submitted_answer"] = agent(question, file_path)
 
69
  except Exception as e:
70
+ traceback.print_exc()
71
+ entry["submitted_answer"] = ""
72
+ entry["error"] = f"{type(e).__name__}: {e}"[:300]
73
+ cache[tid] = entry
74
+ api.save_cache(cache)
75
+ yield f"Done {i}/{len(todo)}. Last answer: {entry['submitted_answer']!r}", cache_table(cache)
76
+
77
+ yield f"Finished. {len(cache)} answers cached. Review them, then press Submit.", cache_table(cache)
78
+
79
+
80
+ def submit_answers(profile: gr.OAuthProfile | None):
81
+ if not profile:
82
+ return "Please log in with the Hugging Face button first.", None
83
+ cache = api.load_cache()
84
+ answers = [
85
+ {"task_id": tid, "submitted_answer": v.get("submitted_answer", "")}
86
+ for tid, v in cache.items() if v.get("submitted_answer")
87
+ ]
88
+ if not answers:
89
+ return "No cached answers yet. Run the agent first.", cache_table(cache)
90
+ space_id = os.getenv("SPACE_ID", "")
91
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
92
  try:
93
+ result = api.submit(profile.username, agent_code, answers)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  except Exception as e:
95
+ detail = getattr(getattr(e, "response", None), "text", "")[:500]
96
+ return f"Submission failed: {e} {detail}", cache_table(cache)
97
+ status = (
98
+ f"Submission successful!\nUser: {result.get('username')}\n"
99
+ f"Score: {result.get('score', 'N/A')}% "
100
+ f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
101
+ f"Message: {result.get('message', '')}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  )
103
+ return status, cache_table(cache)
104
 
 
105
 
106
+ def clear_cache():
107
+ api.save_cache({})
108
+ return "Cache cleared.", cache_table({})
109
 
 
 
 
110
 
111
+ with gr.Blocks() as demo:
112
+ gr.Markdown("# GAIA Agent: Final Assignment Runner")
113
+ gr.Markdown(
114
+ "1. Log in with Hugging Face. \n"
115
+ "2. **Run agent** answers the questions and caches each answer as it goes. "
116
+ "If it stops part-way, press it again: only missing answers are processed. \n"
117
+ "3. Check the table, then **Submit** sends the cached answers for scoring."
118
  )
119
+ gr.LoginButton()
120
+ with gr.Row():
121
+ rerun_errors = gr.Checkbox(label="Also re-run questions that errored", value=True)
122
+ with gr.Row():
123
+ run_btn = gr.Button("Run agent", variant="primary")
124
+ submit_btn = gr.Button("Submit cached answers")
125
+ clear_btn = gr.Button("Clear cache")
126
+ status = gr.Textbox(label="Status", lines=5, interactive=False)
127
+ table = gr.DataFrame(label="Cached answers", wrap=True, value=cache_table(api.load_cache()))
128
+
129
+ run_btn.click(run_agent, inputs=[rerun_errors], outputs=[status, table])
130
+ submit_btn.click(submit_answers, outputs=[status, table])
131
+ clear_btn.click(clear_cache, outputs=[status, table])
132
 
133
  if __name__ == "__main__":
134
+ demo.queue().launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gaia_api.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small client for the course scoring API, plus an on-disk answer cache."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import requests
7
+
8
+ API_URL = "https://agents-course-unit4-scoring.hf.space"
9
+ DOWNLOAD_DIR = Path("downloads")
10
+ CACHE_FILE = Path("answers_cache.json")
11
+
12
+
13
+ def fetch_questions() -> list[dict]:
14
+ r = requests.get(f"{API_URL}/questions", timeout=30)
15
+ r.raise_for_status()
16
+ return r.json()
17
+
18
+
19
+ def download_task_file(task_id: str, file_name: str) -> str | None:
20
+ """Download the file attached to a task (if any). Returns its local path."""
21
+ if not file_name:
22
+ return None
23
+ DOWNLOAD_DIR.mkdir(exist_ok=True)
24
+ path = DOWNLOAD_DIR / f"{task_id}_{Path(file_name).name}"
25
+ if path.exists() and path.stat().st_size > 0:
26
+ return str(path)
27
+ r = requests.get(f"{API_URL}/files/{task_id}", timeout=60)
28
+ r.raise_for_status()
29
+ path.write_bytes(r.content)
30
+ return str(path)
31
+
32
+
33
+ def load_cache() -> dict:
34
+ if CACHE_FILE.exists():
35
+ try:
36
+ return json.loads(CACHE_FILE.read_text())
37
+ except json.JSONDecodeError:
38
+ pass
39
+ return {}
40
+
41
+
42
+ def save_cache(cache: dict) -> None:
43
+ CACHE_FILE.write_text(json.dumps(cache, indent=2, ensure_ascii=False))
44
+
45
+
46
+ def submit(username: str, agent_code: str, answers: list[dict]) -> dict:
47
+ payload = {"username": username.strip(), "agent_code": agent_code, "answers": answers}
48
+ r = requests.post(f"{API_URL}/submit", json=payload, timeout=120)
49
+ r.raise_for_status()
50
+ return r.json()
requirements.txt CHANGED
@@ -1,2 +1,12 @@
1
  gradio
2
- requests
 
 
 
 
 
 
 
 
 
 
 
1
  gradio
2
+ requests
3
+ pandas
4
+ openpyxl
5
+ smolagents[litellm]>=1.26
6
+ ddgs
7
+ markdownify
8
+ youtube-transcript-api>=1.0
9
+ faster-whisper
10
+ pypdf
11
+ python-docx
12
+ pillow
run_local.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Try the agent outside the Space (laptop or Colab), without submitting anything.
2
+
3
+ python run_local.py --list # show the questions and their task ids
4
+ python run_local.py --task 8e867cd7 # answer one question (task id prefix is enough)
5
+ python run_local.py --first 3 # answer the first 3 questions
6
+ python run_local.py --ask "What is 2+2?" # any ad-hoc question
7
+
8
+ Answers for real tasks are written to the same answers_cache.json the Space uses.
9
+ """
10
+
11
+ import argparse
12
+
13
+ import gaia_api as api
14
+
15
+
16
+ def main():
17
+ p = argparse.ArgumentParser()
18
+ p.add_argument("--list", action="store_true")
19
+ p.add_argument("--task", help="task_id or a unique prefix of it")
20
+ p.add_argument("--first", type=int)
21
+ p.add_argument("--ask")
22
+ args = p.parse_args()
23
+
24
+ if args.ask:
25
+ from agent import GaiaAgent
26
+
27
+ print("ANSWER:", GaiaAgent()(args.ask))
28
+ return
29
+
30
+ questions = api.fetch_questions()
31
+ if args.list:
32
+ for q in questions:
33
+ f = f" [file: {q['file_name']}]" if q.get("file_name") else ""
34
+ print(f"{q['task_id'][:8]} {q['question'][:90]!r}{f}")
35
+ return
36
+
37
+ if args.task:
38
+ chosen = [q for q in questions if q["task_id"].startswith(args.task)]
39
+ else:
40
+ chosen = questions[: args.first or 1]
41
+ if not chosen:
42
+ raise SystemExit("No matching task.")
43
+
44
+ from agent import GaiaAgent
45
+
46
+ agent = GaiaAgent()
47
+ cache = api.load_cache()
48
+ for q in chosen:
49
+ path = api.download_task_file(q["task_id"], q.get("file_name", ""))
50
+ answer = agent(q["question"], path)
51
+ print(f"\n=== {q['task_id'][:8]} -> {answer!r}\n")
52
+ cache[q["task_id"]] = {"question": q["question"], "file_name": q.get("file_name", ""),
53
+ "submitted_answer": answer}
54
+ api.save_cache(cache)
55
+
56
+
57
+ if __name__ == "__main__":
58
+ main()
tools.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for the GAIA agent (smolagents).
2
+
3
+ Each tool returns a string. Errors are returned as text, never raised, so the
4
+ agent can read what went wrong and try another route.
5
+ """
6
+
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import requests
15
+ from smolagents import Tool, VisitWebpageTool, tool
16
+
17
+ HEADERS = {"User-Agent": "Mozilla/5.0 (GAIA agent; HF agents-course final project)"}
18
+ MAX_CHARS = 40_000 # cap on any single tool output, to protect the context window
19
+
20
+
21
+ def _truncate(text: str, limit: int = MAX_CHARS) -> str:
22
+ if len(text) <= limit:
23
+ return text
24
+ return text[:limit] + f"\n\n[... truncated, {len(text) - limit} more characters ...]"
25
+
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # Web search: Tavily if TAVILY_API_KEY is set, otherwise DuckDuckGo (free,
29
+ # but rate-limited on shared Space IPs, so it retries with back-off).
30
+ # ---------------------------------------------------------------------------
31
+ class WebSearchTool(Tool):
32
+ name = "web_search"
33
+ description = (
34
+ "Searches the web and returns the top results (title, URL, snippet). "
35
+ "Use it to find pages, then open the most promising URL with visit_webpage "
36
+ "to read the details. Snippets alone are often incomplete."
37
+ )
38
+ inputs = {"query": {"type": "string", "description": "The search query."}}
39
+ output_type = "string"
40
+
41
+ def __init__(self, max_results: int = 6, **kwargs):
42
+ super().__init__(**kwargs)
43
+ self.max_results = max_results
44
+ self.tavily_key = os.getenv("TAVILY_API_KEY")
45
+
46
+ def _tavily(self, query: str) -> str:
47
+ r = requests.post(
48
+ "https://api.tavily.com/search",
49
+ headers={"Authorization": f"Bearer {self.tavily_key}"},
50
+ json={"query": query, "max_results": self.max_results},
51
+ timeout=30,
52
+ )
53
+ r.raise_for_status()
54
+ results = r.json().get("results", [])
55
+ return "\n\n".join(
56
+ f"[{x.get('title', '')}]({x.get('url', '')})\n{x.get('content', '')}" for x in results
57
+ )
58
+
59
+ def _ddg(self, query: str) -> str:
60
+ from ddgs import DDGS
61
+
62
+ last_err = None
63
+ for attempt in range(3):
64
+ try:
65
+ results = list(DDGS().text(query, max_results=self.max_results))
66
+ return "\n\n".join(
67
+ f"[{x.get('title', '')}]({x.get('href', '')})\n{x.get('body', '')}" for x in results
68
+ )
69
+ except Exception as e: # rate limits are common on shared IPs
70
+ last_err = e
71
+ time.sleep(2 * (attempt + 1))
72
+ raise RuntimeError(last_err)
73
+
74
+ def forward(self, query: str) -> str:
75
+ try:
76
+ out = self._tavily(query) if self.tavily_key else self._ddg(query)
77
+ return out or "No results found. Try different keywords."
78
+ except Exception as e:
79
+ return f"Search failed ({e}). Try rephrasing, or go straight to a known URL with visit_webpage."
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # Wikipedia: full article HTML converted to Markdown, so tables survive.
84
+ # (Many GAIA level-1 questions hinge on a discography or results table.)
85
+ # ---------------------------------------------------------------------------
86
+ WIKI_API = "https://en.wikipedia.org/w/api.php"
87
+
88
+
89
+ def _wiki_get(params: dict) -> dict:
90
+ params = {**params, "format": "json", "formatversion": 2}
91
+ r = requests.get(WIKI_API, params=params, headers=HEADERS, timeout=30)
92
+ r.raise_for_status()
93
+ return r.json()
94
+
95
+
96
+ @tool
97
+ def wikipedia_search(query: str) -> str:
98
+ """Searches English Wikipedia and returns matching article titles with short snippets.
99
+ Use it to find the exact title before calling wikipedia_page.
100
+
101
+ Args:
102
+ query: Search terms, e.g. "Mercedes Sosa discography".
103
+ """
104
+ try:
105
+ data = _wiki_get({"action": "query", "list": "search", "srsearch": query, "srlimit": 8})
106
+ hits = data.get("query", {}).get("search", [])
107
+ if not hits:
108
+ return "No Wikipedia results."
109
+ return "\n".join(
110
+ f"- {h['title']}: {re.sub(r'<.*?>', '', h.get('snippet', ''))}" for h in hits
111
+ )
112
+ except Exception as e:
113
+ return f"Wikipedia search failed: {e}"
114
+
115
+
116
+ @tool
117
+ def wikipedia_page(title: str, as_of: str = "") -> str:
118
+ """Returns an English Wikipedia article as Markdown, with tables kept intact.
119
+
120
+ Args:
121
+ title: Exact article title, e.g. "Mercedes Sosa".
122
+ as_of: Optional date "YYYY-MM-DD". If given, returns the article as it stood on
123
+ that date (use when the question names a specific Wikipedia version or year).
124
+ """
125
+ from markdownify import markdownify
126
+
127
+ try:
128
+ params = {"action": "parse", "prop": "text", "redirects": 1, "disableeditsection": 1}
129
+ if as_of:
130
+ rev = _wiki_get({
131
+ "action": "query", "prop": "revisions", "titles": title, "rvlimit": 1,
132
+ "rvprop": "ids|timestamp", "rvdir": "older", "rvstart": f"{as_of}T23:59:59Z",
133
+ "redirects": 1,
134
+ })
135
+ pages = rev.get("query", {}).get("pages", [])
136
+ revs = pages[0].get("revisions") if pages else None
137
+ if not revs:
138
+ return f"No revision of '{title}' found on or before {as_of}."
139
+ params["oldid"] = revs[0]["revid"]
140
+ else:
141
+ params["page"] = title
142
+ data = _wiki_get(params)
143
+ if "error" in data:
144
+ return f"Wikipedia error: {data['error'].get('info')}. Use wikipedia_search to find the exact title."
145
+ html = data["parse"]["text"]
146
+ html = re.sub(r'<sup[^>]*class="reference".*?</sup>', "", html, flags=re.S) # drop [1] markers
147
+ md = markdownify(html, heading_style="ATX")
148
+ md = re.sub(r"\n{3,}", "\n\n", md)
149
+ return _truncate(f"# {data['parse']['title']}\n\n{md}")
150
+ except Exception as e:
151
+ return f"Failed to load Wikipedia page '{title}': {e}"
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # YouTube transcripts. YouTube often blocks requests from cloud servers, so
156
+ # this can fail on a Space; the agent is told to fall back to web search.
157
+ # ---------------------------------------------------------------------------
158
+ @tool
159
+ def youtube_transcript(url: str) -> str:
160
+ """Returns the spoken-word transcript (captions) of a YouTube video.
161
+ It cannot see the video's images, only what is said.
162
+
163
+ Args:
164
+ url: The YouTube URL or the 11-character video id.
165
+ """
166
+ m = re.search(r"(?:v=|youtu\.be/|shorts/|embed/)([\w-]{11})", url)
167
+ video_id = m.group(1) if m else url.strip()
168
+ try:
169
+ from youtube_transcript_api import YouTubeTranscriptApi
170
+
171
+ fetched = YouTubeTranscriptApi().fetch(video_id, languages=["en", "en-US", "en-GB"])
172
+ text = " ".join(snippet.text for snippet in fetched)
173
+ return _truncate(text) or "Transcript is empty."
174
+ except Exception as e:
175
+ return (
176
+ f"Transcript unavailable ({type(e).__name__}: {e}). "
177
+ "Try web_search for the video title plus the quote or topic instead."
178
+ )
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # Attached files
183
+ # ---------------------------------------------------------------------------
184
+ AUDIO_EXT = {".mp3", ".wav", ".m4a", ".flac", ".ogg"}
185
+ IMAGE_EXT = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
186
+
187
+ _whisper_model = None
188
+
189
+
190
+ @tool
191
+ def transcribe_audio(file_path: str) -> str:
192
+ """Transcribes speech in an audio file (mp3, wav, m4a, ...) to text, locally with Whisper.
193
+
194
+ Args:
195
+ file_path: Path to the audio file.
196
+ """
197
+ global _whisper_model
198
+ try:
199
+ from faster_whisper import WhisperModel
200
+
201
+ if _whisper_model is None:
202
+ size = os.getenv("WHISPER_MODEL", "base") # "small" is more accurate but slower on CPU
203
+ _whisper_model = WhisperModel(size, device="cpu", compute_type="int8")
204
+ segments, _info = _whisper_model.transcribe(file_path, beam_size=5)
205
+ return " ".join(s.text.strip() for s in segments) or "No speech detected."
206
+ except Exception as e:
207
+ return f"Transcription failed: {e}"
208
+
209
+
210
+ @tool
211
+ def read_file(file_path: str) -> str:
212
+ """Reads an attached file and returns its contents as text.
213
+ Handles text and code files, CSV, Excel (every sheet), JSON, PDF and Word documents.
214
+ Audio files are transcribed automatically. Images cannot be read as text: they are
215
+ shown to you directly with the task instead.
216
+
217
+ Args:
218
+ file_path: Path to the file.
219
+ """
220
+ p = Path(file_path)
221
+ if not p.exists():
222
+ return f"File not found: {file_path}"
223
+ ext = p.suffix.lower()
224
+ try:
225
+ if ext in AUDIO_EXT:
226
+ return transcribe_audio(file_path)
227
+ if ext in IMAGE_EXT:
228
+ return "This is an image. Look at the image attached to the task instead of reading it as text."
229
+ if ext in {".xlsx", ".xls", ".xlsm"}:
230
+ import pandas as pd
231
+
232
+ sheets = pd.read_excel(p, sheet_name=None)
233
+ parts = [
234
+ f"## Sheet: {name} ({df.shape[0]} rows x {df.shape[1]} cols)\n{df.to_csv(index=False)}"
235
+ for name, df in sheets.items()
236
+ ]
237
+ return _truncate("\n\n".join(parts))
238
+ if ext == ".pdf":
239
+ from pypdf import PdfReader
240
+
241
+ reader = PdfReader(str(p))
242
+ text = "\n\n".join((page.extract_text() or "") for page in reader.pages).strip()
243
+ return _truncate(text) or "No text could be extracted (the PDF may be scanned images)."
244
+ if ext == ".docx":
245
+ import docx
246
+
247
+ return _truncate("\n".join(par.text for par in docx.Document(str(p)).paragraphs))
248
+ return _truncate(p.read_text(encoding="utf-8", errors="replace"))
249
+ except Exception as e:
250
+ return f"Could not read {file_path}: {e}"
251
+
252
+
253
+ @tool
254
+ def run_python_file(file_path: str) -> str:
255
+ """Executes an attached Python script in a separate process and returns what it prints
256
+ (stdout and stderr). Use it when a question asks for the output of an attached .py file.
257
+
258
+ Args:
259
+ file_path: Path to the .py file.
260
+ """
261
+ try:
262
+ proc = subprocess.run(
263
+ [sys.executable, file_path], capture_output=True, text=True, timeout=120,
264
+ cwd=str(Path(file_path).parent),
265
+ )
266
+ out = proc.stdout
267
+ if proc.stderr:
268
+ out += f"\n[stderr]\n{proc.stderr}"
269
+ return _truncate(out) or "(the script printed nothing)"
270
+ except subprocess.TimeoutExpired:
271
+ return "The script ran for more than 120 seconds and was stopped."
272
+ except Exception as e:
273
+ return f"Could not run {file_path}: {e}"
274
+
275
+
276
+ def get_tools() -> list:
277
+ """All tools handed to the agent (final_answer is added by smolagents itself)."""
278
+ return [
279
+ WebSearchTool(),
280
+ VisitWebpageTool(max_output_length=MAX_CHARS),
281
+ wikipedia_search,
282
+ wikipedia_page,
283
+ youtube_transcript,
284
+ read_file,
285
+ transcribe_audio,
286
+ run_python_file,
287
+ ]