Miguel Figueiredo Marques Claude Opus 4.8 commited on
Commit
87033aa
·
1 Parent(s): 81917a3

Build GAIA agent (LangGraph + Groq) with tools and file handling

Browse files

Replace the stub BasicAgent with a real agent: web/wiki/arxiv search,
Python execution, file reading, audio transcription, and image analysis.
Adds attachment downloading, FINAL ANSWER parsing, and rate-limit retries.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Files changed (5) hide show
  1. .env.example +8 -0
  2. .gitignore +177 -0
  3. INSTRUCTIONS.md +91 -0
  4. app.py +325 -64
  5. requirements.txt +14 -2
.env.example ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Copy to .env for local runs. On Hugging Face, set these as Space Secrets instead.
2
+ GROQ_API_KEY=your_groq_api_key
3
+ TAVILY_API_KEY=your_tavily_api_key
4
+
5
+ # Optional overrides
6
+ # GROQ_MODEL=llama-3.3-70b-versatile
7
+ # GROQ_VISION_MODEL=meta-llama/llama-4-scout-17b-16e-instruct
8
+ # PER_QUESTION_DELAY=3
.gitignore ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
175
+
176
+ ###
177
+ /image_outputs
INSTRUCTIONS.md ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GAIA Agent — Setup & Run Instructions
2
+
3
+ A self-contained LangGraph + Groq agent for the Hugging Face Agents Course Unit 4 final
4
+ assignment. Goal: score **≥ 30% (6 / 20)** on the GAIA question subset to earn the certificate.
5
+
6
+ ## What's in here
7
+
8
+ | File | Purpose |
9
+ |---|---|
10
+ | `app.py` | The Gradio app + the agent (LangGraph ↔ Groq, 7 tools, file handling). |
11
+ | `requirements.txt` | Python dependencies. |
12
+ | `.env.example` | Template for local API keys. Copy to `.env`. |
13
+
14
+ **Agent tools:** `web_search` (Tavily), `wiki_search`, `arxiv_search`, `run_python`
15
+ (math/dates/data, pandas & numpy preloaded), `read_file` (text/CSV/Excel),
16
+ `transcribe_audio` (Groq Whisper), `analyze_image` (Groq vision).
17
+
18
+ Questions with attachments are auto-downloaded from `/files/{task_id}` and their local
19
+ path is injected into the prompt so the agent can read/transcribe/analyze them.
20
+
21
+ ## 1. Get the two free API keys
22
+
23
+ - **Groq** (the LLM): https://console.groq.com → API Keys
24
+ - **Tavily** (web search): https://app.tavily.com → API key
25
+
26
+ ## 2. Test locally
27
+
28
+ This machine blocks system-wide `pip` (PEP 668 "externally-managed-environment"), so use a
29
+ virtual environment:
30
+
31
+ ```bash
32
+ cd Final_Assignment_Template
33
+ python3 -m venv .venv
34
+ ./.venv/bin/pip install -r requirements.txt
35
+ cp .env.example .env # then paste your keys into .env
36
+ ```
37
+
38
+ **Smoke-test the agent** (no HF login needed — uses your keys from `.env`):
39
+
40
+ ```bash
41
+ ./.venv/bin/python -c "from app import BasicAgent; print(BasicAgent()('What is the capital of France?'))"
42
+ ```
43
+
44
+ **Launch the full Gradio UI locally** (optional). The HF login button requires your machine
45
+ to be HF-authenticated, so first set a token, then run:
46
+
47
+ ```bash
48
+ export HF_TOKEN=hf_your_token_here # from https://huggingface.co/settings/tokens
49
+ ./.venv/bin/python app.py # opens http://localhost:7860
50
+ ```
51
+
52
+ > Note: `requirements.txt` pins `gradio[oauth]` (needed for the login button) and the Gradio
53
+ > UI is built lazily inside `build_demo()`, so `import app` works for testing without
54
+ > triggering OAuth.
55
+
56
+ ## 3. Deploy to a public Hugging Face Space (required for the certificate)
57
+
58
+ The submission link must point to a **public** Space repo, or the score won't count.
59
+
60
+ 1. Create a new **Gradio** Space (or "Duplicate" the template space) and push these files.
61
+ 2. In the Space's **Settings → Secrets**, add:
62
+ - `GROQ_API_KEY`
63
+ - `TAVILY_API_KEY`
64
+ 3. Open the Space, click **Login** with the HF button, then
65
+ **Run Evaluation & Submit All Answers**. A full run takes several minutes.
66
+
67
+ ## Configuration (optional)
68
+
69
+ Set these as env vars / Space secrets to override defaults:
70
+
71
+ | Variable | Default | Notes |
72
+ |---|---|---|
73
+ | `GROQ_MODEL` | `llama-3.3-70b-versatile` | Main reasoning + tool-calling model. |
74
+ | `GROQ_VISION_MODEL` | `meta-llama/llama-4-scout-17b-16e-instruct` | Image questions. Update if retired. |
75
+ | `PER_QUESTION_DELAY` | `3` | Seconds between questions. Raise to `15` if rate-limited. |
76
+
77
+ ## Troubleshooting
78
+
79
+ - **Rate-limit / 429 errors:** Groq free tier has a tokens-per-minute cap. The agent
80
+ retries with backoff, but if runs still fail, raise `PER_QUESTION_DELAY`.
81
+ - **Vision tool errors:** if Groq retires the vision model, set `GROQ_VISION_MODEL` to a
82
+ current vision-capable model id from the Groq console.
83
+ - **Low score:** 30% is the pass bar, not a ceiling. Audio/image questions are best-effort.
84
+ Improving search quality and adding question-specific reasoning is where extra points come from.
85
+
86
+ ## How the answer format works
87
+
88
+ GAIA grades by exact match. The system prompt forces every answer to end with
89
+ `FINAL ANSWER: [x]`, and `extract_final_answer()` in `app.py` parses the text after it.
90
+ `x` must be a number (no commas/units), as-few-words-as-possible string (no articles or
91
+ abbreviations), or a comma-separated list with one space after each comma.
app.py CHANGED
@@ -1,34 +1,290 @@
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.")
@@ -38,13 +294,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
 
@@ -55,43 +310,54 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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)
@@ -121,61 +387,55 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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}")
@@ -183,14 +443,15 @@ if __name__ == "__main__":
183
  else:
184
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
  print(f"✅ SPACE_ID found: {space_id_startup}")
188
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
  else:
191
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
 
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
 
1
  import os
2
+ import re
3
+ import time
4
+ import base64
5
+ import tempfile
6
+ import io
7
+ import contextlib
8
+
9
  import gradio as gr
10
  import requests
 
11
  import pandas as pd
12
+ from dotenv import load_dotenv
13
+
14
+ from langchain_core.messages import SystemMessage, HumanMessage
15
+ from langchain_core.tools import tool
16
+ from langchain_groq import ChatGroq
17
+ from langgraph.graph import START, StateGraph, MessagesState
18
+ from langgraph.prebuilt import ToolNode, tools_condition
19
+
20
+ load_dotenv()
21
 
 
22
  # --- Constants ---
23
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
24
+ # Main reasoning + tool-calling model (Groq free tier). Swap if a model is retired.
25
+ MODEL_NAME = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
26
+ # Vision model for image questions (best-effort; update id if Groq retires it).
27
+ VISION_MODEL = os.getenv("GROQ_VISION_MODEL", "meta-llama/llama-4-scout-17b-16e-instruct")
28
+ # Seconds to pause between questions to stay under Groq free-tier rate limits.
29
+ PER_QUESTION_DELAY = float(os.getenv("PER_QUESTION_DELAY", "3"))
30
+
31
+ SYSTEM_PROMPT = (
32
+ "You are a precise general AI assistant solving questions from the GAIA benchmark. "
33
+ "Use the available tools to look things up, run calculations, and inspect any files "
34
+ "attached to the question. Reason step by step and verify facts with tools rather than "
35
+ "guessing.\n\n"
36
+ "When a question has an attached file, its local path is given to you. Use read_file, "
37
+ "run_python, transcribe_audio, or analyze_image (whichever fits) to read it before answering.\n\n"
38
+ "Finish your answer with the exact template:\n"
39
+ "FINAL ANSWER: [YOUR FINAL ANSWER]\n\n"
40
+ "YOUR FINAL ANSWER must be a number OR as few words as possible OR a comma separated list "
41
+ "of numbers and/or strings. If asked for a number, don't use commas or units (e.g. $, %) "
42
+ "unless told to. If asked for a string, don't use articles or abbreviations (e.g. for cities) "
43
+ "and write digits in plain text unless told otherwise. For a comma separated list, apply these "
44
+ "rules to each element and put exactly one space after each comma."
45
+ )
46
+
47
+
48
+ # =============== TOOLS =============== #
49
+
50
+ @tool
51
+ def web_search(query: str) -> str:
52
+ """Search the web with Tavily and return the top results (title, url, content snippet).
53
+ Use for current events, facts, and anything not in Wikipedia.
54
+
55
+ Args:
56
+ query: The search query."""
57
+ try:
58
+ from tavily import TavilyClient
59
+ client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
60
+ res = client.search(query, max_results=3)
61
+ out = []
62
+ for r in res.get("results", []):
63
+ out.append(
64
+ f'<result title="{r.get("title", "")}" url="{r.get("url", "")}">\n'
65
+ f'{r.get("content", "")}\n</result>'
66
+ )
67
+ return "\n\n---\n\n".join(out) if out else "No results found."
68
+ except Exception as e:
69
+ return f"web_search error: {e}"
70
+
71
+
72
+ @tool
73
+ def wiki_search(query: str) -> str:
74
+ """Search Wikipedia and return up to 2 article extracts. Use for encyclopedic facts.
75
+
76
+ Args:
77
+ query: The search query."""
78
+ try:
79
+ from langchain_community.document_loaders import WikipediaLoader
80
+ docs = WikipediaLoader(query=query, load_max_docs=2).load()
81
+ return "\n\n---\n\n".join(
82
+ f'<Document source="{d.metadata.get("source", "")}">\n{d.page_content[:4000]}\n</Document>'
83
+ for d in docs
84
+ ) or "No Wikipedia results."
85
+ except Exception as e:
86
+ return f"wiki_search error: {e}"
87
+
88
+
89
+ @tool
90
+ def arxiv_search(query: str) -> str:
91
+ """Search arXiv for academic papers and return up to 3 abstracts.
92
+
93
+ Args:
94
+ query: The search query."""
95
+ try:
96
+ from langchain_community.document_loaders import ArxivLoader
97
+ docs = ArxivLoader(query=query, load_max_docs=3).load()
98
+ return "\n\n---\n\n".join(
99
+ f'<Paper source="{d.metadata.get("source", "")}">\n{d.page_content[:1500]}\n</Paper>'
100
+ for d in docs
101
+ ) or "No arXiv results."
102
+ except Exception as e:
103
+ return f"arxiv_search error: {e}"
104
+
105
+
106
+ @tool
107
+ def run_python(code: str) -> str:
108
+ """Execute Python code and return whatever it prints to stdout. pandas (pd), numpy (np)
109
+ and the standard library are available. Use print() to output results. Great for math,
110
+ date arithmetic, string processing, and analyzing downloaded CSV/Excel files.
111
+
112
+ Args:
113
+ code: The Python source code to run."""
114
+ import numpy as np
115
+ buf = io.StringIO()
116
+ env = {"__name__": "__main__", "pd": pd, "np": np}
117
+ try:
118
+ with contextlib.redirect_stdout(buf):
119
+ exec(code, env)
120
+ out = buf.getvalue()
121
+ return out if out.strip() else "(ran successfully, but nothing was printed — use print())"
122
+ except Exception as e:
123
+ return f"run_python error: {e}"
124
+
125
+
126
+ @tool
127
+ def read_file(path: str) -> str:
128
+ """Read a local file and return its contents or a preview. Handles text, json, code,
129
+ CSV and Excel (returns column info + a preview for tabular files).
130
+
131
+ Args:
132
+ path: The local filesystem path to the file."""
133
+ try:
134
+ if not os.path.exists(path):
135
+ return f"File not found: {path}"
136
+ ext = os.path.splitext(path)[1].lower()
137
+ if ext in (".csv",):
138
+ df = pd.read_csv(path)
139
+ return f"CSV {df.shape[0]} rows x {df.shape[1]} cols. Columns: {list(df.columns)}\n\n{df.head(20).to_string()}"
140
+ if ext in (".xlsx", ".xls"):
141
+ df = pd.read_excel(path)
142
+ return f"Excel {df.shape[0]} rows x {df.shape[1]} cols. Columns: {list(df.columns)}\n\n{df.head(20).to_string()}"
143
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
144
+ content = f.read()
145
+ return content[:8000] + ("\n...[truncated]" if len(content) > 8000 else "")
146
+ except Exception as e:
147
+ return f"read_file error: {e}"
148
+
149
+
150
+ @tool
151
+ def transcribe_audio(path: str) -> str:
152
+ """Transcribe an audio file (mp3, wav, m4a, etc.) to text using Whisper.
153
+ Use for questions that attach a voice recording.
154
+
155
+ Args:
156
+ path: The local path to the audio file."""
157
+ try:
158
+ from groq import Groq
159
+ client = Groq()
160
+ with open(path, "rb") as f:
161
+ tr = client.audio.transcriptions.create(
162
+ file=(os.path.basename(path), f.read()),
163
+ model="whisper-large-v3",
164
+ )
165
+ return tr.text
166
+ except Exception as e:
167
+ return f"transcribe_audio error: {e}"
168
+
169
+
170
+ @tool
171
+ def analyze_image(path: str, question: str) -> str:
172
+ """Analyze an image to answer a question about it (objects, text, chess positions, charts).
173
+
174
+ Args:
175
+ path: The local path to the image file.
176
+ question: What you want to know about the image."""
177
+ try:
178
+ from groq import Groq
179
+ client = Groq()
180
+ with open(path, "rb") as f:
181
+ b64 = base64.b64encode(f.read()).decode()
182
+ ext = (os.path.splitext(path)[1].lstrip(".") or "png").lower()
183
+ resp = client.chat.completions.create(
184
+ model=VISION_MODEL,
185
+ temperature=0,
186
+ messages=[{
187
+ "role": "user",
188
+ "content": [
189
+ {"type": "text", "text": question},
190
+ {"type": "image_url", "image_url": {"url": f"data:image/{ext};base64,{b64}"}},
191
+ ],
192
+ }],
193
+ )
194
+ return resp.choices[0].message.content
195
+ except Exception as e:
196
+ return f"analyze_image error: {e}"
197
+
198
+
199
+ TOOLS = [
200
+ web_search,
201
+ wiki_search,
202
+ arxiv_search,
203
+ run_python,
204
+ read_file,
205
+ transcribe_audio,
206
+ analyze_image,
207
+ ]
208
+
209
+
210
+ # =============== GRAPH =============== #
211
+
212
+ def build_graph():
213
+ """Build a simple assistant <-> tools LangGraph agent."""
214
+ llm = ChatGroq(model=MODEL_NAME, temperature=0)
215
+ llm_with_tools = llm.bind_tools(TOOLS)
216
+
217
+ def assistant(state: MessagesState):
218
+ return {"messages": [llm_with_tools.invoke(state["messages"])]}
219
+
220
+ builder = StateGraph(MessagesState)
221
+ builder.add_node("assistant", assistant)
222
+ builder.add_node("tools", ToolNode(TOOLS))
223
+ builder.add_edge(START, "assistant")
224
+ builder.add_conditional_edges("assistant", tools_condition)
225
+ builder.add_edge("tools", "assistant")
226
+ return builder.compile()
227
+
228
+
229
+ def extract_final_answer(text) -> str:
230
+ """Pull the text after 'FINAL ANSWER:' and clean light formatting."""
231
+ if isinstance(text, list):
232
+ text = " ".join(str(t) for t in text)
233
+ text = str(text)
234
+ m = re.search(r"FINAL ANSWER:\s*(.*)", text, re.IGNORECASE | re.DOTALL)
235
+ ans = (m.group(1) if m else text).strip()
236
+ return ans.strip().strip('"').strip("*").strip()
237
+
238
 
 
 
239
  class BasicAgent:
240
+ """LangGraph + Groq agent for the GAIA questions."""
241
+
242
  def __init__(self):
243
  print("BasicAgent initialized.")
244
+ self.graph = build_graph()
245
+
246
  def __call__(self, question: str) -> str:
247
+ print(f"Agent received question (first 80 chars): {question[:80]}...")
248
+ messages = [SystemMessage(content=SYSTEM_PROMPT), HumanMessage(content=question)]
249
+ for attempt in range(3):
250
+ try:
251
+ result = self.graph.invoke({"messages": messages}, {"recursion_limit": 30})
252
+ answer = extract_final_answer(result["messages"][-1].content)
253
+ print(f"Agent returning: {answer[:120]}")
254
+ return answer
255
+ except Exception as e:
256
+ msg = str(e).lower()
257
+ if ("rate" in msg or "429" in msg) and attempt < 2:
258
+ wait = 25 * (attempt + 1)
259
+ print(f"Rate limited; waiting {wait}s and retrying...")
260
+ time.sleep(wait)
261
+ continue
262
+ raise
263
+
264
+
265
+ def _download_task_file(api_url: str, task_id: str, file_name: str) -> str | None:
266
+ """Download a file attached to a task into a temp dir. Returns the local path or None."""
267
+ try:
268
+ r = requests.get(f"{api_url}/files/{task_id}", timeout=60)
269
+ r.raise_for_status()
270
+ local = os.path.join(tempfile.gettempdir(), file_name or f"{task_id}.bin")
271
+ with open(local, "wb") as f:
272
+ f.write(r.content)
273
+ return local
274
+ except Exception as e:
275
+ print(f"Could not download file for task {task_id}: {e}")
276
+ return None
277
 
278
+
279
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
280
  """
281
+ Fetches all questions, runs the agent on them, submits all answers,
282
  and displays the results.
283
  """
284
+ space_id = os.getenv("SPACE_ID")
 
285
 
286
  if profile:
287
+ username = f"{profile.username}"
288
  print(f"User logged in: {username}")
289
  else:
290
  print("User not logged in.")
 
294
  questions_url = f"{api_url}/questions"
295
  submit_url = f"{api_url}/submit"
296
 
297
+ # 1. Instantiate Agent
298
  try:
299
  agent = BasicAgent()
300
  except Exception as e:
301
  print(f"Error instantiating agent: {e}")
302
  return f"Error initializing agent: {e}", None
 
303
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
304
  print(agent_code)
305
 
 
310
  response.raise_for_status()
311
  questions_data = response.json()
312
  if not questions_data:
313
+ print("Fetched questions list is empty.")
314
+ return "Fetched questions list is empty or invalid format.", None
315
  print(f"Fetched {len(questions_data)} questions.")
316
  except requests.exceptions.RequestException as e:
317
  print(f"Error fetching questions: {e}")
318
  return f"Error fetching questions: {e}", None
 
 
 
 
319
  except Exception as e:
320
  print(f"An unexpected error occurred fetching questions: {e}")
321
  return f"An unexpected error occurred fetching questions: {e}", None
322
 
323
+ # 3. Run the Agent
324
  results_log = []
325
  answers_payload = []
326
  print(f"Running agent on {len(questions_data)} questions...")
327
  for item in questions_data:
328
  task_id = item.get("task_id")
329
  question_text = item.get("question")
330
+ file_name = item.get("file_name")
331
  if not task_id or question_text is None:
332
  print(f"Skipping item with missing task_id or question: {item}")
333
  continue
334
+
335
+ prompt = question_text
336
+ if file_name:
337
+ local = _download_task_file(api_url, task_id, file_name)
338
+ if local:
339
+ prompt = (
340
+ f"{question_text}\n\n[A file is attached to this task. "
341
+ f"It has been downloaded to local path: {local}. "
342
+ f"Use read_file / run_python / transcribe_audio / analyze_image to inspect it.]"
343
+ )
344
+
345
  try:
346
+ submitted_answer = agent(prompt)
347
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
348
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
349
  except Exception as e:
350
+ print(f"Error running agent on task {task_id}: {e}")
351
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
352
+
353
+ if PER_QUESTION_DELAY > 0:
354
+ time.sleep(PER_QUESTION_DELAY)
355
 
356
  if not answers_payload:
357
  print("Agent did not produce any answers to submit.")
358
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
359
 
360
+ # 4. Prepare Submission
361
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
362
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
363
  print(status_update)
 
387
  error_detail += f" Response: {e.response.text[:500]}"
388
  status_message = f"Submission Failed: {error_detail}"
389
  print(status_message)
390
+ return status_message, pd.DataFrame(results_log)
 
391
  except requests.exceptions.Timeout:
392
  status_message = "Submission Failed: The request timed out."
393
  print(status_message)
394
+ return status_message, pd.DataFrame(results_log)
 
395
  except requests.exceptions.RequestException as e:
396
  status_message = f"Submission Failed: Network error - {e}"
397
  print(status_message)
398
+ return status_message, pd.DataFrame(results_log)
 
399
  except Exception as e:
400
  status_message = f"An unexpected error occurred during submission: {e}"
401
  print(status_message)
402
+ return status_message, pd.DataFrame(results_log)
 
403
 
404
 
405
  # --- Build Gradio Interface using Blocks ---
406
+ # Built inside a function so that `import app` (e.g. for local agent testing) does not
407
+ # trigger Gradio's OAuth routes, which require an HF login when run outside a Space.
408
+ def build_demo():
409
+ with gr.Blocks() as demo:
410
+ gr.Markdown("# GAIA Agent Evaluation Runner")
411
+ gr.Markdown(
412
+ """
413
+ **Instructions:**
414
 
415
+ 1. Set the `GROQ_API_KEY` and `TAVILY_API_KEY` secrets in this Space (Settings → Secrets).
416
+ 2. Log in to your Hugging Face account using the button below.
417
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, submit, and see the score.
418
+
419
+ ---
420
+ **Note:** A full run takes several minutes (the agent calls tools per question and pauses to respect rate limits).
421
+ """
422
+ )
423
 
424
+ gr.LoginButton()
 
 
 
 
 
425
 
426
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
427
 
428
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
429
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
430
 
431
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
432
+ return demo
 
433
 
 
 
 
 
434
 
435
  if __name__ == "__main__":
436
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
 
437
  space_host_startup = os.getenv("SPACE_HOST")
438
+ space_id_startup = os.getenv("SPACE_ID")
439
 
440
  if space_host_startup:
441
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
443
  else:
444
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
445
 
446
+ if space_id_startup:
447
  print(f"✅ SPACE_ID found: {space_id_startup}")
448
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
449
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
450
  else:
451
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
452
 
453
+ print("-" * (60 + len(" App Starting ")) + "\n")
454
 
455
+ print("Launching Gradio Interface for GAIA Agent Evaluation...")
456
+ demo = build_demo()
457
+ demo.launch(debug=True, share=False)
requirements.txt CHANGED
@@ -1,2 +1,14 @@
1
- gradio
2
- requests
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio[oauth]
2
+ requests
3
+ python-dotenv
4
+ langchain-core
5
+ langchain-community
6
+ langchain-groq
7
+ langgraph
8
+ groq
9
+ tavily-python
10
+ wikipedia
11
+ arxiv
12
+ pandas
13
+ numpy
14
+ openpyxl