FinnNick commited on
Commit
6e31989
·
verified ·
1 Parent(s): 2b7c7ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -134
app.py CHANGED
@@ -13,18 +13,13 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
  class BasicAgent:
15
  def __init__(self):
16
- self.api_key = os.getenv("GEMINI_API_KEY")
 
17
  if not self.api_key:
18
- raise ValueError("❌ Переменная окружения GEMINI_API_KEY не найдена.")
19
-
20
- self.model = "gemini-1.5-pro"
21
- self.api_url = f"https://generativelanguage.googleapis.com/v1/models/{self.model}:generateContent?key={self.api_key}"
22
- print(f"✅ Подключение к Gemini API: {self.api_url}")
23
 
24
  def __call__(self, question: str) -> str:
25
- if not isinstance(question, str) or not question.strip():
26
- return "❌ Неверный формат вопроса."
27
-
28
  headers = {
29
  "Content-Type": "application/json"
30
  }
@@ -38,39 +33,37 @@ class BasicAgent:
38
  ]
39
  }
40
 
41
- try:
42
- response = requests.post(self.api_url, headers=headers, json=payload, timeout=30)
 
43
 
44
- if response.status_code == 429:
45
- print("⚠️ 429 Too Many Requests спим 10 секунд...")
46
- time.sleep(10)
47
- return "Превышен лимит запросов. Подождите немного."
 
48
 
49
- if response.status_code == 400:
50
- print("❌ Ошибка 400 — неверный формат запроса. Ответ:", response.text[:300])
51
- return "Ошибка 400: Неправильный формат запроса."
52
 
53
- response.raise_for_status()
54
 
55
- data = response.json()
56
- return data["candidates"][0]["content"]["parts"][0]["text"]
57
 
58
- except Exception as e:
59
- print("❌ Ошибка при вызове Gemini API:", e)
60
- return f"Ошибка Gemini API: {e}"
61
 
62
-
63
 
64
- def run_and_submit_all( profile: gr.OAuthProfile | None):
65
- """
66
- Fetches all questions, runs the BasicAgent on them, submits all answers,
67
- and displays the results.
68
- """
69
- # --- Determine HF Space Runtime URL and Repo URL ---
70
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
71
 
72
  if profile:
73
- username= f"{profile.username}"
74
  print(f"User logged in: {username}")
75
  else:
76
  print("User not logged in.")
@@ -80,67 +73,49 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
80
  questions_url = f"{api_url}/questions"
81
  submit_url = f"{api_url}/submit"
82
 
83
- # 1. Instantiate Agent ( modify this part to create your agent)
84
  try:
85
  agent = BasicAgent()
86
  except Exception as e:
87
- print(f"Error instantiating agent: {e}")
88
  return f"Error initializing agent: {e}", None
89
- # 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)
90
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
91
  print(agent_code)
92
 
93
- # 2. Fetch Questions
94
  print(f"Fetching questions from: {questions_url}")
95
  try:
96
  response = requests.get(questions_url, timeout=15)
97
  response.raise_for_status()
98
  questions_data = response.json()
99
  if not questions_data:
100
- print("Fetched questions list is empty.")
101
- return "Fetched questions list is empty or invalid format.", None
102
  print(f"Fetched {len(questions_data)} questions.")
103
- except requests.exceptions.RequestException as e:
104
- print(f"Error fetching questions: {e}")
105
- return f"Error fetching questions: {e}", None
106
- except requests.exceptions.JSONDecodeError as e:
107
- print(f"Error decoding JSON response from questions endpoint: {e}")
108
- print(f"Response text: {response.text[:500]}")
109
- return f"Error decoding server response for questions: {e}", None
110
  except Exception as e:
111
- print(f"An unexpected error occurred fetching questions: {e}")
112
- return f"An unexpected error occurred fetching questions: {e}", None
113
 
114
- # 3. Run your Agent
115
  results_log = []
116
  answers_payload = []
117
  print(f"Running agent on {len(questions_data)} questions...")
 
118
  for item in questions_data:
119
  task_id = item.get("task_id")
120
  question_text = item.get("question")
121
  if not task_id or question_text is None:
122
- print(f"Skipping item with missing task_id or question: {item}")
123
  continue
124
  try:
125
  submitted_answer = agent(question_text)
126
- time.sleep(3)
127
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
128
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
129
  except Exception as e:
130
- print(f"Error running agent on task {task_id}: {e}")
131
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
132
 
133
  if not answers_payload:
134
- print("Agent did not produce any answers to submit.")
135
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
136
 
137
- # 4. Prepare Submission
138
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
139
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
140
- print(status_update)
141
-
142
- # 5. Submit
143
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
144
  try:
145
  response = requests.post(submit_url, json=submission_data, timeout=60)
146
  response.raise_for_status()
@@ -152,88 +127,22 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
152
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
153
  f"Message: {result_data.get('message', 'No message received.')}"
154
  )
155
- print("Submission successful.")
156
- results_df = pd.DataFrame(results_log)
157
- return final_status, results_df
158
- except requests.exceptions.HTTPError as e:
159
- error_detail = f"Server responded with status {e.response.status_code}."
160
- try:
161
- error_json = e.response.json()
162
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
163
- except requests.exceptions.JSONDecodeError:
164
- error_detail += f" Response: {e.response.text[:500]}"
165
- status_message = f"Submission Failed: {error_detail}"
166
- print(status_message)
167
- results_df = pd.DataFrame(results_log)
168
- return status_message, results_df
169
- except requests.exceptions.Timeout:
170
- status_message = "Submission Failed: The request timed out."
171
- print(status_message)
172
- results_df = pd.DataFrame(results_log)
173
- return status_message, results_df
174
- except requests.exceptions.RequestException as e:
175
- status_message = f"Submission Failed: Network error - {e}"
176
- print(status_message)
177
- results_df = pd.DataFrame(results_log)
178
- return status_message, results_df
179
  except Exception as e:
180
- status_message = f"An unexpected error occurred during submission: {e}"
181
- print(status_message)
182
- results_df = pd.DataFrame(results_log)
183
- return status_message, results_df
184
 
185
 
186
- # --- Build Gradio Interface using Blocks ---
187
  with gr.Blocks() as demo:
188
- gr.Markdown("# Basic Agent Evaluation Runner")
189
- gr.Markdown(
190
- """
191
- **Instructions:**
192
-
193
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
194
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
195
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
196
-
197
- ---
198
- **Disclaimers:**
199
- 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).
200
- 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.
201
- """
202
- )
203
 
204
  gr.LoginButton()
205
-
206
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
 
207
 
208
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
209
- # Removed max_rows=10 from DataFrame constructor
210
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
211
-
212
- run_button.click(
213
- fn=run_and_submit_all,
214
- outputs=[status_output, results_table]
215
- )
216
 
217
  if __name__ == "__main__":
218
- print("\n" + "-"*30 + " App Starting " + "-"*30)
219
- # Check for SPACE_HOST and SPACE_ID at startup for information
220
- space_host_startup = os.getenv("SPACE_HOST")
221
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
222
-
223
- if space_host_startup:
224
- print(f"✅ SPACE_HOST found: {space_host_startup}")
225
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
226
- else:
227
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
228
-
229
- if space_id_startup: # Print repo URLs if SPACE_ID is found
230
- print(f"✅ SPACE_ID found: {space_id_startup}")
231
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
232
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
233
- else:
234
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
235
-
236
- print("-"*(60 + len(" App Starting ")) + "\n")
237
-
238
- print("Launching Gradio Interface for Basic Agent Evaluation...")
239
- demo.launch(debug=True, share=False)
 
13
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
  class BasicAgent:
15
  def __init__(self):
16
+ self.api_key = os.getenv("GEMINI_API_KEY") # Убедись, что ключ установлен в переменных окружения
17
+ self.api_url = "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key=" + self.api_key
18
  if not self.api_key:
19
+ raise ValueError("❌ Отсутствует переменная окружения GEMINI_API_KEY")
20
+ print("✅ Gemini Agent initialized.")
 
 
 
21
 
22
  def __call__(self, question: str) -> str:
 
 
 
23
  headers = {
24
  "Content-Type": "application/json"
25
  }
 
33
  ]
34
  }
35
 
36
+ for attempt in range(3): # Повтор до 3 раз
37
+ try:
38
+ response = requests.post(self.api_url, headers=headers, json=payload, timeout=30)
39
 
40
+ if response.status_code == 429:
41
+ wait_time = 5 * (attempt + 1)
42
+ print(f"⚠️ Попытка {attempt+1}: 429 Too Many Requests. Ждём {wait_time} сек...")
43
+ time.sleep(wait_time)
44
+ continue
45
 
46
+ if response.status_code == 400:
47
+ print("❌ Ошибка 400. Ответ:", response.text)
48
+ return "Ошибка 400: Неверный формат запроса"
49
 
50
+ response.raise_for_status()
51
 
52
+ data = response.json()
53
+ return data["candidates"][0]["content"]["parts"][0]["text"]
54
 
55
+ except Exception as e:
56
+ print("❌ Ошибка Gemini API:", e)
57
+ return f"Ошибка Gemini API: {e}"
58
 
59
+ return "❌ Не удалось получить ответ от Gemini API после нескольких попыток."
60
 
61
+
62
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
63
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
64
 
65
  if profile:
66
+ username = f"{profile.username}"
67
  print(f"User logged in: {username}")
68
  else:
69
  print("User not logged in.")
 
73
  questions_url = f"{api_url}/questions"
74
  submit_url = f"{api_url}/submit"
75
 
 
76
  try:
77
  agent = BasicAgent()
78
  except Exception as e:
 
79
  return f"Error initializing agent: {e}", None
80
+
81
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
82
  print(agent_code)
83
 
 
84
  print(f"Fetching questions from: {questions_url}")
85
  try:
86
  response = requests.get(questions_url, timeout=15)
87
  response.raise_for_status()
88
  questions_data = response.json()
89
  if not questions_data:
90
+ return "Fetched questions list is empty or invalid format.", None
 
91
  print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
92
  except Exception as e:
93
+ return f"Error fetching questions: {e}", None
 
94
 
 
95
  results_log = []
96
  answers_payload = []
97
  print(f"Running agent on {len(questions_data)} questions...")
98
+
99
  for item in questions_data:
100
  task_id = item.get("task_id")
101
  question_text = item.get("question")
102
  if not task_id or question_text is None:
 
103
  continue
104
  try:
105
  submitted_answer = agent(question_text)
 
106
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
107
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
108
  except Exception as e:
109
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
110
+
111
+ time.sleep(3) # ⏳ Задержка между запросами
112
 
113
  if not answers_payload:
 
114
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
115
 
 
116
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
117
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
118
+
119
  try:
120
  response = requests.post(submit_url, json=submission_data, timeout=60)
121
  response.raise_for_status()
 
127
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
128
  f"Message: {result_data.get('message', 'No message received.')}"
129
  )
130
+ return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  except Exception as e:
132
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
133
 
134
 
135
+ # --- Gradio UI ---
136
  with gr.Blocks() as demo:
137
+ gr.Markdown("# Gemini Agent Evaluation (Unit 4)")
138
+ gr.Markdown("Log in to Hugging Face and submit your answers to the GAIA benchmark.")
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  gr.LoginButton()
 
141
  run_button = gr.Button("Run Evaluation & Submit All Answers")
142
+ status_output = gr.Textbox(label="Status", lines=5, interactive=False)
143
+ results_table = gr.DataFrame(label="Results", wrap=True)
144
 
145
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
 
 
 
 
146
 
147
  if __name__ == "__main__":
148
+ demo.launch(debug=True)