YajieXu commited on
Commit
28371a0
·
verified ·
1 Parent(s): efdf4d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -20
app.py CHANGED
@@ -1,16 +1,16 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- from smolagents import HfApiModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool
5
- import pandas as pd
6
- import tempfile
7
  from pathlib import Path
 
 
8
  import re
9
 
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
- # --- File Handling ---
14
  def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
15
  url = f"{base_api_url}/files/{task_id}"
16
  try:
@@ -20,12 +20,14 @@ def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
20
  resp.raise_for_status()
21
  except requests.exceptions.HTTPError as e:
22
  raise e
 
23
  cdisp = resp.headers.get("content-disposition", "")
24
  filename = task_id
25
  if "filename=" in cdisp:
26
  m = re.search(r'filename="([^\"]+)"', cdisp)
27
  if m:
28
  filename = m.group(1)
 
29
  tmp_dir = Path(tempfile.gettempdir()) / "gaia_files"
30
  tmp_dir.mkdir(exist_ok=True)
31
  file_path = tmp_dir / filename
@@ -33,31 +35,26 @@ def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
33
  f.write(resp.content)
34
  return str(file_path)
35
 
36
- # --- Basic Agent Definition ---
37
  class BasicAgent:
38
  def __init__(self):
39
- model=OpenAIServerModel(model_id="gpt-4o"),
40
  self.agent = CodeAgent(
41
- model=model,
42
  tools=[DuckDuckGoSearchTool(), WikipediaSearchTool()],
43
  add_base_tools=True,
44
- additional_authorized_imports=['pandas']
45
  )
46
  print("BasicAgent initialized.")
47
 
48
  def __call__(self, question: str) -> str:
49
  print(f"Agent received question (first 50 chars): {question[:50]}...")
50
- try:
51
- fixed_answer = self.agent.run(question)
52
- print(f"Agent returning answer: {fixed_answer}")
53
- return fixed_answer
54
- except Exception as e:
55
- print(f"Error during inference: {e}")
56
- return f"AGENT ERROR: {e}"
57
 
58
- # --- Run and Submit ---
59
  def run_and_submit_all(profile: gr.OAuthProfile | None):
60
- space_id = "YajieXu/Final_Assignment_Template"
61
  if profile:
62
  username = f"{profile.username}"
63
  else:
@@ -86,16 +83,20 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
86
  for item in questions_data:
87
  task_id = item.get("task_id")
88
  question_text = item.get("question")
 
89
  try:
90
  file_path = download_file_if_any(api_url, task_id)
91
  except Exception as e:
92
  file_path = None
 
93
 
94
- q_for_agent = f"{question_text}\n\n---\nFile: {file_path}\n---\n" if file_path else question_text
 
 
 
95
 
96
  if not task_id or question_text is None:
97
  continue
98
-
99
  try:
100
  submitted_answer = agent(q_for_agent)
101
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
@@ -123,7 +124,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
123
  except Exception as e:
124
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
125
 
126
- # --- UI ---
127
  with gr.Blocks() as demo:
128
  gr.Markdown("# Basic Agent Evaluation Runner")
129
  gr.Markdown("""
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool
 
 
5
  from pathlib import Path
6
+ import tempfile
7
+ import pandas as pd
8
  import re
9
 
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
+ # --- File Download Helper ---
14
  def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
15
  url = f"{base_api_url}/files/{task_id}"
16
  try:
 
20
  resp.raise_for_status()
21
  except requests.exceptions.HTTPError as e:
22
  raise e
23
+
24
  cdisp = resp.headers.get("content-disposition", "")
25
  filename = task_id
26
  if "filename=" in cdisp:
27
  m = re.search(r'filename="([^\"]+)"', cdisp)
28
  if m:
29
  filename = m.group(1)
30
+
31
  tmp_dir = Path(tempfile.gettempdir()) / "gaia_files"
32
  tmp_dir.mkdir(exist_ok=True)
33
  file_path = tmp_dir / filename
 
35
  f.write(resp.content)
36
  return str(file_path)
37
 
38
+ # --- Basic Agent ---
39
  class BasicAgent:
40
  def __init__(self):
 
41
  self.agent = CodeAgent(
42
+ model=OpenAIServerModel(model_id="gpt-4o"),
43
  tools=[DuckDuckGoSearchTool(), WikipediaSearchTool()],
44
  add_base_tools=True,
45
+ additional_authorized_imports=[]
46
  )
47
  print("BasicAgent initialized.")
48
 
49
  def __call__(self, question: str) -> str:
50
  print(f"Agent received question (first 50 chars): {question[:50]}...")
51
+ fixed_answer = self.agent.run(question)
52
+ print(f"Agent returning answer: {fixed_answer}")
53
+ return fixed_answer
 
 
 
 
54
 
55
+ # --- Evaluation Logic ---
56
  def run_and_submit_all(profile: gr.OAuthProfile | None):
57
+ space_id = "l3xv/Final_Assignment_Template"
58
  if profile:
59
  username = f"{profile.username}"
60
  else:
 
83
  for item in questions_data:
84
  task_id = item.get("task_id")
85
  question_text = item.get("question")
86
+
87
  try:
88
  file_path = download_file_if_any(api_url, task_id)
89
  except Exception as e:
90
  file_path = None
91
+ print(f"[file fetch error] {task_id}: {e}")
92
 
93
+ q_for_agent = (
94
+ f"{question_text}\n\n---\nA file was downloaded for this task and saved locally at:\n{file_path}\n---\n\n"
95
+ if file_path else question_text
96
+ )
97
 
98
  if not task_id or question_text is None:
99
  continue
 
100
  try:
101
  submitted_answer = agent(q_for_agent)
102
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
 
124
  except Exception as e:
125
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
126
 
127
+ # --- Gradio UI ---
128
  with gr.Blocks() as demo:
129
  gr.Markdown("# Basic Agent Evaluation Runner")
130
  gr.Markdown("""