RozzaCreat commited on
Commit
405550e
·
verified ·
1 Parent(s): b3fb03d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -182
app.py CHANGED
@@ -6,8 +6,8 @@ import pandas as pd
6
  from smolagents import (
7
  CodeAgent,
8
  DuckDuckGoSearchTool,
9
- InferenceClientModel,
10
  WikipediaSearchTool,
 
11
  )
12
 
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -22,13 +22,15 @@ If you are asked for a comma separated list, apply the above rules depending on
22
 
23
  class BasicAgent:
24
  def __init__(self):
25
- token = os.getenv("GEMINI_API_KEY")
26
- print(f"[BasicAgent] GEMINI_API_KEY loaded: {bool(api_key)}")
 
 
27
  self.agent = CodeAgent(
28
  tools=[DuckDuckGoSearchTool(), WikipediaSearchTool()],
29
  model=LiteLLMModel(
30
  model_id="gemini/gemini-2.0-flash",
31
- token=token,
32
  ),
33
  max_steps=12,
34
  additional_authorized_imports=["pandas", "numpy", "datetime", "re", "json", "math"],
@@ -37,7 +39,7 @@ class BasicAgent:
37
  def __call__(self, question: str) -> str:
38
  try:
39
  raw = str(self.agent.run(f"{GAIA_SYSTEM_PROMPT}\n\nQuestion: {question}"))
40
- print(f"[Agent raw output, first 300 chars]: {raw[:300]}")
41
  if "FINAL ANSWER:" in raw:
42
  return raw.split("FINAL ANSWER:")[-1].strip().rstrip(".").strip()
43
  return raw.strip()
@@ -118,181 +120,4 @@ with gr.Blocks() as demo:
118
 
119
 
120
  if __name__ == "__main__":
121
- demo.launch(debug=True, share=False)
122
-
123
-
124
- def run_and_submit_all( profile: gr.OAuthProfile | None):
125
- """
126
- Fetches all questions, runs the BasicAgent on them, submits all answers,
127
- and displays the results.
128
- """
129
- # --- Determine HF Space Runtime URL and Repo URL ---
130
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
131
-
132
- if profile:
133
- username= f"{profile.username}"
134
- print(f"User logged in: {username}")
135
- else:
136
- print("User not logged in.")
137
- return "Please Login to Hugging Face with the button.", None
138
-
139
- api_url = DEFAULT_API_URL
140
- questions_url = f"{api_url}/questions"
141
- submit_url = f"{api_url}/submit"
142
-
143
- # 1. Instantiate Agent ( modify this part to create your agent)
144
- try:
145
- agent = BasicAgent()
146
- except Exception as e:
147
- print(f"Error instantiating agent: {e}")
148
- return f"Error initializing agent: {e}", None
149
- # 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)
150
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
151
- print(agent_code)
152
-
153
- # 2. Fetch Questions
154
- print(f"Fetching questions from: {questions_url}")
155
- try:
156
- response = requests.get(questions_url, timeout=15)
157
- response.raise_for_status()
158
- questions_data = response.json()
159
- if not questions_data:
160
- print("Fetched questions list is empty.")
161
- return "Fetched questions list is empty or invalid format.", None
162
- print(f"Fetched {len(questions_data)} questions.")
163
- except requests.exceptions.RequestException as e:
164
- print(f"Error fetching questions: {e}")
165
- return f"Error fetching questions: {e}", None
166
- except requests.exceptions.JSONDecodeError as e:
167
- print(f"Error decoding JSON response from questions endpoint: {e}")
168
- print(f"Response text: {response.text[:500]}")
169
- return f"Error decoding server response for questions: {e}", None
170
- except Exception as e:
171
- print(f"An unexpected error occurred fetching questions: {e}")
172
- return f"An unexpected error occurred fetching questions: {e}", None
173
-
174
- # 3. Run your Agent
175
- results_log = []
176
- answers_payload = []
177
- print(f"Running agent on {len(questions_data)} questions...")
178
- for item in questions_data:
179
- task_id = item.get("task_id")
180
- question_text = item.get("question")
181
- if not task_id or question_text is None:
182
- print(f"Skipping item with missing task_id or question: {item}")
183
- continue
184
- try:
185
- submitted_answer = agent(question_text)
186
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
187
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
188
- except Exception as e:
189
- print(f"Error running agent on task {task_id}: {e}")
190
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
191
-
192
- if not answers_payload:
193
- print("Agent did not produce any answers to submit.")
194
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
195
-
196
- # 4. Prepare Submission
197
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
198
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
199
- print(status_update)
200
-
201
- # 5. Submit
202
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
203
- try:
204
- response = requests.post(submit_url, json=submission_data, timeout=60)
205
- response.raise_for_status()
206
- result_data = response.json()
207
- final_status = (
208
- f"Submission Successful!\n"
209
- f"User: {result_data.get('username')}\n"
210
- f"Overall Score: {result_data.get('score', 'N/A')}% "
211
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
212
- f"Message: {result_data.get('message', 'No message received.')}"
213
- )
214
- print("Submission successful.")
215
- results_df = pd.DataFrame(results_log)
216
- return final_status, results_df
217
- except requests.exceptions.HTTPError as e:
218
- error_detail = f"Server responded with status {e.response.status_code}."
219
- try:
220
- error_json = e.response.json()
221
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
222
- except requests.exceptions.JSONDecodeError:
223
- error_detail += f" Response: {e.response.text[:500]}"
224
- status_message = f"Submission Failed: {error_detail}"
225
- print(status_message)
226
- results_df = pd.DataFrame(results_log)
227
- return status_message, results_df
228
- except requests.exceptions.Timeout:
229
- status_message = "Submission Failed: The request timed out."
230
- print(status_message)
231
- results_df = pd.DataFrame(results_log)
232
- return status_message, results_df
233
- except requests.exceptions.RequestException as e:
234
- status_message = f"Submission Failed: Network error - {e}"
235
- print(status_message)
236
- results_df = pd.DataFrame(results_log)
237
- return status_message, results_df
238
- except Exception as e:
239
- status_message = f"An unexpected error occurred during submission: {e}"
240
- print(status_message)
241
- results_df = pd.DataFrame(results_log)
242
- return status_message, results_df
243
-
244
-
245
- # --- Build Gradio Interface using Blocks ---
246
- with gr.Blocks() as demo:
247
- gr.Markdown("# Basic Agent Evaluation Runner")
248
- gr.Markdown(
249
- """
250
- **Instructions:**
251
-
252
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
253
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
254
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
255
-
256
- ---
257
- **Disclaimers:**
258
- 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).
259
- 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.
260
- """
261
- )
262
-
263
- gr.LoginButton()
264
-
265
- run_button = gr.Button("Run Evaluation & Submit All Answers")
266
-
267
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
268
- # Removed max_rows=10 from DataFrame constructor
269
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
270
-
271
- run_button.click(
272
- fn=run_and_submit_all,
273
- outputs=[status_output, results_table]
274
- )
275
-
276
- if __name__ == "__main__":
277
- print("\n" + "-"*30 + " App Starting " + "-"*30)
278
- # Check for SPACE_HOST and SPACE_ID at startup for information
279
- space_host_startup = os.getenv("SPACE_HOST")
280
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
281
-
282
- if space_host_startup:
283
- print(f"✅ SPACE_HOST found: {space_host_startup}")
284
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
285
- else:
286
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
287
-
288
- if space_id_startup: # Print repo URLs if SPACE_ID is found
289
- print(f"✅ SPACE_ID found: {space_id_startup}")
290
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
291
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
292
- else:
293
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
294
-
295
- print("-"*(60 + len(" App Starting ")) + "\n")
296
-
297
- print("Launching Gradio Interface for Basic Agent Evaluation...")
298
  demo.launch(debug=True, share=False)
 
6
  from smolagents import (
7
  CodeAgent,
8
  DuckDuckGoSearchTool,
 
9
  WikipediaSearchTool,
10
+ LiteLLMModel,
11
  )
12
 
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
22
 
23
  class BasicAgent:
24
  def __init__(self):
25
+ api_key = os.getenv("GEMINI_API_KEY")
26
+ print(f"[BasicAgent] GEMINI_API_KEY loaded: {bool(api_key)}, length: {len(api_key) if api_key else 0}")
27
+ if not api_key:
28
+ raise RuntimeError("GEMINI_API_KEY is not set. Add it in Settings → Variables and secrets, then Factory rebuild.")
29
  self.agent = CodeAgent(
30
  tools=[DuckDuckGoSearchTool(), WikipediaSearchTool()],
31
  model=LiteLLMModel(
32
  model_id="gemini/gemini-2.0-flash",
33
+ api_key=api_key,
34
  ),
35
  max_steps=12,
36
  additional_authorized_imports=["pandas", "numpy", "datetime", "re", "json", "math"],
 
39
  def __call__(self, question: str) -> str:
40
  try:
41
  raw = str(self.agent.run(f"{GAIA_SYSTEM_PROMPT}\n\nQuestion: {question}"))
42
+ print(f"[Agent raw, first 300]: {raw[:300]}")
43
  if "FINAL ANSWER:" in raw:
44
  return raw.split("FINAL ANSWER:")[-1].strip().rstrip(".").strip()
45
  return raw.strip()
 
120
 
121
 
122
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  demo.launch(debug=True, share=False)