avi080704 commited on
Commit
6768e25
·
verified ·
1 Parent(s): 3c8ec60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -29
app.py CHANGED
@@ -145,6 +145,15 @@ def search_wikipedia(query: str) -> str:
145
  return f"Wikipedia search error: {e}"
146
 
147
 
 
 
 
 
 
 
 
 
 
148
  def _make_agent(model_id: str, hf_token: str) -> CodeAgent:
149
  return CodeAgent(
150
  tools=[
@@ -159,23 +168,20 @@ def _make_agent(model_id: str, hf_token: str) -> CodeAgent:
159
  )
160
 
161
 
162
- # Models in priority order — free tier first, bigger/better after
163
- CANDIDATE_MODELS = [
164
- "Qwen/Qwen2.5-7B-Instruct",
165
- "Qwen/Qwen2.5-72B-Instruct", # Pro only, kept as fallback
166
- "mistralai/Mistral-7B-Instruct-v0.3",
167
- "HuggingFaceTB/SmolLM2-1.7B-Instruct",
168
- ]
169
-
170
-
171
  class BasicAgent:
172
  def __init__(self):
173
  hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
 
 
 
 
 
174
  print(f"HF_TOKEN present: {bool(hf_token)}")
175
 
176
- # Pick the first model that responds without a payment error
177
  self.agent = None
178
  self.model_id = None
 
 
179
  for model_id in CANDIDATE_MODELS:
180
  try:
181
  print(f"Trying model: {model_id}")
@@ -188,13 +194,18 @@ class BasicAgent:
188
  break
189
  except Exception as e:
190
  msg = str(e)
 
191
  if "402" in msg or "Payment" in msg:
192
  print(f"⛔ {model_id} requires payment, trying next...")
193
  else:
194
- print(f"⚠️ {model_id} failed: {msg[:80]}, trying next...")
195
 
196
  if self.agent is None:
197
- raise RuntimeError("No working model found. Check HF_TOKEN and account tier.")
 
 
 
 
198
 
199
  print(f"BasicAgent initialized with model: {self.model_id}")
200
 
@@ -253,16 +264,15 @@ Output ONLY the final answer:"""
253
  return err_msg
254
 
255
 
256
- def run_and_submit_all( profile: gr.OAuthProfile | None):
257
  """
258
  Fetches all questions, runs the BasicAgent on them, submits all answers,
259
  and displays the results.
260
  """
261
- # --- Determine HF Space Runtime URL and Repo URL ---
262
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
263
 
264
  if profile:
265
- username= f"{profile.username}"
266
  print(f"User logged in: {username}")
267
  else:
268
  print("User not logged in.")
@@ -272,13 +282,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
272
  questions_url = f"{api_url}/questions"
273
  submit_url = f"{api_url}/submit"
274
 
275
- # 1. Instantiate Agent ( modify this part to create your agent)
276
  try:
277
  agent = BasicAgent()
278
  except Exception as e:
279
  print(f"Error instantiating agent: {e}")
280
  return f"Error initializing agent: {e}", None
281
- # 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)
282
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
283
  print(agent_code)
284
 
@@ -289,16 +299,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
289
  response.raise_for_status()
290
  questions_data = response.json()
291
  if not questions_data:
292
- print("Fetched questions list is empty.")
293
- return "Fetched questions list is empty or invalid format.", None
294
  print(f"Fetched {len(questions_data)} questions.")
295
  except requests.exceptions.RequestException as e:
296
  print(f"Error fetching questions: {e}")
297
  return f"Error fetching questions: {e}", None
298
  except requests.exceptions.JSONDecodeError as e:
299
- print(f"Error decoding JSON response from questions endpoint: {e}")
300
- print(f"Response text: {response.text[:500]}")
301
- return f"Error decoding server response for questions: {e}", None
302
  except Exception as e:
303
  print(f"An unexpected error occurred fetching questions: {e}")
304
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -319,8 +329,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
319
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
320
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
321
  except Exception as e:
322
- print(f"Error running agent on task {task_id}: {e}")
323
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
324
 
325
  if not answers_payload:
326
  print("Agent did not produce any answers to submit.")
@@ -374,6 +384,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
374
  results_df = pd.DataFrame(results_log)
375
  return status_message, results_df
376
 
 
377
  # --- Build Gradio Interface using Blocks ---
378
  with gr.Blocks() as demo:
379
  gr.Markdown("# Basic Agent Evaluation Runner")
@@ -397,7 +408,6 @@ with gr.Blocks() as demo:
397
  run_button = gr.Button("Run Evaluation & Submit All Answers")
398
 
399
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
400
- # Removed max_rows=10 from DataFrame constructor
401
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
402
 
403
  run_button.click(
@@ -407,9 +417,8 @@ with gr.Blocks() as demo:
407
 
408
  if __name__ == "__main__":
409
  print("\n" + "-"*30 + " App Starting " + "-"*30)
410
- # Check for SPACE_HOST and SPACE_ID at startup for information
411
  space_host_startup = os.getenv("SPACE_HOST")
412
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
413
 
414
  if space_host_startup:
415
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -417,7 +426,7 @@ if __name__ == "__main__":
417
  else:
418
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
419
 
420
- if space_id_startup: # Print repo URLs if SPACE_ID is found
421
  print(f"✅ SPACE_ID found: {space_id_startup}")
422
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
423
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
145
  return f"Wikipedia search error: {e}"
146
 
147
 
148
+ # --- Models in priority order: smallest/free first ---
149
+ CANDIDATE_MODELS = [
150
+ "HuggingFaceTB/SmolLM2-1.7B-Instruct", # tiny, always free
151
+ "mistralai/Mistral-7B-Instruct-v0.3", # free tier
152
+ "Qwen/Qwen2.5-7B-Instruct", # free tier
153
+ "Qwen/Qwen2.5-72B-Instruct", # Pro only, last resort
154
+ ]
155
+
156
+
157
  def _make_agent(model_id: str, hf_token: str) -> CodeAgent:
158
  return CodeAgent(
159
  tools=[
 
168
  )
169
 
170
 
 
 
 
 
 
 
 
 
 
171
  class BasicAgent:
172
  def __init__(self):
173
  hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
174
+ if not hf_token:
175
+ raise RuntimeError(
176
+ "HF_TOKEN environment variable is not set. "
177
+ "Go to Space Settings → Variables and secrets → add HF_TOKEN."
178
+ )
179
  print(f"HF_TOKEN present: {bool(hf_token)}")
180
 
 
181
  self.agent = None
182
  self.model_id = None
183
+ errors = []
184
+
185
  for model_id in CANDIDATE_MODELS:
186
  try:
187
  print(f"Trying model: {model_id}")
 
194
  break
195
  except Exception as e:
196
  msg = str(e)
197
+ errors.append(f"{model_id}: {msg[:120]}")
198
  if "402" in msg or "Payment" in msg:
199
  print(f"⛔ {model_id} requires payment, trying next...")
200
  else:
201
+ print(f"⚠️ {model_id} failed ({msg[:80]}), trying next...")
202
 
203
  if self.agent is None:
204
+ raise RuntimeError(
205
+ "No working model found.\n"
206
+ + "\n".join(errors)
207
+ + "\n\nCheck that HF_TOKEN is set correctly in Space Secrets and your account tier."
208
+ )
209
 
210
  print(f"BasicAgent initialized with model: {self.model_id}")
211
 
 
264
  return err_msg
265
 
266
 
267
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
268
  """
269
  Fetches all questions, runs the BasicAgent on them, submits all answers,
270
  and displays the results.
271
  """
272
+ space_id = os.getenv("SPACE_ID")
 
273
 
274
  if profile:
275
+ username = f"{profile.username}"
276
  print(f"User logged in: {username}")
277
  else:
278
  print("User not logged in.")
 
282
  questions_url = f"{api_url}/questions"
283
  submit_url = f"{api_url}/submit"
284
 
285
+ # 1. Instantiate Agent
286
  try:
287
  agent = BasicAgent()
288
  except Exception as e:
289
  print(f"Error instantiating agent: {e}")
290
  return f"Error initializing agent: {e}", None
291
+
292
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
293
  print(agent_code)
294
 
 
299
  response.raise_for_status()
300
  questions_data = response.json()
301
  if not questions_data:
302
+ print("Fetched questions list is empty.")
303
+ return "Fetched questions list is empty or invalid format.", None
304
  print(f"Fetched {len(questions_data)} questions.")
305
  except requests.exceptions.RequestException as e:
306
  print(f"Error fetching questions: {e}")
307
  return f"Error fetching questions: {e}", None
308
  except requests.exceptions.JSONDecodeError as e:
309
+ print(f"Error decoding JSON response from questions endpoint: {e}")
310
+ print(f"Response text: {response.text[:500]}")
311
+ return f"Error decoding server response for questions: {e}", None
312
  except Exception as e:
313
  print(f"An unexpected error occurred fetching questions: {e}")
314
  return f"An unexpected error occurred fetching questions: {e}", None
 
329
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
330
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
331
  except Exception as e:
332
+ print(f"Error running agent on task {task_id}: {e}")
333
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
334
 
335
  if not answers_payload:
336
  print("Agent did not produce any answers to submit.")
 
384
  results_df = pd.DataFrame(results_log)
385
  return status_message, results_df
386
 
387
+
388
  # --- Build Gradio Interface using Blocks ---
389
  with gr.Blocks() as demo:
390
  gr.Markdown("# Basic Agent Evaluation Runner")
 
408
  run_button = gr.Button("Run Evaluation & Submit All Answers")
409
 
410
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
411
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
412
 
413
  run_button.click(
 
417
 
418
  if __name__ == "__main__":
419
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
420
  space_host_startup = os.getenv("SPACE_HOST")
421
+ space_id_startup = os.getenv("SPACE_ID")
422
 
423
  if space_host_startup:
424
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
426
  else:
427
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
428
 
429
+ if space_id_startup:
430
  print(f"✅ SPACE_ID found: {space_id_startup}")
431
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
432
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")