xinli80 commited on
Commit
df98be1
·
verified ·
1 Parent(s): 1d361fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +475 -220
app.py CHANGED
@@ -1,16 +1,4 @@
1
- """GAIA benchmark agent built with LangGraph + HuggingFace Inference.
2
-
3
- The agent is a ReAct-style tool-calling loop driven by `Qwen/Qwen2.5-Coder-32B-Instruct`
4
- (via `HuggingFaceEndpoint` + `ChatHuggingFace`). It can search the web, query
5
- Wikipedia, fetch arbitrary pages, run Python, and download/inspect files attached
6
- to GAIA tasks.
7
-
8
- The Gradio UI is unchanged: log in with Hugging Face, click the button, the agent
9
- runs over every question returned by the scoring API and submits the answers.
10
- """
11
-
12
- from __future__ import annotations
13
-
14
  import io
15
  import os
16
  import re
@@ -18,242 +6,326 @@ import tempfile
18
  import traceback
19
  from pathlib import Path
20
  from typing import Annotated, Optional, TypedDict
 
21
 
22
  import gradio as gr
23
  import pandas as pd
24
  import requests
25
- from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun
26
- from langchain_community.utilities import (
27
- DuckDuckGoSearchAPIWrapper,
28
- WikipediaAPIWrapper,
29
- )
30
  from langchain_core.messages import AnyMessage, HumanMessage, SystemMessage
31
  from langchain_core.tools import tool
32
  from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
33
- from langgraph.graph import END, START, StateGraph
34
  from langgraph.graph.message import add_messages
35
  from langgraph.prebuilt import ToolNode, tools_condition
36
 
 
37
  # --- Constants ---
38
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
39
  DEFAULT_MODEL_ID = os.getenv("AGENT_MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")
40
- HF_TOKEN_ENV_VARS = ("HUGGINGFACEHUB_API_TOKEN", "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN")
41
  AGENT_RECURSION_LIMIT = int(os.getenv("AGENT_RECURSION_LIMIT", "30"))
42
- MAX_TOOL_OUTPUT_CHARS = 15000
43
-
44
- SYSTEM_PROMPT = """You are a meticulous research assistant solving questions from the GAIA benchmark.
45
-
46
- For every question:
47
- 1. Think step by step before acting.
48
- 2. Use the provided tools whenever they can help you find or verify a fact:
49
- - duckduckgo_search and wikipedia for general lookups
50
- - visit_webpage to read a specific URL
51
- - python_repl for math, parsing, conversions, list manipulation
52
- - download_task_file then read_file to inspect any attachment associated with the task
53
- 3. Prefer primary sources. Cross-check numbers and dates before answering.
54
- 4. If a task has an attached file, the user message will include its `task_id`;
55
- call `download_task_file(task_id)` first to obtain a local path, then `read_file`.
56
-
57
- When you are confident, output your final response as a SINGLE line in this exact form:
58
-
59
- FINAL ANSWER: <your answer>
60
-
61
- Rules for the FINAL ANSWER line:
62
- - A number, OR as few words as possible, OR a comma-separated list of numbers/strings.
63
- - For numbers: no thousands separators and no units (no $, %, etc.) unless the
64
- question explicitly asks for them.
65
- - For strings: no articles, no abbreviations (write city/country names in full),
66
- digits in plain text unless the question asks for digits.
67
- - For lists: apply the rules above to each element.
68
- - Do not wrap the answer in quotes or code fences. Do not write anything after
69
- the FINAL ANSWER line.
70
  """
71
 
72
  _FINAL_ANSWER_RE = re.compile(r"FINAL\s*ANSWER\s*:\s*(.+?)\s*$", re.IGNORECASE | re.DOTALL)
73
 
74
 
75
  def _resolve_hf_token() -> Optional[str]:
76
- for var in HF_TOKEN_ENV_VARS:
77
- token = os.getenv(var)
78
- if token:
79
- return token
80
  return None
81
 
82
 
83
- # --- Custom tools ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  @tool
85
  def visit_webpage(url: str) -> str:
86
- """Fetch a web page and return its main content converted to Markdown.
87
 
88
  Args:
89
- url: An absolute HTTP or HTTPS URL.
90
  """
91
  try:
92
  from markdownify import markdownify as md
93
- except ImportError:
94
- return "markdownify is not installed."
95
- try:
96
- resp = requests.get(
97
  url,
98
- timeout=20,
99
- headers={"User-Agent": "GAIA-Agent/1.0 (+https://huggingface.co)"},
100
  )
101
- resp.raise_for_status()
102
- text = md(resp.text)
 
 
 
 
103
  text = re.sub(r"\n{3,}", "\n\n", text).strip()
104
- return text[:MAX_TOOL_OUTPUT_CHARS]
105
  except Exception as exc:
106
- return f"Error fetching {url}: {exc}"
107
 
108
 
109
  @tool
110
- def python_repl(code: str) -> str:
111
- """Run a snippet of Python code and return whatever it prints.
112
-
113
- Use this for arithmetic, unit conversions, list/string manipulation, or any
114
- deterministic computation. The snippet runs in a fresh namespace; if you
115
- need a value back, `print` it.
116
 
117
  Args:
118
- code: Python source to execute.
 
119
  """
120
- buf = io.StringIO()
121
- namespace: dict = {}
122
  try:
123
- import contextlib
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
- with contextlib.redirect_stdout(buf):
126
- exec(code, namespace, namespace) # noqa: S102 - intentional sandboxed REPL
127
- except Exception:
128
- return f"ERROR:\n{traceback.format_exc()}\nSTDOUT:\n{buf.getvalue()}"
129
- out = buf.getvalue().strip()
130
- return out if out else "(no stdout; remember to print the value you need)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
 
133
  @tool
134
  def read_file(path: str) -> str:
135
- """Read a local file (txt/csv/json/xlsx/pdf/md/py) and return its text.
 
 
136
 
137
  Args:
138
- path: Local path obtained from `download_task_file` or similar.
139
  """
140
- p = Path(path)
141
- if not p.exists():
142
  return f"File does not exist: {path}"
143
- suffix = p.suffix.lower()
 
144
  try:
145
- if suffix in {".xlsx", ".xls"}:
146
- sheets = pd.read_excel(p, sheet_name=None)
147
- chunks = [
148
- f"--- Sheet: {name} ---\n{frame.to_csv(index=False)}"
149
- for name, frame in sheets.items()
 
 
150
  ]
151
- text = "\n\n".join(chunks)
152
- elif suffix == ".csv":
153
- text = pd.read_csv(p).to_csv(index=False)
154
- elif suffix == ".pdf":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  try:
156
  from pypdf import PdfReader
157
  except ImportError:
158
- return "pypdf is not installed; cannot read PDF."
159
- reader = PdfReader(str(p))
160
- text = "\n\n".join((page.extract_text() or "") for page in reader.pages)
161
- else:
162
- text = p.read_text(encoding="utf-8", errors="replace")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  except Exception as exc:
164
- return f"Failed to read {path}: {exc}"
165
- return text[:MAX_TOOL_OUTPUT_CHARS]
166
 
167
 
168
- def _make_download_tool(api_url: str):
169
- """Create a download tool bound to a specific scoring-API base URL."""
 
170
 
171
- @tool
172
- def download_task_file(task_id: str) -> str:
173
- """Download the file attached to a GAIA task and return the local path.
174
 
175
- Returns a message if the task has no attached file.
 
 
 
 
 
 
 
 
 
 
 
176
 
177
- Args:
178
- task_id: The GAIA task identifier (uuid-like string).
179
- """
180
- url = f"{api_url}/files/{task_id}"
181
- try:
182
- resp = requests.get(url, timeout=30)
183
- except Exception as exc:
184
- return f"Network error downloading file for task {task_id}: {exc}"
185
- if resp.status_code == 404:
186
- return f"No file is attached to task {task_id}."
187
- try:
188
- resp.raise_for_status()
189
- except Exception as exc:
190
- return f"Failed to download file for task {task_id}: {exc}"
191
 
192
- cd = resp.headers.get("Content-Disposition", "")
193
- match = re.search(r'filename="?([^";]+)"?', cd)
194
- filename = match.group(1) if match else task_id
195
- out_dir = Path(tempfile.gettempdir()) / "gaia_files"
196
- out_dir.mkdir(parents=True, exist_ok=True)
197
- out_path = out_dir / filename
198
- out_path.write_bytes(resp.content)
199
- return str(out_path)
200
 
201
- return download_task_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
 
204
- # --- LangGraph state ---
205
- class AgentState(TypedDict):
206
- """State shared between graph nodes.
207
 
208
- `messages` is appended to (not replaced) at every step thanks to
209
- the `add_messages` reducer.
210
  """
211
-
212
- messages: Annotated[list[AnyMessage], add_messages]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
 
215
- def _build_graph(chat_model_with_tools, tools, system_prompt: str):
216
- """Build the LangGraph state graph for our ReAct loop.
217
 
218
- Graph shape:
219
 
220
- START -> assistant -> (tool_calls?) -> tools -> assistant -> ...
221
- \\ /
222
- ----------- no tool calls -----------> END
223
- """
224
 
225
  def assistant(state: AgentState) -> dict:
226
- """LLM node: prepend the system prompt and call the model."""
227
- prompt_msgs = [SystemMessage(content=system_prompt), *state["messages"]]
228
- response = chat_model_with_tools.invoke(prompt_msgs)
229
- return {"messages": [response]}
230
 
231
  builder = StateGraph(AgentState)
232
  builder.add_node("assistant", assistant)
233
  builder.add_node("tools", ToolNode(tools))
234
-
235
  builder.add_edge(START, "assistant")
236
- # `tools_condition` returns "tools" if the last AIMessage has tool_calls,
237
- # otherwise it returns END.
238
  builder.add_conditional_edges("assistant", tools_condition)
239
  builder.add_edge("tools", "assistant")
240
-
241
  return builder.compile()
242
 
243
 
244
- # --- Agent ---
 
245
  class BasicAgent:
246
- """ReAct-style agent built on LangGraph with a HuggingFace-hosted LLM."""
247
-
248
- def __init__(self, api_url: str = DEFAULT_API_URL, model_id: str = DEFAULT_MODEL_ID):
249
  token = _resolve_hf_token()
250
  if not token:
251
- raise RuntimeError(
252
- "No Hugging Face token found. Set HUGGINGFACEHUB_API_TOKEN (or HF_TOKEN)."
253
- )
254
 
 
255
  llm = HuggingFaceEndpoint(
256
- repo_id=model_id,
257
  task="text-generation",
258
  max_new_tokens=1024,
259
  do_sample=False,
@@ -263,72 +335,67 @@ class BasicAgent:
263
  )
264
  chat_model = ChatHuggingFace(llm=llm)
265
 
266
- search = DuckDuckGoSearchRun(api_wrapper=DuckDuckGoSearchAPIWrapper())
 
 
 
267
  wikipedia = WikipediaQueryRun(
268
- api_wrapper=WikipediaAPIWrapper(
269
- top_k_results=2,
270
- doc_content_chars_max=4000,
271
- )
272
  )
273
- download_task_file = _make_download_tool(api_url)
274
 
275
- tools = [
276
  search,
277
  wikipedia,
278
  visit_webpage,
279
- python_repl,
 
 
280
  download_task_file,
281
  read_file,
 
282
  ]
283
-
284
- chat_with_tools = chat_model.bind_tools(tools)
285
- self.graph = _build_graph(chat_with_tools, tools, SYSTEM_PROMPT)
286
- self.model_id = model_id
287
- print(f"BasicAgent initialized with LangGraph + {model_id}.")
288
 
289
  def __call__(self, question: str, task_id: Optional[str] = None) -> str:
290
- print(f"Agent received question (first 80 chars): {question[:80]}...")
291
- user_content = (
292
- f"[task_id: {task_id}]\n{question}" if task_id else question
293
- )
294
  try:
295
  result = self.graph.invoke(
296
- {"messages": [HumanMessage(content=user_content)]},
297
  config={"recursion_limit": AGENT_RECURSION_LIMIT},
298
  )
299
  except Exception as exc:
300
- print(f"Agent failed on task {task_id}: {exc}")
301
- return f"AGENT_ERROR: {exc}"
302
-
303
- messages = result.get("messages") or []
304
- final_text = messages[-1].content if messages else ""
305
- if isinstance(final_text, list):
306
- final_text = "\n".join(
307
- part.get("text", "") if isinstance(part, dict) else str(part)
308
- for part in final_text
309
  )
310
- answer = _extract_final_answer(final_text)
311
- print(f"Agent answer for task {task_id}: {answer!r}")
312
  return answer
313
 
314
 
315
- def _extract_final_answer(text: str) -> str:
316
- """Pull the value after 'FINAL ANSWER:'; fall back to the last meaningful line."""
317
- if not text:
318
- return ""
319
- match = _FINAL_ANSWER_RE.search(text)
320
  if match:
321
  return match.group(1).strip().strip("`").rstrip(".").strip()
322
- lines = [line.strip() for line in text.strip().splitlines() if line.strip()]
323
  return lines[-1] if lines else text.strip()
324
 
325
 
326
  def run_and_submit_all(profile: gr.OAuthProfile | None):
327
  """
328
- Fetches all questions, runs the agent on them, submits all answers,
329
  and displays the results.
330
  """
331
- space_id = os.getenv("SPACE_ID")
 
332
 
333
  if profile:
334
  username = f"{profile.username}"
@@ -341,13 +408,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
341
  questions_url = f"{api_url}/questions"
342
  submit_url = f"{api_url}/submit"
343
 
344
- # 1. Instantiate Agent
345
  try:
346
  agent = BasicAgent(api_url=api_url)
347
  except Exception as e:
348
  print(f"Error instantiating agent: {e}")
349
  return f"Error initializing agent: {e}", None
350
-
351
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
352
  print(agent_code)
353
 
@@ -372,44 +439,36 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
372
  print(f"An unexpected error occurred fetching questions: {e}")
373
  return f"An unexpected error occurred fetching questions: {e}", None
374
 
375
- # 3. Run the agent on every question
376
  results_log = []
377
  answers_payload = []
378
  print(f"Running agent on {len(questions_data)} questions...")
379
- for idx, item in enumerate(questions_data, 1):
380
  task_id = item.get("task_id")
381
  question_text = item.get("question")
382
  if not task_id or question_text is None:
383
  print(f"Skipping item with missing task_id or question: {item}")
384
  continue
385
- print(f"--- [{idx}/{len(questions_data)}] task_id={task_id} ---")
386
  try:
 
387
  submitted_answer = agent(question_text, task_id=task_id)
 
 
 
 
388
  except Exception as e:
389
  print(f"Error running agent on task {task_id}: {e}")
390
- submitted_answer = f"AGENT ERROR: {e}"
391
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
392
- results_log.append(
393
- {
394
- "Task ID": task_id,
395
- "Question": question_text,
396
- "Submitted Answer": submitted_answer,
397
- }
398
- )
399
 
400
  if not answers_payload:
401
  print("Agent did not produce any answers to submit.")
402
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
403
 
404
  # 4. Prepare Submission
405
- submission_data = {
406
- "username": username.strip(),
407
- "agent_code": agent_code,
408
- "answers": answers_payload,
409
- }
410
- status_update = (
411
- f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
412
- )
413
  print(status_update)
414
 
415
  # 5. Submit
@@ -513,3 +572,199 @@ if __name__ == "__main__":
513
 
514
  print("Launching Gradio Interface for Basic Agent Evaluation...")
515
  demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
 
 
 
 
 
 
 
 
 
 
 
 
2
  import io
3
  import os
4
  import re
 
6
  import traceback
7
  from pathlib import Path
8
  from typing import Annotated, Optional, TypedDict
9
+ from urllib.parse import parse_qs, urlparse
10
 
11
  import gradio as gr
12
  import pandas as pd
13
  import requests
14
+ from langchain_community.tools import DuckDuckGoSearchResults, WikipediaQueryRun
15
+ from langchain_community.utilities import DuckDuckGoSearchAPIWrapper, WikipediaAPIWrapper
 
 
 
16
  from langchain_core.messages import AnyMessage, HumanMessage, SystemMessage
17
  from langchain_core.tools import tool
18
  from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
19
+ from langgraph.graph import START, StateGraph
20
  from langgraph.graph.message import add_messages
21
  from langgraph.prebuilt import ToolNode, tools_condition
22
 
23
+ # (Keep Constants as is)
24
  # --- Constants ---
25
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
26
  DEFAULT_MODEL_ID = os.getenv("AGENT_MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")
 
27
  AGENT_RECURSION_LIMIT = int(os.getenv("AGENT_RECURSION_LIMIT", "30"))
28
+ MAX_TOOL_OUTPUT_CHARS = int(os.getenv("MAX_TOOL_OUTPUT_CHARS", "15000"))
29
+ HF_TOKEN_ENV_VARS = ("HUGGINGFACEHUB_API_TOKEN", "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN")
30
+
31
+ SYSTEM_PROMPT = """You are a helpful assistant tasked with answering GAIA benchmark questions using tools.
32
+
33
+ Use tools aggressively when they can verify the answer: web search, Wikipedia, web pages, YouTube transcripts, task files, downloaded files, and Python calculations.
34
+ If the user message includes a task_id and the question mentions an image, spreadsheet, audio, pdf, or other attachment, first call download_task_file(task_id), then inspect it with read_file.
35
+
36
+ Report your thoughts internally through tool use, but finish your answer with the following template:
37
+ FINAL ANSWER: [YOUR FINAL ANSWER].
38
+
39
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
40
+ If you are asked for a number, don't use commas and don't use units such as $, percent sign, km, etc. unless explicitly specified.
41
+ If you are asked for a string, don't use articles or abbreviations, and write digits in plain text unless explicitly specified.
42
+ If you are asked for a comma separated list, apply the rules above for each element and ensure there is exactly one space after each comma.
43
+ Your final message should only start with "FINAL ANSWER: ", followed by the answer. Do not write anything after the final answer.
 
 
 
 
 
 
 
 
 
 
 
 
44
  """
45
 
46
  _FINAL_ANSWER_RE = re.compile(r"FINAL\s*ANSWER\s*:\s*(.+?)\s*$", re.IGNORECASE | re.DOTALL)
47
 
48
 
49
  def _resolve_hf_token() -> Optional[str]:
50
+ for var_name in HF_TOKEN_ENV_VARS:
51
+ value = os.getenv(var_name)
52
+ if value:
53
+ return value
54
  return None
55
 
56
 
57
+ def _trim(text: str, limit: int = MAX_TOOL_OUTPUT_CHARS) -> str:
58
+ if len(text) <= limit:
59
+ return text
60
+ return text[:limit] + "\n\n[TRUNCATED]"
61
+
62
+
63
+ def _safe_filename_from_response(response: requests.Response, fallback: str) -> str:
64
+ content_disposition = response.headers.get("Content-Disposition", "")
65
+ match = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^";]+)"?', content_disposition)
66
+ if match:
67
+ return Path(match.group(1)).name
68
+ parsed = urlparse(response.url)
69
+ name = Path(parsed.path).name
70
+ return name or fallback
71
+
72
+
73
  @tool
74
  def visit_webpage(url: str) -> str:
75
+ """Fetch a webpage and return readable markdown/text.
76
 
77
  Args:
78
+ url: HTTP or HTTPS URL to fetch.
79
  """
80
  try:
81
  from markdownify import markdownify as md
82
+
83
+ response = requests.get(
 
 
84
  url,
85
+ timeout=25,
86
+ headers={"User-Agent": "GAIA-Agent/1.0"},
87
  )
88
+ response.raise_for_status()
89
+ content_type = response.headers.get("Content-Type", "")
90
+ if "text/html" in content_type:
91
+ text = md(response.text)
92
+ else:
93
+ text = response.text
94
  text = re.sub(r"\n{3,}", "\n\n", text).strip()
95
+ return _trim(text)
96
  except Exception as exc:
97
+ return f"Error fetching webpage: {exc}"
98
 
99
 
100
  @tool
101
+ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
102
+ """Download a file from a URL to a temporary path and return that path.
 
 
 
 
103
 
104
  Args:
105
+ url: Direct URL to the file.
106
+ filename: Optional output filename.
107
  """
 
 
108
  try:
109
+ response = requests.get(url, timeout=45, stream=True, headers={"User-Agent": "GAIA-Agent/1.0"})
110
+ response.raise_for_status()
111
+ filename = filename or _safe_filename_from_response(response, "downloaded_file")
112
+ out_dir = Path(tempfile.gettempdir()) / "gaia_downloads"
113
+ out_dir.mkdir(parents=True, exist_ok=True)
114
+ out_path = out_dir / filename
115
+ with out_path.open("wb") as f:
116
+ for chunk in response.iter_content(chunk_size=8192):
117
+ if chunk:
118
+ f.write(chunk)
119
+ return str(out_path)
120
+ except Exception as exc:
121
+ return f"Error downloading file: {exc}"
122
 
123
+
124
+ def _make_download_task_file_tool(api_url: str):
125
+ @tool
126
+ def download_task_file(task_id: str) -> str:
127
+ """Download the file attached to a GAIA task and return the local path.
128
+
129
+ Args:
130
+ task_id: The task_id returned by the questions API.
131
+ """
132
+ try:
133
+ response = requests.get(f"{api_url}/files/{task_id}", timeout=45, stream=True)
134
+ if response.status_code == 404:
135
+ return f"No file is attached to task {task_id}."
136
+ response.raise_for_status()
137
+ filename = _safe_filename_from_response(response, task_id)
138
+ out_dir = Path(tempfile.gettempdir()) / "gaia_task_files"
139
+ out_dir.mkdir(parents=True, exist_ok=True)
140
+ out_path = out_dir / filename
141
+ with out_path.open("wb") as f:
142
+ for chunk in response.iter_content(chunk_size=8192):
143
+ if chunk:
144
+ f.write(chunk)
145
+ return str(out_path)
146
+ except Exception as exc:
147
+ return f"Error downloading task file: {exc}"
148
+
149
+ return download_task_file
150
 
151
 
152
  @tool
153
  def read_file(path: str) -> str:
154
+ """Read a local file and return text or a compact structured summary.
155
+
156
+ Supports text, csv, xlsx/xls, pdf, and basic image metadata/OCR when available.
157
 
158
  Args:
159
+ path: Local file path.
160
  """
161
+ file_path = Path(path)
162
+ if not file_path.exists():
163
  return f"File does not exist: {path}"
164
+
165
+ suffix = file_path.suffix.lower()
166
  try:
167
+ if suffix == ".csv":
168
+ df = pd.read_csv(file_path)
169
+ summary = [
170
+ f"CSV rows={len(df)}, columns={len(df.columns)}",
171
+ f"Columns: {', '.join(map(str, df.columns))}",
172
+ "Preview:",
173
+ df.head(20).to_csv(index=False),
174
  ]
175
+ return _trim("\n".join(summary))
176
+
177
+ if suffix in {".xlsx", ".xls"}:
178
+ sheets = pd.read_excel(file_path, sheet_name=None)
179
+ chunks = []
180
+ for name, df in sheets.items():
181
+ chunks.append(
182
+ "\n".join(
183
+ [
184
+ f"Sheet: {name}",
185
+ f"rows={len(df)}, columns={len(df.columns)}",
186
+ f"Columns: {', '.join(map(str, df.columns))}",
187
+ "Preview:",
188
+ df.head(20).to_csv(index=False),
189
+ ]
190
+ )
191
+ )
192
+ return _trim("\n\n---\n\n".join(chunks))
193
+
194
+ if suffix == ".pdf":
195
  try:
196
  from pypdf import PdfReader
197
  except ImportError:
198
+ return "pypdf is not installed."
199
+ reader = PdfReader(str(file_path))
200
+ text = "\n\n".join(page.extract_text() or "" for page in reader.pages)
201
+ return _trim(text)
202
+
203
+ if suffix in {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}:
204
+ try:
205
+ from PIL import Image
206
+
207
+ image = Image.open(file_path)
208
+ lines = [f"Image: {file_path.name}", f"size={image.size}", f"mode={image.mode}"]
209
+ try:
210
+ import pytesseract
211
+
212
+ ocr_text = pytesseract.image_to_string(image).strip()
213
+ if ocr_text:
214
+ lines.extend(["OCR text:", ocr_text])
215
+ else:
216
+ lines.append("OCR text: (empty)")
217
+ except Exception as exc:
218
+ lines.append(f"OCR unavailable: {exc}")
219
+ return _trim("\n".join(lines))
220
+ except Exception as exc:
221
+ return f"Error reading image: {exc}"
222
+
223
+ return _trim(file_path.read_text(encoding="utf-8", errors="replace"))
224
  except Exception as exc:
225
+ return f"Error reading file: {exc}"
 
226
 
227
 
228
+ @tool
229
+ def python_repl(code: str) -> str:
230
+ """Run Python code and return stdout or errors.
231
 
232
+ Use this for math, data wrangling, date logic, parsing, and exact computations.
 
 
233
 
234
+ Args:
235
+ code: Python code. Use print(...) for values you need returned.
236
+ """
237
+ stdout = io.StringIO()
238
+ namespace = {"pd": pd, "requests": requests, "re": re, "Path": Path}
239
+ try:
240
+ with contextlib.redirect_stdout(stdout):
241
+ exec(code, namespace, namespace) # noqa: S102 - intentional agent tool
242
+ except Exception:
243
+ return _trim(f"ERROR:\n{traceback.format_exc()}\nSTDOUT:\n{stdout.getvalue()}")
244
+ output = stdout.getvalue().strip()
245
+ return _trim(output or "(no stdout; print the result explicitly)")
246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
+ @tool
249
+ def youtube_transcript(url_or_video_id: str) -> str:
250
+ """Fetch a YouTube transcript when captions are available.
 
 
 
 
 
251
 
252
+ Args:
253
+ url_or_video_id: YouTube URL or video id.
254
+ """
255
+ try:
256
+ from youtube_transcript_api import YouTubeTranscriptApi
257
+
258
+ video_id = url_or_video_id.strip()
259
+ if "youtube.com" in video_id or "youtu.be" in video_id:
260
+ parsed = urlparse(video_id)
261
+ if parsed.netloc.endswith("youtu.be"):
262
+ video_id = parsed.path.strip("/")
263
+ else:
264
+ video_id = parse_qs(parsed.query).get("v", [video_id])[0]
265
+ transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=["en"])
266
+ text = " ".join(item.get("text", "") for item in transcript)
267
+ return _trim(text)
268
+ except Exception as exc:
269
+ return f"Could not fetch transcript: {exc}"
270
 
271
 
272
+ @tool
273
+ def arxiv_search(query: str) -> str:
274
+ """Search arXiv and return up to three compact results.
275
 
276
+ Args:
277
+ query: Search query.
278
  """
279
+ try:
280
+ from langchain_community.document_loaders import ArxivLoader
281
+
282
+ docs = ArxivLoader(query=query, load_max_docs=3).load()
283
+ if not docs:
284
+ return "No arXiv results found."
285
+ return _trim(
286
+ "\n\n---\n\n".join(
287
+ f"Title: {doc.metadata.get('Title', '')}\n"
288
+ f"Authors: {doc.metadata.get('Authors', '')}\n"
289
+ f"Published: {doc.metadata.get('Published', '')}\n"
290
+ f"Summary: {doc.page_content[:1500]}"
291
+ for doc in docs
292
+ )
293
+ )
294
+ except Exception as exc:
295
+ return f"Error searching arXiv: {exc}"
296
 
297
 
298
+ class AgentState(TypedDict):
299
+ messages: Annotated[list[AnyMessage], add_messages]
300
 
 
301
 
302
+ def build_graph(chat_model_with_tools, tools):
303
+ """Build the explicit LangGraph ReAct loop used by BasicAgent."""
 
 
304
 
305
  def assistant(state: AgentState) -> dict:
306
+ messages = [SystemMessage(content=SYSTEM_PROMPT), *state["messages"]]
307
+ return {"messages": [chat_model_with_tools.invoke(messages)]}
 
 
308
 
309
  builder = StateGraph(AgentState)
310
  builder.add_node("assistant", assistant)
311
  builder.add_node("tools", ToolNode(tools))
 
312
  builder.add_edge(START, "assistant")
 
 
313
  builder.add_conditional_edges("assistant", tools_condition)
314
  builder.add_edge("tools", "assistant")
 
315
  return builder.compile()
316
 
317
 
318
+ # --- Basic Agent Definition ---
319
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
320
  class BasicAgent:
321
+ def __init__(self, api_url: str = DEFAULT_API_URL):
 
 
322
  token = _resolve_hf_token()
323
  if not token:
324
+ raise RuntimeError("Set HUGGINGFACEHUB_API_TOKEN or HF_TOKEN in your Space secrets.")
 
 
325
 
326
+ print(f"BasicAgent initializing with LangGraph and {DEFAULT_MODEL_ID}.")
327
  llm = HuggingFaceEndpoint(
328
+ repo_id=DEFAULT_MODEL_ID,
329
  task="text-generation",
330
  max_new_tokens=1024,
331
  do_sample=False,
 
335
  )
336
  chat_model = ChatHuggingFace(llm=llm)
337
 
338
+ search = DuckDuckGoSearchResults(
339
+ api_wrapper=DuckDuckGoSearchAPIWrapper(max_results=5),
340
+ output_format="list",
341
+ )
342
  wikipedia = WikipediaQueryRun(
343
+ api_wrapper=WikipediaAPIWrapper(top_k_results=3, doc_content_chars_max=5000)
 
 
 
344
  )
345
+ download_task_file = _make_download_task_file_tool(api_url)
346
 
347
+ self.tools = [
348
  search,
349
  wikipedia,
350
  visit_webpage,
351
+ arxiv_search,
352
+ youtube_transcript,
353
+ download_file_from_url,
354
  download_task_file,
355
  read_file,
356
+ python_repl,
357
  ]
358
+ self.graph = build_graph(chat_model.bind_tools(self.tools), self.tools)
359
+ print("BasicAgent initialized.")
 
 
 
360
 
361
  def __call__(self, question: str, task_id: Optional[str] = None) -> str:
362
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
363
+ user_prompt = f"task_id: {task_id}\n\nQuestion: {question}" if task_id else question
 
 
364
  try:
365
  result = self.graph.invoke(
366
+ {"messages": [HumanMessage(content=user_prompt)]},
367
  config={"recursion_limit": AGENT_RECURSION_LIMIT},
368
  )
369
  except Exception as exc:
370
+ print(f"Agent error: {exc}")
371
+ return f"AGENT ERROR: {exc}"
372
+
373
+ content = result["messages"][-1].content
374
+ if isinstance(content, list):
375
+ content = "\n".join(
376
+ item.get("text", "") if isinstance(item, dict) else str(item)
377
+ for item in content
 
378
  )
379
+ answer = extract_final_answer(str(content))
380
+ print(f"Agent returning answer: {answer}")
381
  return answer
382
 
383
 
384
+ def extract_final_answer(text: str) -> str:
385
+ match = _FINAL_ANSWER_RE.search(text.strip())
 
 
 
386
  if match:
387
  return match.group(1).strip().strip("`").rstrip(".").strip()
388
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
389
  return lines[-1] if lines else text.strip()
390
 
391
 
392
  def run_and_submit_all(profile: gr.OAuthProfile | None):
393
  """
394
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
395
  and displays the results.
396
  """
397
+ # --- Determine HF Space Runtime URL and Repo URL ---
398
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
399
 
400
  if profile:
401
  username = f"{profile.username}"
 
408
  questions_url = f"{api_url}/questions"
409
  submit_url = f"{api_url}/submit"
410
 
411
+ # 1. Instantiate Agent ( modify this part to create your agent)
412
  try:
413
  agent = BasicAgent(api_url=api_url)
414
  except Exception as e:
415
  print(f"Error instantiating agent: {e}")
416
  return f"Error initializing agent: {e}", None
417
+ # 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)
418
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
419
  print(agent_code)
420
 
 
439
  print(f"An unexpected error occurred fetching questions: {e}")
440
  return f"An unexpected error occurred fetching questions: {e}", None
441
 
442
+ # 3. Run your Agent
443
  results_log = []
444
  answers_payload = []
445
  print(f"Running agent on {len(questions_data)} questions...")
446
+ for idx, item in enumerate(questions_data, start=1):
447
  task_id = item.get("task_id")
448
  question_text = item.get("question")
449
  if not task_id or question_text is None:
450
  print(f"Skipping item with missing task_id or question: {item}")
451
  continue
 
452
  try:
453
+ print(f"Running task {idx}/{len(questions_data)}: {task_id}")
454
  submitted_answer = agent(question_text, task_id=task_id)
455
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
456
+ results_log.append(
457
+ {"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}
458
+ )
459
  except Exception as e:
460
  print(f"Error running agent on task {task_id}: {e}")
461
+ results_log.append(
462
+ {"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"}
463
+ )
 
 
 
 
 
 
464
 
465
  if not answers_payload:
466
  print("Agent did not produce any answers to submit.")
467
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
468
 
469
  # 4. Prepare Submission
470
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
471
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
 
 
 
 
 
472
  print(status_update)
473
 
474
  # 5. Submit
 
572
 
573
  print("Launching Gradio Interface for Basic Agent Evaluation...")
574
  demo.launch(debug=True, share=False)
575
+ import os
576
+ import gradio as gr
577
+ import requests
578
+ import inspect
579
+ import pandas as pd
580
+
581
+ # (Keep Constants as is)
582
+ # --- Constants ---
583
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
584
+
585
+ # --- Basic Agent Definition ---
586
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
587
+ class BasicAgent:
588
+ def __init__(self):
589
+ print("BasicAgent initialized.")
590
+ def __call__(self, question: str) -> str:
591
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
592
+ fixed_answer = "This is a default answer."
593
+ print(f"Agent returning fixed answer: {fixed_answer}")
594
+ return fixed_answer
595
+
596
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
597
+ """
598
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
599
+ and displays the results.
600
+ """
601
+ # --- Determine HF Space Runtime URL and Repo URL ---
602
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
603
+
604
+ if profile:
605
+ username= f"{profile.username}"
606
+ print(f"User logged in: {username}")
607
+ else:
608
+ print("User not logged in.")
609
+ return "Please Login to Hugging Face with the button.", None
610
+
611
+ api_url = DEFAULT_API_URL
612
+ questions_url = f"{api_url}/questions"
613
+ submit_url = f"{api_url}/submit"
614
+
615
+ # 1. Instantiate Agent ( modify this part to create your agent)
616
+ try:
617
+ agent = BasicAgent()
618
+ except Exception as e:
619
+ print(f"Error instantiating agent: {e}")
620
+ return f"Error initializing agent: {e}", None
621
+ # 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)
622
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
623
+ print(agent_code)
624
+
625
+ # 2. Fetch Questions
626
+ print(f"Fetching questions from: {questions_url}")
627
+ try:
628
+ response = requests.get(questions_url, timeout=15)
629
+ response.raise_for_status()
630
+ questions_data = response.json()
631
+ if not questions_data:
632
+ print("Fetched questions list is empty.")
633
+ return "Fetched questions list is empty or invalid format.", None
634
+ print(f"Fetched {len(questions_data)} questions.")
635
+ except requests.exceptions.RequestException as e:
636
+ print(f"Error fetching questions: {e}")
637
+ return f"Error fetching questions: {e}", None
638
+ except requests.exceptions.JSONDecodeError as e:
639
+ print(f"Error decoding JSON response from questions endpoint: {e}")
640
+ print(f"Response text: {response.text[:500]}")
641
+ return f"Error decoding server response for questions: {e}", None
642
+ except Exception as e:
643
+ print(f"An unexpected error occurred fetching questions: {e}")
644
+ return f"An unexpected error occurred fetching questions: {e}", None
645
+
646
+ # 3. Run your Agent
647
+ results_log = []
648
+ answers_payload = []
649
+ print(f"Running agent on {len(questions_data)} questions...")
650
+ for item in questions_data:
651
+ task_id = item.get("task_id")
652
+ question_text = item.get("question")
653
+ if not task_id or question_text is None:
654
+ print(f"Skipping item with missing task_id or question: {item}")
655
+ continue
656
+ try:
657
+ submitted_answer = agent(question_text)
658
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
659
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
660
+ except Exception as e:
661
+ print(f"Error running agent on task {task_id}: {e}")
662
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
663
+
664
+ if not answers_payload:
665
+ print("Agent did not produce any answers to submit.")
666
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
667
+
668
+ # 4. Prepare Submission
669
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
670
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
671
+ print(status_update)
672
+
673
+ # 5. Submit
674
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
675
+ try:
676
+ response = requests.post(submit_url, json=submission_data, timeout=60)
677
+ response.raise_for_status()
678
+ result_data = response.json()
679
+ final_status = (
680
+ f"Submission Successful!\n"
681
+ f"User: {result_data.get('username')}\n"
682
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
683
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
684
+ f"Message: {result_data.get('message', 'No message received.')}"
685
+ )
686
+ print("Submission successful.")
687
+ results_df = pd.DataFrame(results_log)
688
+ return final_status, results_df
689
+ except requests.exceptions.HTTPError as e:
690
+ error_detail = f"Server responded with status {e.response.status_code}."
691
+ try:
692
+ error_json = e.response.json()
693
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
694
+ except requests.exceptions.JSONDecodeError:
695
+ error_detail += f" Response: {e.response.text[:500]}"
696
+ status_message = f"Submission Failed: {error_detail}"
697
+ print(status_message)
698
+ results_df = pd.DataFrame(results_log)
699
+ return status_message, results_df
700
+ except requests.exceptions.Timeout:
701
+ status_message = "Submission Failed: The request timed out."
702
+ print(status_message)
703
+ results_df = pd.DataFrame(results_log)
704
+ return status_message, results_df
705
+ except requests.exceptions.RequestException as e:
706
+ status_message = f"Submission Failed: Network error - {e}"
707
+ print(status_message)
708
+ results_df = pd.DataFrame(results_log)
709
+ return status_message, results_df
710
+ except Exception as e:
711
+ status_message = f"An unexpected error occurred during submission: {e}"
712
+ print(status_message)
713
+ results_df = pd.DataFrame(results_log)
714
+ return status_message, results_df
715
+
716
+
717
+ # --- Build Gradio Interface using Blocks ---
718
+ with gr.Blocks() as demo:
719
+ gr.Markdown("# Basic Agent Evaluation Runner")
720
+ gr.Markdown(
721
+ """
722
+ **Instructions:**
723
+
724
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
725
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
726
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
727
+
728
+ ---
729
+ **Disclaimers:**
730
+ 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).
731
+ 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.
732
+ """
733
+ )
734
+
735
+ gr.LoginButton()
736
+
737
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
738
+
739
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
740
+ # Removed max_rows=10 from DataFrame constructor
741
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
742
+
743
+ run_button.click(
744
+ fn=run_and_submit_all,
745
+ outputs=[status_output, results_table]
746
+ )
747
+
748
+ if __name__ == "__main__":
749
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
750
+ # Check for SPACE_HOST and SPACE_ID at startup for information
751
+ space_host_startup = os.getenv("SPACE_HOST")
752
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
753
+
754
+ if space_host_startup:
755
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
756
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
757
+ else:
758
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
759
+
760
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
761
+ print(f"✅ SPACE_ID found: {space_id_startup}")
762
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
763
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
764
+ else:
765
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
766
+
767
+ print("-"*(60 + len(" App Starting ")) + "\n")
768
+
769
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
770
+ demo.launch(debug=True, share=False)