Tesvia commited on
Commit
4a751ef
·
verified ·
1 Parent(s): 4f62d4c

Upload 3 files

Browse files
Files changed (3) hide show
  1. agent.py +3 -2
  2. app.py +12 -9
  3. tools.py +10 -7
agent.py CHANGED
@@ -83,9 +83,10 @@ class GAIAAgent(CodeAgent):
83
  last_step = step
84
  # If last_step is a FinalAnswerStep with .answer, return it
85
  answer = getattr(last_step, "answer", None)
 
86
  if answer is not None:
87
- return str(answer)
88
- return str(last_step)
89
 
90
  # ---------------------------------------------------------------------------
91
  # Factory helpers expected by app.py
 
83
  last_step = step
84
  # If last_step is a FinalAnswerStep with .answer, return it
85
  answer = getattr(last_step, "answer", None)
86
+ # Always return as a string, with stripping for safety
87
  if answer is not None:
88
+ return str(answer).strip()
89
+ return str(last_step).strip()
90
 
91
  # ---------------------------------------------------------------------------
92
  # Factory helpers expected by app.py
app.py CHANGED
@@ -10,7 +10,6 @@ from agent import gaia_agent
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
-
14
  def run_and_submit_all( profile: gr.OAuthProfile | None):
15
  """
16
  Fetches all questions, runs the BasicAgent on them, submits all answers,
@@ -43,21 +42,23 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
43
 
44
  # 2. Fetch Questions
45
  print(f"Fetching questions from: {questions_url}")
 
 
46
  try:
47
  response = requests.get(questions_url, timeout=15)
48
  response.raise_for_status()
49
  questions_data = response.json()
50
  if not questions_data:
51
- print("Fetched questions list is empty.")
52
- return "Fetched questions list is empty or invalid format.", None
53
  print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
54
  except requests.exceptions.RequestException as e:
55
  print(f"Error fetching questions: {e}")
56
  return f"Error fetching questions: {e}", None
57
- except requests.exceptions.JSONDecodeError as e:
58
- print(f"Error decoding JSON response from questions endpoint: {e}")
59
- print(f"Response text: {response.text[:500]}")
60
- return f"Error decoding server response for questions: {e}", None
61
  except Exception as e:
62
  print(f"An unexpected error occurred fetching questions: {e}")
63
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -74,6 +75,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
74
  continue
75
  try:
76
  submitted_answer = agent(question_text)
 
 
 
 
77
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
78
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
79
  except Exception as e:
@@ -156,7 +161,6 @@ with gr.Blocks() as demo:
156
  run_button = gr.Button("Run Evaluation & Submit All Answers")
157
 
158
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
159
- # Removed max_rows=10 from DataFrame constructor
160
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
161
 
162
  run_button.click(
@@ -166,7 +170,6 @@ with gr.Blocks() as demo:
166
 
167
  if __name__ == "__main__":
168
  print("\n" + "-"*30 + " App Starting " + "-"*30)
169
- # Check for SPACE_HOST and SPACE_ID at startup for information
170
  space_host_startup = os.getenv("SPACE_HOST")
171
  space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
172
 
 
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
 
13
  def run_and_submit_all( profile: gr.OAuthProfile | None):
14
  """
15
  Fetches all questions, runs the BasicAgent on them, submits all answers,
 
42
 
43
  # 2. Fetch Questions
44
  print(f"Fetching questions from: {questions_url}")
45
+ import json
46
+
47
  try:
48
  response = requests.get(questions_url, timeout=15)
49
  response.raise_for_status()
50
  questions_data = response.json()
51
  if not questions_data:
52
+ print("Fetched questions list is empty.")
53
+ return "Fetched questions list is empty or invalid format.", None
54
  print(f"Fetched {len(questions_data)} questions.")
55
+ except json.JSONDecodeError as e:
56
+ print(f"Error decoding JSON response from questions endpoint: {e}")
57
+ print(f"Response text: {response.text[:500]}")
58
+ return f"Error decoding server response for questions: {e}", None
59
  except requests.exceptions.RequestException as e:
60
  print(f"Error fetching questions: {e}")
61
  return f"Error fetching questions: {e}", None
 
 
 
 
62
  except Exception as e:
63
  print(f"An unexpected error occurred fetching questions: {e}")
64
  return f"An unexpected error occurred fetching questions: {e}", None
 
75
  continue
76
  try:
77
  submitted_answer = agent(question_text)
78
+ # --- DEBUG LOGGING ---
79
+ print(f"[DEBUG] Task {task_id}: Answer type: {type(submitted_answer)}, Value: {repr(submitted_answer)}")
80
+ # Force string type here just in case (defensive)
81
+ submitted_answer = str(submitted_answer).strip()
82
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
83
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
84
  except Exception as e:
 
161
  run_button = gr.Button("Run Evaluation & Submit All Answers")
162
 
163
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
164
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
165
 
166
  run_button.click(
 
170
 
171
  if __name__ == "__main__":
172
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
173
  space_host_startup = os.getenv("SPACE_HOST")
174
  space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
175
 
tools.py CHANGED
@@ -32,7 +32,9 @@ class PythonRunTool(Tool):
32
  except Exception as e:
33
  raise RuntimeError(f"PythonRunTool error: {e}") from e
34
  out = buf.getvalue()
35
- return (out + (repr(last) if last is not None else "")).strip()
 
 
36
 
37
  # ---- 2. ExcelLoaderTool ----------------------------------------------------
38
  class ExcelLoaderTool(Tool):
@@ -56,12 +58,11 @@ class ExcelLoaderTool(Tool):
56
  }
57
  output_type = "array"
58
 
59
- def forward(self, path: str, sheet: str | int | None = None) -> List[Dict[str, Any]]:
60
  import pandas as pd
61
  if not os.path.isfile(path):
62
  raise FileNotFoundError(path)
63
  ext = os.path.splitext(path)[1].lower()
64
- # Handle empty string as None for sheet
65
  if sheet == "":
66
  sheet = None
67
  if ext == ".csv":
@@ -69,7 +70,8 @@ class ExcelLoaderTool(Tool):
69
  else:
70
  df = pd.read_excel(path, sheet_name=sheet)
71
  records = [{str(k): v for k, v in row.items()} for row in df.to_dict(orient="records")]
72
- return records
 
73
 
74
  # ---- 3. YouTubeTranscriptTool ---------------------------------------------
75
  class YouTubeTranscriptTool(Tool):
@@ -98,7 +100,8 @@ class YouTubeTranscriptTool(Tool):
98
  from youtube_transcript_api._api import YouTubeTranscriptApi
99
  vid = parse_qs(urlparse(url).query).get("v", [None])[0] or url.split("/")[-1]
100
  data = YouTubeTranscriptApi.get_transcript(vid, languages=[lang, "en", "en-US", "en-GB"])
101
- return " ".join(d["text"] for d in data).strip()
 
102
 
103
  # ---- 4. AudioTranscriptionTool --------------------------------------------
104
  class AudioTranscriptionTool(Tool):
@@ -129,7 +132,7 @@ class AudioTranscriptionTool(Tool):
129
  client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
130
  with open(path, "rb") as fp:
131
  transcript = client.audio.transcriptions.create(model=model, file=fp)
132
- return transcript.text.strip()
133
 
134
  # ---- 5. SimpleOCRTool ------------------------------------------------------
135
  class SimpleOCRTool(Tool):
@@ -151,7 +154,7 @@ class SimpleOCRTool(Tool):
151
  import pytesseract
152
  if not os.path.isfile(path):
153
  raise FileNotFoundError(path)
154
- return pytesseract.image_to_string(Image.open(path)).strip()
155
 
156
  # ---------------------------------------------------------------------------
157
  __all__ = [
 
32
  except Exception as e:
33
  raise RuntimeError(f"PythonRunTool error: {e}") from e
34
  out = buf.getvalue()
35
+ # Always return a string
36
+ result = (out + (repr(last) if last is not None else "")).strip()
37
+ return str(result)
38
 
39
  # ---- 2. ExcelLoaderTool ----------------------------------------------------
40
  class ExcelLoaderTool(Tool):
 
58
  }
59
  output_type = "array"
60
 
61
+ def forward(self, path: str, sheet: str | int | None = None) -> str:
62
  import pandas as pd
63
  if not os.path.isfile(path):
64
  raise FileNotFoundError(path)
65
  ext = os.path.splitext(path)[1].lower()
 
66
  if sheet == "":
67
  sheet = None
68
  if ext == ".csv":
 
70
  else:
71
  df = pd.read_excel(path, sheet_name=sheet)
72
  records = [{str(k): v for k, v in row.items()} for row in df.to_dict(orient="records")]
73
+ # Always return a string
74
+ return str(records)
75
 
76
  # ---- 3. YouTubeTranscriptTool ---------------------------------------------
77
  class YouTubeTranscriptTool(Tool):
 
100
  from youtube_transcript_api._api import YouTubeTranscriptApi
101
  vid = parse_qs(urlparse(url).query).get("v", [None])[0] or url.split("/")[-1]
102
  data = YouTubeTranscriptApi.get_transcript(vid, languages=[lang, "en", "en-US", "en-GB"])
103
+ text = " ".join(d["text"] for d in data).strip()
104
+ return str(text)
105
 
106
  # ---- 4. AudioTranscriptionTool --------------------------------------------
107
  class AudioTranscriptionTool(Tool):
 
132
  client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
133
  with open(path, "rb") as fp:
134
  transcript = client.audio.transcriptions.create(model=model, file=fp)
135
+ return str(transcript.text.strip())
136
 
137
  # ---- 5. SimpleOCRTool ------------------------------------------------------
138
  class SimpleOCRTool(Tool):
 
154
  import pytesseract
155
  if not os.path.isfile(path):
156
  raise FileNotFoundError(path)
157
+ return str(pytesseract.image_to_string(Image.open(path)).strip())
158
 
159
  # ---------------------------------------------------------------------------
160
  __all__ = [