Realistvik0 commited on
Commit
4b49c6e
·
verified ·
1 Parent(s): f664f59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -2
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import inspect
3
  import yaml
4
  import requests
@@ -7,6 +8,11 @@ import pandas as pd
7
 
8
  from smolagents import CodeAgent, OpenAIServerModel, LiteLLMModel, Tool, HfApiModel
9
 
 
 
 
 
 
10
  from tools.calculator import Calculator
11
  from tools.final_answer import FinalAnswerTool
12
  from tools.visit_webpage import VisitWebpageTool
@@ -32,6 +38,11 @@ MAX_STEPS = 6
32
  MAX_TOKENS = 900
33
  TEMPERATURE = 0.2
34
 
 
 
 
 
 
35
 
36
  # =========================================================
37
  # Research Context
@@ -242,6 +253,87 @@ def _format_verification_result(result: dict) -> str:
242
  return "\n".join(lines)
243
 
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  # =========================================================
246
  # Load Prompts
247
  # =========================================================
@@ -398,21 +490,51 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
398
  # 3. Run your Agent
399
  results_log = []
400
  answers_payload = []
 
401
  print(f"Running agent on {len(questions_data)} questions...")
402
- for item in questions_data:
 
403
  task_id = item.get("task_id")
404
  question_text = item.get("question")
405
  if not task_id or question_text is None:
406
  print(f"Skipping item with missing task_id or question: {item}")
407
  continue
 
 
 
408
  try:
409
- submitted_answer = agent_runner(question_text)
410
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
411
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
412
  except Exception as e:
413
  print(f"Error running agent on task {task_id}: {e}")
414
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
  if not answers_payload:
417
  print("Agent did not produce any answers to submit.")
418
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
@@ -435,6 +557,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
435
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
436
  f"Message: {result_data.get('message', 'No message received.')}"
437
  )
 
 
 
 
 
438
  print("Submission successful.")
439
  results_df = pd.DataFrame(results_log)
440
  return final_status, results_df
 
1
  import os
2
+ import time
3
  import inspect
4
  import yaml
5
  import requests
 
8
 
9
  from smolagents import CodeAgent, OpenAIServerModel, LiteLLMModel, Tool, HfApiModel
10
 
11
+ try:
12
+ from litellm.exceptions import RateLimitError
13
+ except ImportError:
14
+ RateLimitError = None
15
+
16
  from tools.calculator import Calculator
17
  from tools.final_answer import FinalAnswerTool
18
  from tools.visit_webpage import VisitWebpageTool
 
38
  MAX_TOKENS = 900
39
  TEMPERATURE = 0.2
40
 
41
+ # Pacing / rate-limit handling
42
+ MIN_SECONDS_BETWEEN_QUESTIONS = 60
43
+ MAX_RATE_LIMIT_RETRIES = 5
44
+ RATE_LIMIT_BASE_DELAY = 30 # seconds; doubles each retry
45
+
46
 
47
  # =========================================================
48
  # Research Context
 
253
  return "\n".join(lines)
254
 
255
 
256
+ # =========================================================
257
+ # Rate limit / quota handling
258
+ # =========================================================
259
+
260
+ class DailyQuotaExhaustedError(Exception):
261
+ """Raised when the model provider reports a daily/per-day quota
262
+ exhaustion, as opposed to a transient per-minute rate limit."""
263
+ pass
264
+
265
+
266
+ def _is_rate_limit_error(exc: Exception) -> bool:
267
+ """
268
+ Detect rate-limit / quota errors across providers, since exact
269
+ exception types can vary by SDK version. Falls back to matching
270
+ on common message fragments.
271
+ """
272
+ if RateLimitError is not None and isinstance(exc, RateLimitError):
273
+ return True
274
+
275
+ message = str(exc).lower()
276
+ signals = [
277
+ "rate limit",
278
+ "rate_limit",
279
+ "429",
280
+ "quota",
281
+ "resource_exhausted",
282
+ "too many requests",
283
+ ]
284
+ return any(signal in message for signal in signals)
285
+
286
+
287
+ def _is_daily_quota_exhausted(exc: Exception) -> bool:
288
+ """
289
+ Heuristically detect a *daily/per-day* quota exhaustion (as opposed
290
+ to a transient per-minute rate limit). These typically won't resolve
291
+ with a short backoff, so retrying is pointless and the whole run
292
+ should stop early rather than burn time and further requests.
293
+
294
+ Gemini/Google API quota errors usually include phrases like
295
+ "PerDay", "per day", "daily limit", or a quota_id containing
296
+ "PerDay" when the daily free-tier quota is hit.
297
+ """
298
+ message = str(exc).lower()
299
+ signals = [
300
+ "per day",
301
+ "perday",
302
+ "daily limit",
303
+ "daily quota",
304
+ "generate_content_free_tier_requests_per_day",
305
+ ]
306
+ return any(signal in message for signal in signals)
307
+
308
+
309
+ def _run_agent_with_backoff(agent_runner, question_text,
310
+ max_retries=MAX_RATE_LIMIT_RETRIES,
311
+ base_delay=RATE_LIMIT_BASE_DELAY):
312
+ """
313
+ Runs the agent on a single question, retrying with exponential
314
+ backoff if a transient rate-limit error is hit. If the error looks
315
+ like a daily/per-day quota exhaustion, raises DailyQuotaExhaustedError
316
+ immediately instead of retrying, since backoff won't help.
317
+ Non-rate-limit errors are raised immediately (handled by the caller).
318
+ """
319
+ for attempt in range(max_retries + 1):
320
+ try:
321
+ return agent_runner(question_text)
322
+ except Exception as e:
323
+ if _is_daily_quota_exhausted(e):
324
+ raise DailyQuotaExhaustedError(str(e)) from e
325
+
326
+ if _is_rate_limit_error(e) and attempt < max_retries:
327
+ delay = base_delay * (2 ** attempt) # 30, 60, 120, 240, 480...
328
+ print(
329
+ f"Rate limit/quota hit (attempt {attempt + 1}/{max_retries}). "
330
+ f"Backing off for {delay}s..."
331
+ )
332
+ time.sleep(delay)
333
+ continue
334
+ raise
335
+
336
+
337
  # =========================================================
338
  # Load Prompts
339
  # =========================================================
 
490
  # 3. Run your Agent
491
  results_log = []
492
  answers_payload = []
493
+ quota_exhausted = False
494
  print(f"Running agent on {len(questions_data)} questions...")
495
+
496
+ for idx, item in enumerate(questions_data):
497
  task_id = item.get("task_id")
498
  question_text = item.get("question")
499
  if not task_id or question_text is None:
500
  print(f"Skipping item with missing task_id or question: {item}")
501
  continue
502
+
503
+ start_time = time.monotonic()
504
+
505
  try:
506
+ submitted_answer = _run_agent_with_backoff(agent_runner, question_text)
507
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
508
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
509
+ except DailyQuotaExhaustedError as e:
510
+ print(f"Daily quota exhausted, stopping run early: {e}")
511
+ results_log.append({
512
+ "Task ID": task_id,
513
+ "Question": question_text,
514
+ "Submitted Answer": f"SKIPPED (daily quota exhausted): {e}",
515
+ })
516
+ quota_exhausted = True
517
+ break
518
  except Exception as e:
519
  print(f"Error running agent on task {task_id}: {e}")
520
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
521
 
522
+ # Pace requests: ensure at least MIN_SECONDS_BETWEEN_QUESTIONS
523
+ # seconds between question starts, accounting for however long
524
+ # this question took (including any backoff sleeps it already did).
525
+ if idx < len(questions_data) - 1:
526
+ elapsed = time.monotonic() - start_time
527
+ remaining = MIN_SECONDS_BETWEEN_QUESTIONS - elapsed
528
+ if remaining > 0:
529
+ print(f"Waiting {remaining:.1f}s before the next question (pacing)...")
530
+ time.sleep(remaining)
531
+
532
+ if quota_exhausted:
533
+ print(
534
+ f"Stopped early due to daily quota exhaustion. "
535
+ f"{len(answers_payload)} answers collected before stopping."
536
+ )
537
+
538
  if not answers_payload:
539
  print("Agent did not produce any answers to submit.")
540
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
557
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
558
  f"Message: {result_data.get('message', 'No message received.')}"
559
  )
560
+ if quota_exhausted:
561
+ final_status += (
562
+ f"\n\nNote: run stopped early after {len(answers_payload)} "
563
+ f"questions due to daily quota exhaustion."
564
+ )
565
  print("Submission successful.")
566
  results_df = pd.DataFrame(results_log)
567
  return final_status, results_df