added timout for gemini
Browse files
app.py
CHANGED
@@ -73,21 +73,18 @@ def generate_certificate_image(name_on_cert):
|
|
73 |
|
74 |
if not os.path.exists(certificate_template_path):
|
75 |
alt_cert_path_templates_parent = os.path.join(current_dir,"..", "templates", "certificate.png")
|
76 |
-
alt_cert_path_root = os.path.join(current_dir, "certificate.png")
|
77 |
|
78 |
if os.path.exists(alt_cert_path_templates_parent):
|
79 |
certificate_template_path = alt_cert_path_templates_parent
|
80 |
-
# The next elif is redundant if the initial check for certificate_template_path (which is alt_cert_path_root) failed.
|
81 |
-
# However, to keep it identical to the user's provided version:
|
82 |
elif os.path.exists(alt_cert_path_root):
|
83 |
certificate_template_path = alt_cert_path_root
|
84 |
else:
|
85 |
-
# The error message in the user's version was slightly different, I'll use a combined one.
|
86 |
raise FileNotFoundError(f"Certificate template not found. Checked default, ../templates/, and root relative to app.py.")
|
87 |
|
88 |
if not os.path.exists(font_path):
|
89 |
alt_font_path_parent = os.path.join(current_dir, "..","Quattrocento-Regular.ttf")
|
90 |
-
alt_font_path_root = os.path.join(current_dir, "Quattrocento-Regular.ttf")
|
91 |
|
92 |
if os.path.exists(alt_font_path_parent):
|
93 |
font_path = alt_font_path_parent
|
@@ -144,7 +141,8 @@ def get_gaia_api_questions():
|
|
144 |
try:
|
145 |
questions_url = f"{GAIA_API_BASE_URL}/questions"
|
146 |
print(f"Attempting to fetch questions from: {questions_url}")
|
147 |
-
|
|
|
148 |
response.raise_for_status()
|
149 |
return response.json(), None
|
150 |
except requests.exceptions.RequestException as e:
|
@@ -162,14 +160,11 @@ def my_agent_logic(task_id: str, question: str, files: list = None):
|
|
162 |
if files:
|
163 |
print(f"Files associated with this task: {files}")
|
164 |
|
165 |
-
# IMPORTANT: You MUST set GEMINI_API_KEY as a Space Secret for this to work.
|
166 |
gemini_api_key = os.environ.get("GEMINI_API_KEY")
|
167 |
if not gemini_api_key:
|
168 |
print("Error: GEMINI_API_KEY not found in environment variables. Please set it in Space Secrets.")
|
169 |
return f"ERROR_GEMINI_KEY_MISSING_FOR_TASK_{task_id}"
|
170 |
|
171 |
-
# Construct the prompt for Gemini
|
172 |
-
# This prompt is crucial. You will likely need to refine it.
|
173 |
prompt_parts = [
|
174 |
"You are an AI assistant answering questions for the GAIA benchmark.",
|
175 |
"Your goal is to provide the single, exact, concise, and factual answer to the question below.",
|
@@ -189,21 +184,23 @@ def my_agent_logic(task_id: str, question: str, files: list = None):
|
|
189 |
"role": "user",
|
190 |
"parts": [{"text": full_prompt}]
|
191 |
}],
|
192 |
-
"generationConfig": {
|
193 |
-
"temperature": 0.4,
|
194 |
"maxOutputTokens": 250,
|
195 |
}
|
196 |
}
|
197 |
|
198 |
api_url_with_key = f"{GEMINI_API_URL_BASE}?key={gemini_api_key}"
|
199 |
|
200 |
-
agent_computed_answer = f"ERROR_CALLING_GEMINI_FOR_TASK_{task_id}"
|
201 |
|
202 |
try:
|
203 |
headers = {"Content-Type": "application/json"}
|
204 |
print(f"Calling Gemini API for task {task_id}...")
|
205 |
-
|
206 |
-
response.
|
|
|
|
|
207 |
|
208 |
result = response.json()
|
209 |
|
@@ -212,12 +209,10 @@ def my_agent_logic(task_id: str, question: str, files: list = None):
|
|
212 |
result["candidates"][0]["content"].get("parts") and
|
213 |
result["candidates"][0]["content"]["parts"][0].get("text")):
|
214 |
agent_computed_answer = result["candidates"][0]["content"]["parts"][0]["text"].strip()
|
215 |
-
# Post-processing: remove any accidental "FINAL ANSWER:" prefix if LLM still adds it.
|
216 |
if agent_computed_answer.upper().startswith("FINAL ANSWER:"):
|
217 |
agent_computed_answer = agent_computed_answer[len("FINAL ANSWER:"):].strip()
|
218 |
else:
|
219 |
print(f"Warning: Unexpected response structure from Gemini API for task {task_id}: {result}")
|
220 |
-
# Check for promptFeedback if a candidate is missing
|
221 |
if result.get("promptFeedback") and result["promptFeedback"].get("blockReason"):
|
222 |
block_reason = result["promptFeedback"]["blockReason"]
|
223 |
print(f"Gemini API blocked the prompt for task {task_id}. Reason: {block_reason}")
|
@@ -225,6 +220,9 @@ def my_agent_logic(task_id: str, question: str, files: list = None):
|
|
225 |
else:
|
226 |
agent_computed_answer = f"ERROR_PARSING_GEMINI_RESPONSE_FOR_TASK_{task_id}"
|
227 |
|
|
|
|
|
|
|
228 |
except requests.exceptions.RequestException as e:
|
229 |
print(f"Error calling Gemini API for task {task_id}: {e}")
|
230 |
if e.response is not None:
|
@@ -288,16 +286,14 @@ def submit_agent_answers(profile: gr.OAuthProfile, answers_for_submission_state)
|
|
288 |
if not answers_for_submission_state:
|
289 |
return "No answers available to submit. Please run the agent first."
|
290 |
username = profile.username
|
291 |
-
space_id = os.getenv('SPACE_ID', '')
|
292 |
agent_code_link = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
293 |
-
# Add a temporary log message list for this function
|
294 |
submission_log_messages = [f"Preparing to submit answers for user: {username}"]
|
295 |
|
296 |
if not space_id:
|
297 |
-
# Fallback if SPACE_ID is not available
|
298 |
your_space_name_guess = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
|
299 |
if not your_space_name_guess or your_space_name_guess == 'app':
|
300 |
-
your_space_name_guess = "YOUR_SPACE_NAME_HERE"
|
301 |
agent_code_link = f"https://huggingface.co/spaces/{username}/{your_space_name_guess}/tree/main"
|
302 |
submission_log_messages.append(f"Warning: SPACE_ID not found. Constructed agent_code_link as: {agent_code_link}. Please verify this link is correct.")
|
303 |
|
@@ -308,12 +304,12 @@ def submit_agent_answers(profile: gr.OAuthProfile, answers_for_submission_state)
|
|
308 |
"agent_code": agent_code_link,
|
309 |
"answers": answers_for_submission_state
|
310 |
}
|
311 |
-
# submission_log_messages.append(f"Payload (shortened answers): {{'username': '{username}', 'agent_code': '{agent_code_link}', 'answers_count': {len(answers_for_submission_state)}}}")
|
312 |
|
313 |
try:
|
314 |
submit_url = f"{GAIA_API_BASE_URL}/submit"
|
315 |
-
print(f"Attempting to submit answers to: {submit_url} with payload: {payload}")
|
316 |
-
|
|
|
317 |
response.raise_for_status()
|
318 |
submission_response = response.json()
|
319 |
submission_log_messages.append(f"Submission successful! Response: {submission_response}")
|
@@ -325,6 +321,10 @@ def submit_agent_answers(profile: gr.OAuthProfile, answers_for_submission_state)
|
|
325 |
elif score_string: final_message = score_string
|
326 |
elif score is not None: final_message = f"Score: {score}"
|
327 |
return "\n".join(submission_log_messages) + f"\n\n➡️ Result: {final_message}"
|
|
|
|
|
|
|
|
|
328 |
except requests.exceptions.RequestException as e:
|
329 |
error_detail = f"Error submitting answers: {e}"
|
330 |
if e.response is not None:
|
|
|
73 |
|
74 |
if not os.path.exists(certificate_template_path):
|
75 |
alt_cert_path_templates_parent = os.path.join(current_dir,"..", "templates", "certificate.png")
|
76 |
+
alt_cert_path_root = os.path.join(current_dir, "certificate.png")
|
77 |
|
78 |
if os.path.exists(alt_cert_path_templates_parent):
|
79 |
certificate_template_path = alt_cert_path_templates_parent
|
|
|
|
|
80 |
elif os.path.exists(alt_cert_path_root):
|
81 |
certificate_template_path = alt_cert_path_root
|
82 |
else:
|
|
|
83 |
raise FileNotFoundError(f"Certificate template not found. Checked default, ../templates/, and root relative to app.py.")
|
84 |
|
85 |
if not os.path.exists(font_path):
|
86 |
alt_font_path_parent = os.path.join(current_dir, "..","Quattrocento-Regular.ttf")
|
87 |
+
alt_font_path_root = os.path.join(current_dir, "Quattrocento-Regular.ttf")
|
88 |
|
89 |
if os.path.exists(alt_font_path_parent):
|
90 |
font_path = alt_font_path_parent
|
|
|
141 |
try:
|
142 |
questions_url = f"{GAIA_API_BASE_URL}/questions"
|
143 |
print(f"Attempting to fetch questions from: {questions_url}")
|
144 |
+
# Adding a timeout to the GET request as well, for consistency
|
145 |
+
response = requests.get(questions_url, timeout=30) # 30-second timeout for fetching questions
|
146 |
response.raise_for_status()
|
147 |
return response.json(), None
|
148 |
except requests.exceptions.RequestException as e:
|
|
|
160 |
if files:
|
161 |
print(f"Files associated with this task: {files}")
|
162 |
|
|
|
163 |
gemini_api_key = os.environ.get("GEMINI_API_KEY")
|
164 |
if not gemini_api_key:
|
165 |
print("Error: GEMINI_API_KEY not found in environment variables. Please set it in Space Secrets.")
|
166 |
return f"ERROR_GEMINI_KEY_MISSING_FOR_TASK_{task_id}"
|
167 |
|
|
|
|
|
168 |
prompt_parts = [
|
169 |
"You are an AI assistant answering questions for the GAIA benchmark.",
|
170 |
"Your goal is to provide the single, exact, concise, and factual answer to the question below.",
|
|
|
184 |
"role": "user",
|
185 |
"parts": [{"text": full_prompt}]
|
186 |
}],
|
187 |
+
"generationConfig": {
|
188 |
+
"temperature": 0.4,
|
189 |
"maxOutputTokens": 250,
|
190 |
}
|
191 |
}
|
192 |
|
193 |
api_url_with_key = f"{GEMINI_API_URL_BASE}?key={gemini_api_key}"
|
194 |
|
195 |
+
agent_computed_answer = f"ERROR_CALLING_GEMINI_FOR_TASK_{task_id}"
|
196 |
|
197 |
try:
|
198 |
headers = {"Content-Type": "application/json"}
|
199 |
print(f"Calling Gemini API for task {task_id}...")
|
200 |
+
# --- MODIFIED LINE: Added timeout=60 ---
|
201 |
+
response = requests.post(api_url_with_key, headers=headers, json=payload, timeout=60)
|
202 |
+
# --- END OF MODIFIED LINE ---
|
203 |
+
response.raise_for_status()
|
204 |
|
205 |
result = response.json()
|
206 |
|
|
|
209 |
result["candidates"][0]["content"].get("parts") and
|
210 |
result["candidates"][0]["content"]["parts"][0].get("text")):
|
211 |
agent_computed_answer = result["candidates"][0]["content"]["parts"][0]["text"].strip()
|
|
|
212 |
if agent_computed_answer.upper().startswith("FINAL ANSWER:"):
|
213 |
agent_computed_answer = agent_computed_answer[len("FINAL ANSWER:"):].strip()
|
214 |
else:
|
215 |
print(f"Warning: Unexpected response structure from Gemini API for task {task_id}: {result}")
|
|
|
216 |
if result.get("promptFeedback") and result["promptFeedback"].get("blockReason"):
|
217 |
block_reason = result["promptFeedback"]["blockReason"]
|
218 |
print(f"Gemini API blocked the prompt for task {task_id}. Reason: {block_reason}")
|
|
|
220 |
else:
|
221 |
agent_computed_answer = f"ERROR_PARSING_GEMINI_RESPONSE_FOR_TASK_{task_id}"
|
222 |
|
223 |
+
except requests.exceptions.Timeout:
|
224 |
+
print(f"Timeout error calling Gemini API for task {task_id}.")
|
225 |
+
agent_computed_answer = f"ERROR_GEMINI_TIMEOUT_FOR_TASK_{task_id}"
|
226 |
except requests.exceptions.RequestException as e:
|
227 |
print(f"Error calling Gemini API for task {task_id}: {e}")
|
228 |
if e.response is not None:
|
|
|
286 |
if not answers_for_submission_state:
|
287 |
return "No answers available to submit. Please run the agent first."
|
288 |
username = profile.username
|
289 |
+
space_id = os.getenv('SPACE_ID', '')
|
290 |
agent_code_link = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
291 |
submission_log_messages = [f"Preparing to submit answers for user: {username}"]
|
292 |
|
293 |
if not space_id:
|
|
|
294 |
your_space_name_guess = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
|
295 |
if not your_space_name_guess or your_space_name_guess == 'app':
|
296 |
+
your_space_name_guess = "YOUR_SPACE_NAME_HERE"
|
297 |
agent_code_link = f"https://huggingface.co/spaces/{username}/{your_space_name_guess}/tree/main"
|
298 |
submission_log_messages.append(f"Warning: SPACE_ID not found. Constructed agent_code_link as: {agent_code_link}. Please verify this link is correct.")
|
299 |
|
|
|
304 |
"agent_code": agent_code_link,
|
305 |
"answers": answers_for_submission_state
|
306 |
}
|
|
|
307 |
|
308 |
try:
|
309 |
submit_url = f"{GAIA_API_BASE_URL}/submit"
|
310 |
+
print(f"Attempting to submit answers to: {submit_url} with payload: {payload}")
|
311 |
+
# Adding a timeout to the POST request for submission as well
|
312 |
+
response = requests.post(submit_url, json=payload, timeout=60)
|
313 |
response.raise_for_status()
|
314 |
submission_response = response.json()
|
315 |
submission_log_messages.append(f"Submission successful! Response: {submission_response}")
|
|
|
321 |
elif score_string: final_message = score_string
|
322 |
elif score is not None: final_message = f"Score: {score}"
|
323 |
return "\n".join(submission_log_messages) + f"\n\n➡️ Result: {final_message}"
|
324 |
+
except requests.exceptions.Timeout:
|
325 |
+
error_detail = f"Timeout error submitting answers to GAIA scoring API."
|
326 |
+
submission_log_messages.append(error_detail)
|
327 |
+
return "\n".join(submission_log_messages)
|
328 |
except requests.exceptions.RequestException as e:
|
329 |
error_detail = f"Error submitting answers: {e}"
|
330 |
if e.response is not None:
|