Kreb1907 commited on
Commit
0641555
·
verified ·
1 Parent(s): c9d7ce2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -64
app.py CHANGED
@@ -1,8 +1,8 @@
1
  import os
2
  import time
 
3
  import gradio as gr
4
  import requests
5
- import inspect
6
  import pandas as pd
7
  import spaces
8
 
@@ -15,19 +15,24 @@ def _keep_alive():
15
  # --- Constants ---
16
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
 
18
- # Yeni API key'lere acik olan modeller (tercih sirasiyla).
19
- # Google eski modelleri yeni key'lere kapattigi icin liste onemli.
20
- PREFERRED_MODELS = [
21
- "gemini-3.1-flash-lite", # lite modeller çok daha az yoğun
 
22
  "gemini-3-flash-preview",
23
  "gemini-3.5-flash-lite",
24
  "gemini-flash-latest",
25
- "gemini-3.5-flash"
 
26
  ]
27
 
 
 
28
 
29
- def pick_gemini_model(api_key: str) -> str:
30
- """API key'in gercekten erisebildigi modeller arasindan uygun olani secer."""
 
31
  try:
32
  r = requests.get(
33
  "https://generativelanguage.googleapis.com/v1beta/models",
@@ -47,65 +52,50 @@ def pick_gemini_model(api_key: str) -> str:
47
  print("=" * 70)
48
  except Exception as e:
49
  print(f"[MODEL LIST ERROR] {type(e).__name__}: {e}")
50
- return PREFERRED_MODELS[0]
51
-
52
- # 1) Tercih listesinden ilk eslesen
53
- for p in PREFERRED_MODELS:
54
- if p in available:
55
- print(f"[MODEL SELECTED] {p}")
56
- return p
57
-
58
- # 2) Yoksa herhangi bir 'flash' text modeli
59
- blacklist = ("image", "tts", "audio", "live", "embedding", "vision")
60
- flashes = [
61
- m for m in available
62
- if "flash" in m and not any(b in m for b in blacklist)
63
- ]
64
- if flashes:
65
- print(f"[MODEL SELECTED - fallback] {flashes[0]}")
66
- return flashes[0]
67
-
68
- # 3) Son care
69
- if available:
70
- print(f"[MODEL SELECTED - last resort] {available[0]}")
71
- return available[0]
72
-
73
- return PREFERRED_MODELS[0]
74
 
75
 
76
  # --- Basic Agent Definition ---
77
  class BasicAgent:
78
- FALLBACKS = ["gemini-3.5-flash", "gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-flash-latest"]
79
-
80
  def __init__(self):
81
  self.api_key = os.environ["GEMINI_API_KEY"]
82
- pick_gemini_model(self.api_key) # sadece listeyi logla
83
  self.model_idx = 0
84
  self._build_agent()
85
 
86
- def _build_agent(self):
87
- from smolagents import CodeAgent, PythonInterpreterTool
88
- from smolagents import LiteLLMModel
89
- name = self.FALLBACKS[self.model_idx]
90
- print(f"[MODEL] {name} ile agent kuruluyor")
 
91
  model = LiteLLMModel(
92
  model_id=f"gemini/{name}",
93
  api_key=self.api_key,
94
  num_retries=5,
95
  )
 
96
  try:
97
  from smolagents import WebSearchTool
98
  search_tool = WebSearchTool()
 
99
  except ImportError:
100
  from smolagents import DuckDuckGoSearchTool
101
  search_tool = DuckDuckGoSearchTool()
102
- self.agent = CodeAgent(tools=[search_tool, PythonInterpreterTool()], model=model, max_steps=6)
103
 
104
- def _switch_model(self):
105
- if self.model_idx + 1 < len(self.FALLBACKS):
 
 
 
 
 
 
106
  self.model_idx += 1
 
107
  self._build_agent()
108
  return True
 
109
  return False
110
 
111
  def _clean(self, text: str) -> str:
@@ -116,7 +106,6 @@ class BasicAgent:
116
  return text.strip().strip('"').rstrip(".")
117
 
118
  def __call__(self, question: str) -> str:
119
- import traceback
120
  prompt = (
121
  "You are answering a benchmark question. Your response is graded by EXACT string match.\n"
122
  "Output ONLY the answer itself: no explanation, no sentence, no units unless the question asks for them, "
@@ -124,16 +113,18 @@ class BasicAgent:
124
  "If the answer is a number, write just the number. If it is a name, write just the name.\n\n"
125
  f"Question: {question}"
126
  )
127
- for attempt in range(2):
 
128
  try:
129
  answer = self.agent.run(prompt)
130
  cleaned = self._clean(answer)
131
  if cleaned:
132
  return cleaned
133
  except Exception as e:
134
- print(f"[AGENT ERROR] attempt {attempt+1} | {type(e).__name__}: {e}")
 
135
  traceback.print_exc()
136
- if "503" in str(e) or "UNAVAILABLE" in str(e):
137
  self._switch_model()
138
  time.sleep(5)
139
  return "unknown"
@@ -162,6 +153,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
162
  agent = BasicAgent()
163
  except Exception as e:
164
  print(f"Error instantiating agent: {e}")
 
165
  return f"Error initializing agent: {e}", None
166
 
167
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
@@ -177,13 +169,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
177
  print("Fetched questions list is empty.")
178
  return "Fetched questions list is empty or invalid format.", None
179
  print(f"Fetched {len(questions_data)} questions.")
180
- except requests.exceptions.RequestException as e:
181
- print(f"Error fetching questions: {e}")
182
- return f"Error fetching questions: {e}", None
183
  except requests.exceptions.JSONDecodeError as e:
184
  print(f"Error decoding JSON response from questions endpoint: {e}")
185
- print(f"Response text: {response.text[:500]}")
186
  return f"Error decoding server response for questions: {e}", None
 
 
 
187
  except Exception as e:
188
  print(f"An unexpected error occurred fetching questions: {e}")
189
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -209,6 +200,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
209
  print(f"<<< [{idx}/{total}] answer = {submitted_answer!r}")
210
  except Exception as e:
211
  print(f"Error running agent on task {task_id}: {e}")
 
212
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
213
 
214
  # Free tier RPM limitini asmamak icin nefes payi
@@ -220,8 +212,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
220
 
221
  # 4. Prepare Submission
222
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
223
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
224
- print(status_update)
225
 
226
  # 5. Submit
227
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
@@ -237,8 +228,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
237
  f"Message: {result_data.get('message', 'No message received.')}"
238
  )
239
  print("Submission successful.")
240
- results_df = pd.DataFrame(results_log)
241
- return final_status, results_df
242
  except requests.exceptions.HTTPError as e:
243
  error_detail = f"Server responded with status {e.response.status_code}."
244
  try:
@@ -248,23 +238,19 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
248
  error_detail += f" Response: {e.response.text[:500]}"
249
  status_message = f"Submission Failed: {error_detail}"
250
  print(status_message)
251
- results_df = pd.DataFrame(results_log)
252
- return status_message, results_df
253
  except requests.exceptions.Timeout:
254
  status_message = "Submission Failed: The request timed out."
255
  print(status_message)
256
- results_df = pd.DataFrame(results_log)
257
- return status_message, results_df
258
  except requests.exceptions.RequestException as e:
259
  status_message = f"Submission Failed: Network error - {e}"
260
  print(status_message)
261
- results_df = pd.DataFrame(results_log)
262
- return status_message, results_df
263
  except Exception as e:
264
  status_message = f"An unexpected error occurred during submission: {e}"
265
  print(status_message)
266
- results_df = pd.DataFrame(results_log)
267
- return status_message, results_df
268
 
269
 
270
  # --- Build Gradio Interface using Blocks ---
@@ -281,7 +267,7 @@ with gr.Blocks() as demo:
281
  ---
282
  **Disclaimers:**
283
  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).
284
- 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.
285
  """
286
  )
287
 
 
1
  import os
2
  import time
3
+ import traceback
4
  import gradio as gr
5
  import requests
 
6
  import pandas as pd
7
  import spaces
8
 
 
15
  # --- Constants ---
16
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
 
18
+ # TEK KAYNAK: model sirasi sadece burada. Sirasiyla denenir.
19
+ # Not: 2.x modeller listede gorunse bile yeni API key'lere kapali (404 verir),
20
+ # o yuzden buraya hic koymuyoruz.
21
+ MODEL_CANDIDATES = [
22
+ "gemini-3.1-flash-lite",
23
  "gemini-3-flash-preview",
24
  "gemini-3.5-flash-lite",
25
  "gemini-flash-latest",
26
+ "gemini-3.5-flash",
27
+ "gemini-3.6-flash",
28
  ]
29
 
30
+ # 503 / asiri yuk hatalarini yakalamak icin anahtar kelimeler
31
+ OVERLOAD_KEYS = ("503", "UNAVAILABLE", "ServiceUnavailable", "overloaded", "high demand")
32
 
33
+
34
+ def log_available_models(api_key: str) -> None:
35
+ """Sadece bilgi amacli: key'in gordugu modelleri loglar."""
36
  try:
37
  r = requests.get(
38
  "https://generativelanguage.googleapis.com/v1beta/models",
 
52
  print("=" * 70)
53
  except Exception as e:
54
  print(f"[MODEL LIST ERROR] {type(e).__name__}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
 
57
  # --- Basic Agent Definition ---
58
  class BasicAgent:
 
 
59
  def __init__(self):
60
  self.api_key = os.environ["GEMINI_API_KEY"]
61
+ log_available_models(self.api_key)
62
  self.model_idx = 0
63
  self._build_agent()
64
 
65
+ def _build_agent(self) -> None:
66
+ from smolagents import CodeAgent, LiteLLMModel, PythonInterpreterTool
67
+
68
+ name = MODEL_CANDIDATES[self.model_idx]
69
+ print(f"[MODEL] agent kuruluyor -> gemini/{name}")
70
+
71
  model = LiteLLMModel(
72
  model_id=f"gemini/{name}",
73
  api_key=self.api_key,
74
  num_retries=5,
75
  )
76
+
77
  try:
78
  from smolagents import WebSearchTool
79
  search_tool = WebSearchTool()
80
+ print("[TOOL] WebSearchTool")
81
  except ImportError:
82
  from smolagents import DuckDuckGoSearchTool
83
  search_tool = DuckDuckGoSearchTool()
84
+ print("[TOOL] DuckDuckGoSearchTool")
85
 
86
+ self.agent = CodeAgent(
87
+ tools=[search_tool, PythonInterpreterTool()],
88
+ model=model,
89
+ max_steps=6,
90
+ )
91
+
92
+ def _switch_model(self) -> bool:
93
+ if self.model_idx + 1 < len(MODEL_CANDIDATES):
94
  self.model_idx += 1
95
+ print(f"[FALLBACK] siradaki modele geciliyor: {MODEL_CANDIDATES[self.model_idx]}")
96
  self._build_agent()
97
  return True
98
+ print("[FALLBACK] denenecek baska model kalmadi")
99
  return False
100
 
101
  def _clean(self, text: str) -> str:
 
106
  return text.strip().strip('"').rstrip(".")
107
 
108
  def __call__(self, question: str) -> str:
 
109
  prompt = (
110
  "You are answering a benchmark question. Your response is graded by EXACT string match.\n"
111
  "Output ONLY the answer itself: no explanation, no sentence, no units unless the question asks for them, "
 
113
  "If the answer is a number, write just the number. If it is a name, write just the name.\n\n"
114
  f"Question: {question}"
115
  )
116
+
117
+ for attempt in range(3):
118
  try:
119
  answer = self.agent.run(prompt)
120
  cleaned = self._clean(answer)
121
  if cleaned:
122
  return cleaned
123
  except Exception as e:
124
+ err = f"{type(e).__name__}: {e}"
125
+ print(f"[AGENT ERROR] attempt {attempt+1} | {err}")
126
  traceback.print_exc()
127
+ if any(k in err for k in OVERLOAD_KEYS):
128
  self._switch_model()
129
  time.sleep(5)
130
  return "unknown"
 
153
  agent = BasicAgent()
154
  except Exception as e:
155
  print(f"Error instantiating agent: {e}")
156
+ traceback.print_exc()
157
  return f"Error initializing agent: {e}", None
158
 
159
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
169
  print("Fetched questions list is empty.")
170
  return "Fetched questions list is empty or invalid format.", None
171
  print(f"Fetched {len(questions_data)} questions.")
 
 
 
172
  except requests.exceptions.JSONDecodeError as e:
173
  print(f"Error decoding JSON response from questions endpoint: {e}")
 
174
  return f"Error decoding server response for questions: {e}", None
175
+ except requests.exceptions.RequestException as e:
176
+ print(f"Error fetching questions: {e}")
177
+ return f"Error fetching questions: {e}", None
178
  except Exception as e:
179
  print(f"An unexpected error occurred fetching questions: {e}")
180
  return f"An unexpected error occurred fetching questions: {e}", None
 
200
  print(f"<<< [{idx}/{total}] answer = {submitted_answer!r}")
201
  except Exception as e:
202
  print(f"Error running agent on task {task_id}: {e}")
203
+ answers_payload.append({"task_id": task_id, "submitted_answer": "unknown"})
204
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
205
 
206
  # Free tier RPM limitini asmamak icin nefes payi
 
212
 
213
  # 4. Prepare Submission
214
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
215
+ print(f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'...")
 
216
 
217
  # 5. Submit
218
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
228
  f"Message: {result_data.get('message', 'No message received.')}"
229
  )
230
  print("Submission successful.")
231
+ return final_status, pd.DataFrame(results_log)
 
232
  except requests.exceptions.HTTPError as e:
233
  error_detail = f"Server responded with status {e.response.status_code}."
234
  try:
 
238
  error_detail += f" Response: {e.response.text[:500]}"
239
  status_message = f"Submission Failed: {error_detail}"
240
  print(status_message)
241
+ return status_message, pd.DataFrame(results_log)
 
242
  except requests.exceptions.Timeout:
243
  status_message = "Submission Failed: The request timed out."
244
  print(status_message)
245
+ return status_message, pd.DataFrame(results_log)
 
246
  except requests.exceptions.RequestException as e:
247
  status_message = f"Submission Failed: Network error - {e}"
248
  print(status_message)
249
+ return status_message, pd.DataFrame(results_log)
 
250
  except Exception as e:
251
  status_message = f"An unexpected error occurred during submission: {e}"
252
  print(status_message)
253
+ return status_message, pd.DataFrame(results_log)
 
254
 
255
 
256
  # --- Build Gradio Interface using Blocks ---
 
267
  ---
268
  **Disclaimers:**
269
  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).
270
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.
271
  """
272
  )
273