GilbertoEwaldFilho commited on
Commit
aabe38e
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -44
app.py CHANGED
@@ -4,31 +4,112 @@ 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,15 +119,17 @@ 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
 
51
  # 2. Fetch Questions
52
  print(f"Fetching questions from: {questions_url}")
@@ -55,16 +138,16 @@ 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
@@ -81,19 +164,39 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
81
  continue
82
  try:
83
  submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
 
 
 
 
 
97
  print(status_update)
98
 
99
  # 5. Submit
@@ -142,19 +245,20 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
 
@@ -162,20 +266,24 @@ with gr.Blocks() as demo:
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 +291,16 @@ 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)
 
4
  import inspect
5
  import pandas as pd
6
 
7
+ # 🔹 NOVO: imports do smolagents
8
+ from smolagents import CodeAgent, InferenceClientModel
9
+
10
  # --- Constants ---
11
+ # (mantido como no template)
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
+
15
+ # =========================================================
16
+ # Helper: limpeza de resposta para EXACT MATCH
17
+ # =========================================================
18
+ def clean_answer(text: str) -> str:
19
+ """
20
+ Limpa a saída do modelo para ficar mais adequada ao EXACT MATCH.
21
+ Remove prefixos como 'Answer:', 'Final answer:' etc.,
22
+ aspas externas e ponto final solto.
23
+ """
24
+ if text is None:
25
+ return ""
26
+
27
+ ans = str(text).strip()
28
+
29
+ # remove prefixos comuns
30
+ prefixes = [
31
+ "answer:", "resposta:", "final answer:", "final:", "ans:", "a:",
32
+ "the answer is", "the final answer is",
33
+ ]
34
+ lower = ans.lower()
35
+ for p in prefixes:
36
+ if lower.startswith(p):
37
+ ans = ans[len(p):].strip()
38
+ break
39
+
40
+ # remove ponto final se não parecer número decimal
41
+ if ans.endswith(".") and not ans.replace(".", "", 1).isdigit():
42
+ ans = ans[:-1].strip()
43
+
44
+ # remove aspas externas
45
+ if len(ans) > 1 and ans[0] == ans[-1] and ans[0] in ["'", '"']:
46
+ ans = ans[1:-1].strip()
47
+
48
+ return ans
49
+
50
+
51
+ # =========================================================
52
+ # Basic Agent Definition – AGORA usando smolagents
53
+ # =========================================================
54
+
55
+ SYSTEM_PROMPT = (
56
+ "You are an exam-taking assistant.\n"
57
+ "For each question, reply with ONLY the final answer, with no explanation, "
58
+ "no reasoning, no extra words, no quotes, and no labels like 'Final answer'.\n"
59
+ "If the answer is a number, output just the number. "
60
+ "If it is a word or short phrase, output just that.\n"
61
+ "Your output will be compared to the ground truth using EXACT MATCH."
62
+ )
63
+
64
+
65
  class BasicAgent:
66
+ """
67
+ Agente simples baseado em smolagents:
68
+ - Usa InferenceClientModel (Inference API da Hugging Face)
69
+ - Não utiliza tools adicionais
70
+ - Retorna uma string já limpa para EXACT MATCH
71
+ """
72
+
73
  def __init__(self):
74
+ print("Initializing smolagents BasicAgent...")
75
+
76
+ # Modelo remoto via Inference API (utiliza HF_TOKEN configurado no Space)
77
+ self.model = InferenceClientModel()
78
+
79
+ # CodeAgent sem ferramentas (agente simples)
80
+ self.agent = CodeAgent(
81
+ model=self.model,
82
+ tools=[], # agente simples: sem tools
83
+ max_steps=1, # sem tools, 1 passo é suficiente
84
+ system_prompt=SYSTEM_PROMPT,
85
+ )
86
+
87
  def __call__(self, question: str) -> str:
88
+ print(f"Agent received question (first 80 chars): {question[:80]}...")
89
+ try:
90
+ raw_answer = self.agent.run(question)
91
+ fixed_answer = clean_answer(raw_answer)
92
+ print(f"Agent returning cleaned answer: {fixed_answer}")
93
+ return fixed_answer
94
+ except Exception as e:
95
+ print(f"Error inside BasicAgent.__call__: {e}")
96
+ # Em caso de erro, devolve string vazia (melhor do que quebrar tudo)
97
+ return ""
98
+
99
 
100
+ # =========================================================
101
+ # Runner + submit (mantido do template, só usando BasicAgent novo)
102
+ # =========================================================
103
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
104
  """
105
  Fetches all questions, runs the BasicAgent on them, submits all answers,
106
  and displays the results.
107
  """
108
  # --- Determine HF Space Runtime URL and Repo URL ---
109
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
110
 
111
  if profile:
112
+ username = f"{profile.username}"
113
  print(f"User logged in: {username}")
114
  else:
115
  print("User not logged in.")
 
119
  questions_url = f"{api_url}/questions"
120
  submit_url = f"{api_url}/submit"
121
 
122
+ # 1. Instantiate Agent (agora nosso agente smolagents)
123
  try:
124
  agent = BasicAgent()
125
  except Exception as e:
126
  print(f"Error instantiating agent: {e}")
127
  return f"Error initializing agent: {e}", None
128
+
129
+ # In the case of an app running as a hugging Face space, this link points toward your codebase
130
+ # (useful for others so please keep it public)
131
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
132
+ print(f"Agent code URL: {agent_code}")
133
 
134
  # 2. Fetch Questions
135
  print(f"Fetching questions from: {questions_url}")
 
138
  response.raise_for_status()
139
  questions_data = response.json()
140
  if not questions_data:
141
+ print("Fetched questions list is empty.")
142
+ return "Fetched questions list is empty or invalid format.", None
143
  print(f"Fetched {len(questions_data)} questions.")
144
  except requests.exceptions.RequestException as e:
145
  print(f"Error fetching questions: {e}")
146
  return f"Error fetching questions: {e}", None
147
  except requests.exceptions.JSONDecodeError as e:
148
+ print(f"Error decoding JSON response from questions endpoint: {e}")
149
+ print(f"Response text: {response.text[:500]}")
150
+ return f"Error decoding server response for questions: {e}", None
151
  except Exception as e:
152
  print(f"An unexpected error occurred fetching questions: {e}")
153
  return f"An unexpected error occurred fetching questions: {e}", None
 
164
  continue
165
  try:
166
  submitted_answer = agent(question_text)
167
+ answers_payload.append(
168
+ {"task_id": task_id, "submitted_answer": submitted_answer}
169
+ )
170
+ results_log.append(
171
+ {
172
+ "Task ID": task_id,
173
+ "Question": question_text,
174
+ "Submitted Answer": submitted_answer,
175
+ }
176
+ )
177
  except Exception as e:
178
+ print(f"Error running agent on task {task_id}: {e}")
179
+ results_log.append(
180
+ {
181
+ "Task ID": task_id,
182
+ "Question": question_text,
183
+ "Submitted Answer": f"AGENT ERROR: {e}",
184
+ }
185
+ )
186
 
187
  if not answers_payload:
188
  print("Agent did not produce any answers to submit.")
189
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
190
 
191
+ # 4. Prepare Submission
192
+ submission_data = {
193
+ "username": username.strip(),
194
+ "agent_code": agent_code,
195
+ "answers": answers_payload,
196
+ }
197
+ status_update = (
198
+ f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
199
+ )
200
  print(status_update)
201
 
202
  # 5. Submit
 
245
 
246
  # --- Build Gradio Interface using Blocks ---
247
  with gr.Blocks() as demo:
248
+ gr.Markdown("# Basic Agent Evaluation Runner (smolagents)")
249
  gr.Markdown(
250
  """
251
  **Instructions:**
252
+ 1. This space uses a simple agent built with `smolagents` + `InferenceClientModel`.
253
+ 2. Log in to your Hugging Face account using the button below.
254
+ 3. Click **'Run Evaluation & Submit All Answers'** to fetch questions,
255
+ run the agent, submit answers, and see your score.
 
256
  ---
257
+ **Notes:**
258
+ - The correction on the server uses EXACT MATCH, so the agent is prompted
259
+ to output only the final answer (sem 'FINAL ANSWER', sem explicações).
260
+ - This template is intentionally simples; você pode adicionar tools,
261
+ melhorar o prompt, etc., se quiser subir seu score.
262
  """
263
  )
264
 
 
266
 
267
  run_button = gr.Button("Run Evaluation & Submit All Answers")
268
 
269
+ status_output = gr.Textbox(
270
+ label="Run Status / Submission Result", lines=5, interactive=False
271
+ )
272
+ results_table = gr.DataFrame(
273
+ label="Questions and Agent Answers",
274
+ wrap=True,
275
+ )
276
 
277
  run_button.click(
278
  fn=run_and_submit_all,
279
+ outputs=[status_output, results_table],
280
  )
281
 
282
  if __name__ == "__main__":
283
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
284
  # Check for SPACE_HOST and SPACE_ID at startup for information
285
  space_host_startup = os.getenv("SPACE_HOST")
286
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
287
 
288
  if space_host_startup:
289
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
291
  else:
292
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
293
 
294
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
295
  print(f"✅ SPACE_ID found: {space_id_startup}")
296
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
297
+ print(
298
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
299
+ )
300
  else:
301
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
302
 
303
+ print("-" * (60 + len(" App Starting ")) + "\n")
304
 
305
  print("Launching Gradio Interface for Basic Agent Evaluation...")
306
  demo.launch(debug=True, share=False)