Diego-Fco commited on
Commit
aa9a022
·
verified ·
1 Parent(s): 9c0fdc9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -175
app.py CHANGED
@@ -1,249 +1,139 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
-
7
- # add ->
8
  from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool
9
- # <- add
10
 
11
- # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
- # --- Basic Agent Definition ---
16
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
17
  class BasicAgent:
18
  def __init__(self):
19
- print("BasicAgent initialized.")
 
20
 
21
- # 1. Definimos el modelo
22
- # Usamos Qwen 2.5 Coder, excelente para seguir instrucciones lógicas
23
- # model_id = "meta-llama/Llama-3.3-70B-Instruct"
24
- model_id = "qwen/Qwen2.5-Coder-32B-Instruct"
25
-
26
- # 2. Definimos la herramienta de búsqueda
27
  search_tool = DuckDuckGoSearchTool()
28
 
29
- # 3. Inicializamos el modelo con la clase NUEVA (InferenceClientModel)
30
  self.model = InferenceClientModel(
31
  model_id=model_id,
32
  token=os.getenv("HF_TOKEN")
33
  )
34
 
35
- # 4. Creamos el agente
36
- # CodeAgent es ideal porque puede escribir código Python para resolver tareas complejas
37
  self.agent = CodeAgent(
38
  tools=[search_tool],
39
  model=self.model,
40
- max_steps=7,
41
- verbosity_level=1
 
42
  )
43
 
44
  def __call__(self, question: str) -> str:
45
- print(f"Agent received question: {question}")
46
-
47
- prompt = f"""
48
- IMPORTANT INSTRUCTIONS:
49
- 1. Use Python code or Search ONLY if needed.
50
- 2. Once you have the answer, print it clearly.
51
- 3. CRITICAL: The final return value must be a CLEAN string.
52
- - NO markdown formatting (no **bold**, no `code`).
53
- - NO explanations like "The answer is".
54
- - Just the raw data (e.g., "14", "Paris", "apple, banana").
55
-
56
- Answer the following question as accurately as possible.
57
  QUESTION: {question}
 
 
 
 
 
 
 
 
58
  """
59
 
60
  try:
61
- # Ejecutar el agente
62
  answer = self.agent.run(prompt)
63
  clean = str(answer).strip()
64
-
65
- if "<code>" in clean or "Calling tools:" in clean:
66
- return "Agent Error: Output contains raw code"
67
-
68
- return clean
 
69
 
70
  except Exception as e:
71
  print(f"Error executing agent: {e}")
72
  return "Error parsing answer"
73
-
74
 
75
- def run_and_submit_all( profile: gr.OAuthProfile | None):
76
- """
77
- Fetches all questions, runs the BasicAgent on them, submits all answers,
78
- and displays the results.
79
- """
80
- # --- Determine HF Space Runtime URL and Repo URL ---
81
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
82
 
83
  if profile:
84
- username= f"{profile.username}"
85
  print(f"User logged in: {username}")
86
  else:
87
- print("User not logged in.")
88
  return "Please Login to Hugging Face with the button.", None
89
 
90
  api_url = DEFAULT_API_URL
91
  questions_url = f"{api_url}/questions"
92
  submit_url = f"{api_url}/submit"
 
 
93
 
94
- # 1. Instantiate Agent ( modify this part to create your agent)
95
- try:
96
- agent = BasicAgent()
97
- except Exception as e:
98
- print(f"Error instantiating agent: {e}")
99
- return f"Error initializing agent: {e}", None
100
- # 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)
101
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
102
- print(agent_code)
103
-
104
- # 2. Fetch Questions
105
- print(f"Fetching questions from: {questions_url}")
106
  try:
107
  response = requests.get(questions_url, timeout=15)
108
- response.raise_for_status()
109
  questions_data = response.json()
110
- if not questions_data:
111
- print("Fetched questions list is empty.")
112
- return "Fetched questions list is empty or invalid format.", None
113
- print(f"Fetched {len(questions_data)} questions.")
114
- except requests.exceptions.RequestException as e:
115
- print(f"Error fetching questions: {e}")
116
- return f"Error fetching questions: {e}", None
117
- except requests.exceptions.JSONDecodeError as e:
118
- print(f"Error decoding JSON response from questions endpoint: {e}")
119
- print(f"Response text: {response.text[:500]}")
120
- return f"Error decoding server response for questions: {e}", None
121
  except Exception as e:
122
- print(f"An unexpected error occurred fetching questions: {e}")
123
- return f"An unexpected error occurred fetching questions: {e}", None
124
 
125
- # 3. Run your Agent
126
  results_log = []
127
  answers_payload = []
 
128
  print(f"Running agent on {len(questions_data)} questions...")
 
 
129
  for item in questions_data:
130
  task_id = item.get("task_id")
131
  question_text = item.get("question")
132
- if not task_id or question_text is None:
133
- print(f"Skipping item with missing task_id or question: {item}")
134
- continue
 
135
  try:
136
- submitted_answer = agent(question_text)
 
 
 
 
 
 
 
 
 
 
137
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
138
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
139
  except Exception as e:
140
  print(f"Error running agent on task {task_id}: {e}")
141
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
142
 
143
- if not answers_payload:
144
- print("Agent did not produce any answers to submit.")
145
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
146
-
147
- # 4. Prepare Submission
148
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
149
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
150
- print(status_update)
151
-
152
- # 5. Submit
153
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
154
  try:
155
  response = requests.post(submit_url, json=submission_data, timeout=60)
156
- response.raise_for_status()
157
- result_data = response.json()
158
- final_status = (
159
- f"Submission Successful!\n"
160
- f"User: {result_data.get('username')}\n"
161
- f"Overall Score: {result_data.get('score', 'N/A')}% "
162
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
163
- f"Message: {result_data.get('message', 'No message received.')}"
164
- )
165
- print("Submission successful.")
166
- results_df = pd.DataFrame(results_log)
167
- return final_status, results_df
168
- except requests.exceptions.HTTPError as e:
169
- error_detail = f"Server responded with status {e.response.status_code}."
170
  try:
171
- error_json = e.response.json()
172
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
173
- except requests.exceptions.JSONDecodeError:
174
- error_detail += f" Response: {e.response.text[:500]}"
175
- status_message = f"Submission Failed: {error_detail}"
176
- print(status_message)
177
- results_df = pd.DataFrame(results_log)
178
- return status_message, results_df
179
- except requests.exceptions.Timeout:
180
- status_message = "Submission Failed: The request timed out."
181
- print(status_message)
182
- results_df = pd.DataFrame(results_log)
183
- return status_message, results_df
184
- except requests.exceptions.RequestException as e:
185
- status_message = f"Submission Failed: Network error - {e}"
186
- print(status_message)
187
- results_df = pd.DataFrame(results_log)
188
- return status_message, results_df
189
  except Exception as e:
190
- status_message = f"An unexpected error occurred during submission: {e}"
191
- print(status_message)
192
- results_df = pd.DataFrame(results_log)
193
- return status_message, results_df
194
-
195
 
196
- # --- Build Gradio Interface using Blocks ---
197
  with gr.Blocks() as demo:
198
- gr.Markdown("# Basic Agent Evaluation Runner")
199
- gr.Markdown(
200
- """
201
- **Instructions:**
202
-
203
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
204
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
205
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
206
-
207
- ---
208
- **Disclaimers:**
209
- 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).
210
- 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.
211
- """
212
- )
213
-
214
  gr.LoginButton()
215
-
216
  run_button = gr.Button("Run Evaluation & Submit All Answers")
217
-
218
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
219
- # Removed max_rows=10 from DataFrame constructor
220
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
221
-
222
- run_button.click(
223
- fn=run_and_submit_all,
224
- outputs=[status_output, results_table]
225
- )
226
 
227
  if __name__ == "__main__":
228
- print("\n" + "-"*30 + " App Starting " + "-"*30)
229
- # Check for SPACE_HOST and SPACE_ID at startup for information
230
- space_host_startup = os.getenv("SPACE_HOST")
231
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
232
-
233
- if space_host_startup:
234
- print(f"✅ SPACE_HOST found: {space_host_startup}")
235
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
236
- else:
237
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
238
-
239
- if space_id_startup: # Print repo URLs if SPACE_ID is found
240
- print(f"✅ SPACE_ID found: {space_id_startup}")
241
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
242
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
243
- else:
244
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
245
-
246
- print("-"*(60 + len(" App Starting ")) + "\n")
247
-
248
- print("Launching Gradio Interface for Basic Agent Evaluation...")
249
- demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
 
 
5
  from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool
 
6
 
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
 
 
10
  class BasicAgent:
11
  def __init__(self):
12
+ # uso el clasico Qwen 32B
13
+ model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
14
 
 
 
 
 
 
 
15
  search_tool = DuckDuckGoSearchTool()
16
 
 
17
  self.model = InferenceClientModel(
18
  model_id=model_id,
19
  token=os.getenv("HF_TOKEN")
20
  )
21
 
22
+ # 4. CON PERMISOS EXTRA
 
23
  self.agent = CodeAgent(
24
  tools=[search_tool],
25
  model=self.model,
26
+ max_steps=12,
27
+ verbosity_level=1,
28
+ additional_authorized_imports=['csv', 'pandas', 'bs4', 'requests', 're', 'collections', 'itertools']
29
  )
30
 
31
  def __call__(self, question: str) -> str:
32
+ prompt = f"""
33
+ TASK: Answer the following question.
 
 
 
 
 
 
 
 
 
 
34
  QUESTION: {question}
35
+
36
+ RULES:
37
+ 1. If reading a file (CSV/Excel), USE 'pandas' or 'csv' libraries.
38
+ 2. Solve step by step using Python.
39
+ 3. FINAL OUTPUT: Return ONLY the raw answer string.
40
+ - Do NOT output markdown code blocks (```).
41
+ - Do NOT write "The answer is".
42
+ - Just the value (e.g., "14", "Paris", "apple, banana").
43
  """
44
 
45
  try:
 
46
  answer = self.agent.run(prompt)
47
  clean = str(answer).strip()
48
+
49
+ # Limpieza básica de emergencia por si hay código
50
+ if "Final Answer:" in clean:
51
+ clean = clean.split("Final Answer:")[-1].strip()
52
+
53
+ return clean
54
 
55
  except Exception as e:
56
  print(f"Error executing agent: {e}")
57
  return "Error parsing answer"
 
58
 
59
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
60
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
 
61
 
62
  if profile:
63
+ username = f"{profile.username}"
64
  print(f"User logged in: {username}")
65
  else:
 
66
  return "Please Login to Hugging Face with the button.", None
67
 
68
  api_url = DEFAULT_API_URL
69
  questions_url = f"{api_url}/questions"
70
  submit_url = f"{api_url}/submit"
71
+
72
+ agent_code = f"[https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id}/tree/main"
73
 
74
+ # 1. Fetch Questions
 
 
 
 
 
 
 
 
 
 
 
75
  try:
76
  response = requests.get(questions_url, timeout=15)
 
77
  questions_data = response.json()
 
 
 
 
 
 
 
 
 
 
 
78
  except Exception as e:
79
+ return f"Error fetching questions: {e}", None
 
80
 
 
81
  results_log = []
82
  answers_payload = []
83
+
84
  print(f"Running agent on {len(questions_data)} questions...")
85
+
86
+ # 2. Loop de Preguntas
87
  for item in questions_data:
88
  task_id = item.get("task_id")
89
  question_text = item.get("question")
90
+ if not task_id: continue
91
+
92
+ print(f"Processing Task: {task_id}")
93
+
94
  try:
95
+ # <--- CORRECCIÓN IMPORTANTE 2:
96
+ # ¡Instanciamos el agente AQUÍ DENTRO!
97
+ # Esto reinicia su cerebro para cada pregunta nueva.
98
+ current_agent = BasicAgent()
99
+
100
+ submitted_answer = current_agent(question_text)
101
+
102
+ # Verificación de seguridad para el Error 500
103
+ if len(submitted_answer) > 200:
104
+ submitted_answer = submitted_answer[:200]
105
+
106
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
107
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
108
+
109
  except Exception as e:
110
  print(f"Error running agent on task {task_id}: {e}")
111
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": "Error"})
112
 
113
+ # 3. Submit
 
 
 
 
114
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
115
+ print(f"Submitting {len(answers_payload)} answers...")
116
+
 
 
 
117
  try:
118
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  try:
120
+ result_data = response.json()
121
+ final_status = f"Submission Successful! Score: {result_data.get('score', 'N/A')}%"
122
+ except:
123
+ final_status = f"Submission Failed. Response: {response.text}"
124
+
125
+ return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
126
  except Exception as e:
127
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
 
128
 
129
+ # --- Gradio Interface ---
130
  with gr.Blocks() as demo:
131
+ gr.Markdown("# Basic Agent Evaluation Runner (Fixed Memory)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  gr.LoginButton()
 
133
  run_button = gr.Button("Run Evaluation & Submit All Answers")
134
+ status_output = gr.Textbox(label="Status", interactive=False)
135
+ results_table = gr.DataFrame(label="Results", wrap=True)
136
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
 
 
 
137
 
138
  if __name__ == "__main__":
139
+ demo.launch()