Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,13 @@
|
|
1 |
import gradio as gr
|
2 |
from datasets import load_dataset, Dataset
|
3 |
-
from datetime import datetime, date
|
4 |
import io
|
5 |
import os
|
6 |
from PIL import Image, ImageDraw, ImageFont
|
7 |
from huggingface_hub import login
|
8 |
-
import requests
|
9 |
-
import json
|
|
|
10 |
|
11 |
# Attempt to login using environment token
|
12 |
try:
|
@@ -141,8 +142,7 @@ def get_gaia_api_questions():
|
|
141 |
try:
|
142 |
questions_url = f"{GAIA_API_BASE_URL}/questions"
|
143 |
print(f"Attempting to fetch questions from: {questions_url}")
|
144 |
-
|
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:
|
@@ -152,65 +152,157 @@ def get_gaia_api_questions():
|
|
152 |
print(f"An unexpected error occurred while fetching questions: {e}")
|
153 |
return None, f"An unexpected error occurred: {e}"
|
154 |
|
155 |
-
def
|
156 |
"""
|
157 |
-
|
|
|
|
|
158 |
"""
|
159 |
-
|
160 |
-
if
|
161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
169 |
-
|
170 |
-
|
171 |
-
"
|
172 |
-
"
|
173 |
-
"
|
174 |
-
"
|
175 |
-
|
|
|
|
|
|
|
|
|
176 |
]
|
177 |
-
|
178 |
-
|
|
|
|
|
|
|
179 |
|
180 |
-
|
|
|
181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
182 |
payload = {
|
183 |
-
"contents": [{
|
184 |
-
"role": "user",
|
185 |
-
"parts": [{"text": full_prompt}]
|
186 |
-
}],
|
187 |
"generationConfig": {
|
188 |
-
"temperature": 0.
|
189 |
-
"maxOutputTokens":
|
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 |
|
207 |
if (result.get("candidates") and
|
208 |
result["candidates"][0].get("content") and
|
209 |
result["candidates"][0]["content"].get("parts") and
|
210 |
result["candidates"][0]["content"]["parts"][0].get("text")):
|
211 |
-
|
212 |
-
|
213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"):
|
@@ -219,7 +311,6 @@ def my_agent_logic(task_id: str, question: str, files: list = None):
|
|
219 |
agent_computed_answer = f"ERROR_GEMINI_PROMPT_BLOCKED_{block_reason}_FOR_TASK_{task_id}"
|
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}"
|
@@ -227,16 +318,14 @@ def my_agent_logic(task_id: str, question: str, files: list = None):
|
|
227 |
print(f"Error calling Gemini API for task {task_id}: {e}")
|
228 |
if e.response is not None:
|
229 |
print(f"Gemini API Error Response Status: {e.response.status_code}")
|
230 |
-
try:
|
231 |
-
|
232 |
-
except json.JSONDecodeError:
|
233 |
-
print(f"Gemini API Error Response Body (text): {e.response.text}")
|
234 |
agent_computed_answer = f"ERROR_GEMINI_REQUEST_FAILED_FOR_TASK_{task_id}"
|
235 |
except Exception as e:
|
236 |
print(f"An unexpected error occurred in my_agent_logic for task {task_id}: {e}")
|
237 |
agent_computed_answer = f"ERROR_UNEXPECTED_IN_AGENT_LOGIC_FOR_TASK_{task_id}"
|
238 |
|
239 |
-
print(f"Agent (Gemini) computed answer for Task ID {task_id}: {agent_computed_answer}")
|
240 |
return agent_computed_answer
|
241 |
|
242 |
def run_agent_on_gaia(profile: gr.OAuthProfile, run_all_questions: bool = True):
|
@@ -265,13 +354,14 @@ def run_agent_on_gaia(profile: gr.OAuthProfile, run_all_questions: bool = True):
|
|
265 |
for task in tasks_to_process:
|
266 |
task_id = task.get("task_id")
|
267 |
question = task.get("question")
|
268 |
-
|
269 |
if task_id and question:
|
270 |
log_messages.append(f"\nProcessing Task ID: {task_id}")
|
271 |
log_messages.append(f"Question: {question}")
|
272 |
-
if
|
273 |
-
log_messages.append(f"Associated files: {
|
274 |
-
|
|
|
275 |
log_messages.append(f"Agent's Answer: {submitted_answer}")
|
276 |
answers_to_submit.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
277 |
else:
|
@@ -289,26 +379,21 @@ def submit_agent_answers(profile: gr.OAuthProfile, answers_for_submission_state)
|
|
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 |
-
|
300 |
submission_log_messages.append(f"Agent Code Link: {agent_code_link}")
|
301 |
-
|
302 |
payload = {
|
303 |
"username": username,
|
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()
|
@@ -337,7 +422,7 @@ def submit_agent_answers(profile: gr.OAuthProfile, answers_for_submission_state)
|
|
337 |
submission_log_messages.append(f"An unexpected error occurred during submission: {e}")
|
338 |
return "\n".join(submission_log_messages)
|
339 |
|
340 |
-
# --- Gradio Interface ---
|
341 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
342 |
gr.Markdown("# 🎓 Agents Course - Unit 4 Final Project")
|
343 |
gr.Markdown("⚠️ **Note**: Due to high demand, you might experience occasional bugs. If something doesn't work, please try again after a moment!")
|
@@ -350,7 +435,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
350 |
with gr.Tabs():
|
351 |
with gr.TabItem("🤖 Run Agent on GAIA Benchmark"):
|
352 |
gr.Markdown("## Step 1: Run Your Agent & Generate Answers")
|
353 |
-
gr.Markdown("This agent uses the Gemini API
|
354 |
run_all_questions_checkbox = gr.Checkbox(label="Process all questions (unchecked processes 1 random question for testing)", value=True)
|
355 |
run_agent_button = gr.Button("🔎 Fetch Questions & Run My Agent")
|
356 |
gr.Markdown("### Agent Run Log & Generated Answers:")
|
|
|
1 |
import gradio as gr
|
2 |
from datasets import load_dataset, Dataset
|
3 |
+
from datetime import datetime, date
|
4 |
import io
|
5 |
import os
|
6 |
from PIL import Image, ImageDraw, ImageFont
|
7 |
from huggingface_hub import login
|
8 |
+
import requests
|
9 |
+
import json
|
10 |
+
import base64 # <-- ADDED IMPORT for image handling
|
11 |
|
12 |
# Attempt to login using environment token
|
13 |
try:
|
|
|
142 |
try:
|
143 |
questions_url = f"{GAIA_API_BASE_URL}/questions"
|
144 |
print(f"Attempting to fetch questions from: {questions_url}")
|
145 |
+
response = requests.get(questions_url, timeout=30)
|
|
|
146 |
response.raise_for_status()
|
147 |
return response.json(), None
|
148 |
except requests.exceptions.RequestException as e:
|
|
|
152 |
print(f"An unexpected error occurred while fetching questions: {e}")
|
153 |
return None, f"An unexpected error occurred: {e}"
|
154 |
|
155 |
+
def get_gaia_file_data_for_task(task_id_for_file_fetch, associated_file_metadata_list):
|
156 |
"""
|
157 |
+
Fetches the content of the primary file associated with a task_id from the GAIA API.
|
158 |
+
Returns raw_bytes, detected_mime_type, and file_name.
|
159 |
+
associated_file_metadata_list is the 'files' list from the question data.
|
160 |
"""
|
161 |
+
# If no metadata, assume no file to fetch for this specialized getter.
|
162 |
+
# Or, if the API always serves THE file for task_id, then metadata is just for info.
|
163 |
+
# Let's assume the API /files/{task_id} always gives the relevant file if one exists for the task.
|
164 |
+
|
165 |
+
file_url = f"{GAIA_API_BASE_URL}/files/{task_id_for_file_fetch}"
|
166 |
+
print(f"Attempting to fetch file for task {task_id_for_file_fetch} from {file_url}")
|
167 |
+
|
168 |
+
try:
|
169 |
+
response = requests.get(file_url, timeout=30)
|
170 |
+
response.raise_for_status() # This will error if file not found (404) or other issues
|
171 |
+
|
172 |
+
raw_bytes = response.content
|
173 |
+
detected_mime_type = response.headers.get('Content-Type', '').split(';')[0].strip()
|
174 |
+
|
175 |
+
# Try to get a filename from metadata if available, otherwise default
|
176 |
+
file_name = "attached_file"
|
177 |
+
if associated_file_metadata_list and isinstance(associated_file_metadata_list, list) and len(associated_file_metadata_list) > 0:
|
178 |
+
# Assuming the first file in metadata is the one fetched, or provides its name
|
179 |
+
first_file_meta = associated_file_metadata_list[0]
|
180 |
+
if isinstance(first_file_meta, dict) and 'file_name' in first_file_meta:
|
181 |
+
file_name = first_file_meta['file_name']
|
182 |
+
|
183 |
+
print(f"File fetched for task {task_id_for_file_fetch}. Mime-type: {detected_mime_type}, Name: {file_name}, Size: {len(raw_bytes)} bytes")
|
184 |
+
return raw_bytes, detected_mime_type, file_name
|
185 |
+
|
186 |
+
except requests.exceptions.HTTPError as http_err:
|
187 |
+
# Specifically handle 404 for "no file" vs other errors
|
188 |
+
if http_err.response.status_code == 404:
|
189 |
+
print(f"No file found (404) for task {task_id_for_file_fetch} at {file_url}.")
|
190 |
+
else:
|
191 |
+
print(f"HTTP error fetching file for task {task_id_for_file_fetch}: {http_err}")
|
192 |
+
return None, None, None
|
193 |
+
except requests.exceptions.RequestException as e:
|
194 |
+
print(f"Could not fetch file for task {task_id_for_file_fetch}: {e}. Proceeding without file content.")
|
195 |
+
return None, None, None
|
196 |
+
except Exception as e_gen:
|
197 |
+
print(f"Unexpected error fetching file for task {task_id_for_file_fetch}: {e_gen}")
|
198 |
+
return None, None, None
|
199 |
+
|
200 |
+
def my_agent_logic(task_id: str, question: str, files_metadata: list = None): # files_metadata is the list from task.get("files")
|
201 |
+
"""
|
202 |
+
Uses the Gemini API, with GAIA-specific prompting and basic file handling,
|
203 |
+
to generate an answer for the given question.
|
204 |
+
"""
|
205 |
+
print(f"Agent (GAIA-Grounded Gemini) processing Task ID: {task_id}, Question: {question}")
|
206 |
+
if files_metadata: # This is the list of file metadata dicts
|
207 |
+
print(f"File metadata associated with this task: {files_metadata}")
|
208 |
|
209 |
gemini_api_key = os.environ.get("GEMINI_API_KEY")
|
210 |
if not gemini_api_key:
|
211 |
print("Error: GEMINI_API_KEY not found in environment variables. Please set it in Space Secrets.")
|
212 |
return f"ERROR_GEMINI_KEY_MISSING_FOR_TASK_{task_id}"
|
213 |
|
214 |
+
# --- GAIA-specific System Prompt ---
|
215 |
+
# Adapted from Figure 2 of GAIA Paper [cite: 103, 104, 105, 106, 107, 108]
|
216 |
+
system_prompt_lines = [
|
217 |
+
"You are a general AI assistant. I will ask you a question.",
|
218 |
+
"Report your thoughts (for your own processing, not for the final answer), and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].", # Instructing the LLM about the template it should "think" in
|
219 |
+
"However, your actual returned response to me (the user) should ONLY be [YOUR FINAL ANSWER] part, without the 'FINAL ANSWER:' prefix.", # Clarification for our use case
|
220 |
+
"YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.",
|
221 |
+
"If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.",
|
222 |
+
"If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.",
|
223 |
+
"If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.",
|
224 |
+
"Be precise and ensure the answer strictly adheres to any format requested in the question.",
|
225 |
+
"If external files are mentioned or provided, use their content if relevant and accessible to answer the question.",
|
226 |
]
|
227 |
+
# We won't send this as a separate "system" message in Gemini's typical API structure,
|
228 |
+
# but rather prepend it to the user question for a single turn.
|
229 |
+
|
230 |
+
# --- Prepare parts for Gemini API payload ---
|
231 |
+
gemini_parts = []
|
232 |
|
233 |
+
# Prepend system prompt guidelines to the main question text part
|
234 |
+
user_question_text = "\n".join(system_prompt_lines) + f"\n\nGAIA Question: {question}"
|
235 |
|
236 |
+
# --- File Handling ---
|
237 |
+
file_content_bytes, detected_mime_type, file_name = None, None, None
|
238 |
+
if files_metadata: # If the question has associated file(s) metadata
|
239 |
+
file_content_bytes, detected_mime_type, file_name = get_gaia_file_data_for_task(task_id, files_metadata)
|
240 |
+
|
241 |
+
if file_content_bytes:
|
242 |
+
if detected_mime_type and detected_mime_type.startswith("image/"): # Handle images
|
243 |
+
try:
|
244 |
+
base64_image = base64.b64encode(file_content_bytes).decode('utf-8')
|
245 |
+
gemini_parts.append({"text": user_question_text}) # Question text first
|
246 |
+
gemini_parts.append({
|
247 |
+
"inline_data": {
|
248 |
+
"mime_type": detected_mime_type,
|
249 |
+
"data": base64_image
|
250 |
+
}
|
251 |
+
})
|
252 |
+
print(f"Added image {file_name} ({detected_mime_type}) to Gemini prompt for task {task_id}.")
|
253 |
+
except Exception as e_img:
|
254 |
+
print(f"Error processing image file {file_name} for task {task_id}: {e_img}")
|
255 |
+
gemini_parts.append({"text": user_question_text + f"\n[Agent note: An image file '{file_name}' was associated but could not be processed: {e_img}]"})
|
256 |
+
elif detected_mime_type and detected_mime_type == "text/plain": # Handle plain text files
|
257 |
+
try:
|
258 |
+
text_content = file_content_bytes.decode('utf-8')
|
259 |
+
user_question_text += f"\n\nContent of attached text file '{file_name}':\n{text_content}"
|
260 |
+
gemini_parts.append({"text": user_question_text})
|
261 |
+
print(f"Added text file content '{file_name}' to Gemini prompt for task {task_id}.")
|
262 |
+
except Exception as e_txt:
|
263 |
+
print(f"Error decoding text file {file_name} for task {task_id}: {e_txt}")
|
264 |
+
gemini_parts.append({"text": user_question_text + f"\n[Agent note: A text file '{file_name}' was associated but could not be decoded: {e_txt}]"})
|
265 |
+
else: # Other file types, just mention them
|
266 |
+
user_question_text += f"\n\nNote: A file named '{file_name}' (type: {detected_mime_type or 'unknown'}) is associated with this question. Its content is not directly viewable in this text prompt."
|
267 |
+
gemini_parts.append({"text": user_question_text})
|
268 |
+
print(f"Noted non-image/text file {file_name} ({detected_mime_type}) in Gemini prompt for task {task_id}.")
|
269 |
+
else: # No file content fetched or no files associated
|
270 |
+
gemini_parts.append({"text": user_question_text})
|
271 |
+
|
272 |
payload = {
|
273 |
+
"contents": [{"role": "user", "parts": gemini_parts}],
|
|
|
|
|
|
|
274 |
"generationConfig": {
|
275 |
+
"temperature": 0.2, # Lower temperature for more factual/deterministic GAIA answers
|
276 |
+
"maxOutputTokens": 300, # Increased slightly for potentially more complex answers
|
277 |
}
|
278 |
}
|
279 |
|
280 |
api_url_with_key = f"{GEMINI_API_URL_BASE}?key={gemini_api_key}"
|
|
|
281 |
agent_computed_answer = f"ERROR_CALLING_GEMINI_FOR_TASK_{task_id}"
|
282 |
|
283 |
try:
|
284 |
headers = {"Content-Type": "application/json"}
|
285 |
print(f"Calling Gemini API for task {task_id}...")
|
|
|
286 |
response = requests.post(api_url_with_key, headers=headers, json=payload, timeout=60)
|
|
|
287 |
response.raise_for_status()
|
|
|
288 |
result = response.json()
|
289 |
|
290 |
if (result.get("candidates") and
|
291 |
result["candidates"][0].get("content") and
|
292 |
result["candidates"][0]["content"].get("parts") and
|
293 |
result["candidates"][0]["content"]["parts"][0].get("text")):
|
294 |
+
raw_answer = result["candidates"][0]["content"]["parts"][0]["text"].strip()
|
295 |
+
|
296 |
+
# Remove the "FINAL ANSWER:" prefix if the LLM included it, despite instructions
|
297 |
+
if raw_answer.upper().startswith("FINAL ANSWER:"):
|
298 |
+
agent_computed_answer = raw_answer[len("FINAL ANSWER:"):].strip()
|
299 |
+
else:
|
300 |
+
agent_computed_answer = raw_answer
|
301 |
+
# Further cleaning: sometimes LLMs might still add subtle quotes if the answer is a simple string
|
302 |
+
if len(agent_computed_answer) > 1 and ((agent_computed_answer.startswith('"') and agent_computed_answer.endswith('"')) or \
|
303 |
+
(agent_computed_answer.startswith("'") and agent_computed_answer.endswith("'"))):
|
304 |
+
agent_computed_answer = agent_computed_answer[1:-1]
|
305 |
+
|
306 |
else:
|
307 |
print(f"Warning: Unexpected response structure from Gemini API for task {task_id}: {result}")
|
308 |
if result.get("promptFeedback") and result["promptFeedback"].get("blockReason"):
|
|
|
311 |
agent_computed_answer = f"ERROR_GEMINI_PROMPT_BLOCKED_{block_reason}_FOR_TASK_{task_id}"
|
312 |
else:
|
313 |
agent_computed_answer = f"ERROR_PARSING_GEMINI_RESPONSE_FOR_TASK_{task_id}"
|
|
|
314 |
except requests.exceptions.Timeout:
|
315 |
print(f"Timeout error calling Gemini API for task {task_id}.")
|
316 |
agent_computed_answer = f"ERROR_GEMINI_TIMEOUT_FOR_TASK_{task_id}"
|
|
|
318 |
print(f"Error calling Gemini API for task {task_id}: {e}")
|
319 |
if e.response is not None:
|
320 |
print(f"Gemini API Error Response Status: {e.response.status_code}")
|
321 |
+
try: print(f"Gemini API Error Response Body: {e.response.json()}")
|
322 |
+
except json.JSONDecodeError: print(f"Gemini API Error Response Body (text): {e.response.text}")
|
|
|
|
|
323 |
agent_computed_answer = f"ERROR_GEMINI_REQUEST_FAILED_FOR_TASK_{task_id}"
|
324 |
except Exception as e:
|
325 |
print(f"An unexpected error occurred in my_agent_logic for task {task_id}: {e}")
|
326 |
agent_computed_answer = f"ERROR_UNEXPECTED_IN_AGENT_LOGIC_FOR_TASK_{task_id}"
|
327 |
|
328 |
+
print(f"Agent (GAIA-Grounded Gemini) computed answer for Task ID {task_id}: {agent_computed_answer}")
|
329 |
return agent_computed_answer
|
330 |
|
331 |
def run_agent_on_gaia(profile: gr.OAuthProfile, run_all_questions: bool = True):
|
|
|
354 |
for task in tasks_to_process:
|
355 |
task_id = task.get("task_id")
|
356 |
question = task.get("question")
|
357 |
+
associated_files_metadata = task.get("files", []) # This is the list of file metadata dicts
|
358 |
if task_id and question:
|
359 |
log_messages.append(f"\nProcessing Task ID: {task_id}")
|
360 |
log_messages.append(f"Question: {question}")
|
361 |
+
if associated_files_metadata:
|
362 |
+
log_messages.append(f"Associated files metadata: {associated_files_metadata}")
|
363 |
+
# Pass the files_metadata to the agent logic
|
364 |
+
submitted_answer = my_agent_logic(task_id, question, associated_files_metadata)
|
365 |
log_messages.append(f"Agent's Answer: {submitted_answer}")
|
366 |
answers_to_submit.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
367 |
else:
|
|
|
379 |
space_id = os.getenv('SPACE_ID', '')
|
380 |
agent_code_link = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
381 |
submission_log_messages = [f"Preparing to submit answers for user: {username}"]
|
|
|
382 |
if not space_id:
|
383 |
your_space_name_guess = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
|
384 |
if not your_space_name_guess or your_space_name_guess == 'app':
|
385 |
your_space_name_guess = "YOUR_SPACE_NAME_HERE"
|
386 |
agent_code_link = f"https://huggingface.co/spaces/{username}/{your_space_name_guess}/tree/main"
|
387 |
submission_log_messages.append(f"Warning: SPACE_ID not found. Constructed agent_code_link as: {agent_code_link}. Please verify this link is correct.")
|
|
|
388 |
submission_log_messages.append(f"Agent Code Link: {agent_code_link}")
|
|
|
389 |
payload = {
|
390 |
"username": username,
|
391 |
"agent_code": agent_code_link,
|
392 |
"answers": answers_for_submission_state
|
393 |
}
|
|
|
394 |
try:
|
395 |
submit_url = f"{GAIA_API_BASE_URL}/submit"
|
396 |
print(f"Attempting to submit answers to: {submit_url} with payload: {payload}")
|
|
|
397 |
response = requests.post(submit_url, json=payload, timeout=60)
|
398 |
response.raise_for_status()
|
399 |
submission_response = response.json()
|
|
|
422 |
submission_log_messages.append(f"An unexpected error occurred during submission: {e}")
|
423 |
return "\n".join(submission_log_messages)
|
424 |
|
425 |
+
# --- Gradio Interface (largely unchanged from your latest version) ---
|
426 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
427 |
gr.Markdown("# 🎓 Agents Course - Unit 4 Final Project")
|
428 |
gr.Markdown("⚠️ **Note**: Due to high demand, you might experience occasional bugs. If something doesn't work, please try again after a moment!")
|
|
|
435 |
with gr.Tabs():
|
436 |
with gr.TabItem("🤖 Run Agent on GAIA Benchmark"):
|
437 |
gr.Markdown("## Step 1: Run Your Agent & Generate Answers")
|
438 |
+
gr.Markdown("This agent uses the Gemini API (with GAIA-specific prompting and basic file handling) to generate answers.")
|
439 |
run_all_questions_checkbox = gr.Checkbox(label="Process all questions (unchecked processes 1 random question for testing)", value=True)
|
440 |
run_agent_button = gr.Button("🔎 Fetch Questions & Run My Agent")
|
441 |
gr.Markdown("### Agent Run Log & Generated Answers:")
|