Kurama0303 commited on
Commit
89ba998
·
verified ·
1 Parent(s): 1b6ddab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -17
app.py CHANGED
@@ -5,6 +5,7 @@ import inspect
5
  import pandas as pd
6
  from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool
7
  from smolagents.tools import Tool
 
8
 
9
  # (Keep Constants as is)
10
  # --- Constants ---
@@ -29,32 +30,53 @@ class BasicAgent:
29
  print(f"Agent returning fixed answer: {fixed_answer}")
30
  return fixed_answer
31
 
32
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  """
34
- Fetches all questions, runs the BasicAgent on them, submits all answers,
35
- and displays the results.
36
  """
 
37
  # --- Determine HF Space Runtime URL and Repo URL ---
38
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
39
 
40
  if profile:
41
- username= f"{profile.username}"
42
  print(f"User logged in: {username}")
43
  else:
44
  print("User not logged in.")
45
  return "Please Login to Hugging Face with the button.", None
46
 
 
47
  api_url = DEFAULT_API_URL
48
  questions_url = f"{api_url}/questions"
49
  submit_url = f"{api_url}/submit"
50
 
51
- # 1. Instantiate Agent ( modify this part to create your agent)
52
  try:
53
  agent = BasicAgent()
54
  except Exception as e:
55
  print(f"Error instantiating agent: {e}")
56
  return f"Error initializing agent: {e}", None
57
- # 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)
 
58
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
59
  print(agent_code)
60
 
@@ -65,16 +87,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
65
  response.raise_for_status()
66
  questions_data = response.json()
67
  if not questions_data:
68
- print("Fetched questions list is empty.")
69
- return "Fetched questions list is empty or invalid format.", None
70
  print(f"Fetched {len(questions_data)} questions.")
71
  except requests.exceptions.RequestException as e:
72
  print(f"Error fetching questions: {e}")
73
  return f"Error fetching questions: {e}", None
74
  except requests.exceptions.JSONDecodeError as e:
75
- print(f"Error decoding JSON response from questions endpoint: {e}")
76
- print(f"Response text: {response.text[:500]}")
77
- return f"Error decoding server response for questions: {e}", None
78
  except Exception as e:
79
  print(f"An unexpected error occurred fetching questions: {e}")
80
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -83,6 +105,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
83
  results_log = []
84
  answers_payload = []
85
  print(f"Running agent on {len(questions_data)} questions...")
 
86
  for item in questions_data:
87
  task_id = item.get("task_id")
88
  question_text = item.get("question")
@@ -90,19 +113,24 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
90
  print(f"Skipping item with missing task_id or question: {item}")
91
  continue
92
  try:
93
- submitted_answer = agent(question_text)
 
94
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
95
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
96
  except Exception as e:
97
- print(f"Error running agent on task {task_id}: {e}")
98
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
99
 
100
  if not answers_payload:
101
  print("Agent did not produce any answers to submit.")
102
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
103
 
104
- # 4. Prepare Submission
105
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
106
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
107
  print(status_update)
108
 
 
5
  import pandas as pd
6
  from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool
7
  from smolagents.tools import Tool
8
+ import time
9
 
10
  # (Keep Constants as is)
11
  # --- Constants ---
 
30
  print(f"Agent returning fixed answer: {fixed_answer}")
31
  return fixed_answer
32
 
33
+
34
+ def safe_agent_call(agent, question, retries=5, wait_time=20):
35
+ """
36
+ Helper function to safely call the agent with retry on rate limit errors (HTTP 429).
37
+ """
38
+ for attempt in range(retries):
39
+ try:
40
+ return agent(question)
41
+ except Exception as e:
42
+ error_text = str(e).lower()
43
+ if "rate limit" in error_text or "429" in error_text:
44
+ print(f"[Retry] Rate limit hit. Waiting {wait_time} seconds before retrying... (Attempt {attempt + 1}/{retries})")
45
+ time.sleep(wait_time)
46
+ else:
47
+ print(f"[Error] Non-rate-limit error encountered: {e}")
48
+ raise e
49
+ raise Exception(f"Failed after {retries} retries due to repeated rate limit errors.")
50
+
51
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
52
  """
53
+ Fetches all questions, runs the BasicAgent on them with retry logic on rate limit,
54
+ submits all answers, and displays the results.
55
  """
56
+
57
  # --- Determine HF Space Runtime URL and Repo URL ---
58
+ space_id = os.getenv("SPACE_ID")
59
 
60
  if profile:
61
+ username = f"{profile.username}"
62
  print(f"User logged in: {username}")
63
  else:
64
  print("User not logged in.")
65
  return "Please Login to Hugging Face with the button.", None
66
 
67
+ # --- Constants ---
68
  api_url = DEFAULT_API_URL
69
  questions_url = f"{api_url}/questions"
70
  submit_url = f"{api_url}/submit"
71
 
72
+ # 1. Instantiate Agent
73
  try:
74
  agent = BasicAgent()
75
  except Exception as e:
76
  print(f"Error instantiating agent: {e}")
77
  return f"Error initializing agent: {e}", None
78
+
79
+ # Build agent code link
80
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
81
  print(agent_code)
82
 
 
87
  response.raise_for_status()
88
  questions_data = response.json()
89
  if not questions_data:
90
+ print("Fetched questions list is empty.")
91
+ return "Fetched questions list is empty or invalid format.", None
92
  print(f"Fetched {len(questions_data)} questions.")
93
  except requests.exceptions.RequestException as e:
94
  print(f"Error fetching questions: {e}")
95
  return f"Error fetching questions: {e}", None
96
  except requests.exceptions.JSONDecodeError as e:
97
+ print(f"Error decoding JSON response from questions endpoint: {e}")
98
+ print(f"Response text: {response.text[:500]}")
99
+ return f"Error decoding server response for questions: {e}", None
100
  except Exception as e:
101
  print(f"An unexpected error occurred fetching questions: {e}")
102
  return f"An unexpected error occurred fetching questions: {e}", None
 
105
  results_log = []
106
  answers_payload = []
107
  print(f"Running agent on {len(questions_data)} questions...")
108
+
109
  for item in questions_data:
110
  task_id = item.get("task_id")
111
  question_text = item.get("question")
 
113
  print(f"Skipping item with missing task_id or question: {item}")
114
  continue
115
  try:
116
+ # Using safe_agent_call to handle rate limit retries
117
+ submitted_answer = safe_agent_call(agent, question_text)
118
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
119
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
120
  except Exception as e:
121
+ print(f"Error running agent on task {task_id}: {e}")
122
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
123
 
124
  if not answers_payload:
125
  print("Agent did not produce any answers to submit.")
126
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
127
 
128
+ # 4. Prepare Submission
129
+ submission_data = {
130
+ "username": username.strip(),
131
+ "agent_code": agent_code,
132
+ "answers": answers_payload
133
+ }
134
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
135
  print(status_update)
136