manaankit commited on
Commit
3190a87
Β·
verified Β·
1 Parent(s): 8f6e3b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +384 -105
app.py CHANGED
@@ -1,126 +1,405 @@
 
 
1
  import os
2
- import json
3
- import pandas as pd
4
- from typing import Optional, List, Dict
 
 
 
5
 
6
- import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Optional: Use transformers/torchvision for image analysis if available
9
- try:
10
- from PIL import Image
11
- from io import BytesIO
12
- import torch
13
- from transformers import BlipProcessor, BlipForConditionalGeneration
14
- HAS_VISION = True
15
- except ImportError:
16
- HAS_VISION = False
17
-
18
- # Path to local GAIA metadata
19
- GAIA_METADATA_PATH = "GAIA/2023/validation/metadata.jsonl"
20
- GAIA_FILES_BASE = "GAIA/2023/validation/"
21
-
22
- def load_gaia_metadata() -> List[Dict]:
23
- with open(GAIA_METADATA_PATH, "r", encoding="utf-8") as f:
24
- return [json.loads(line) for line in f]
25
-
26
- class GeneralAIAssistant:
27
- def __init__(self):
28
- if HAS_VISION:
29
- self.vision_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
30
- self.vision_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
 
 
 
31
  else:
32
- self.vision_processor = None
33
- self.vision_model = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- def __call__(self, question: str, file_path: Optional[str] = None) -> (str, str):
36
- reasoning = []
37
- answer = None
 
 
 
 
38
 
39
- if file_path:
40
- reasoning.append(f"File provided: {file_path}")
41
- file_analysis = self.analyze_file(file_path)
42
- reasoning.append(f"File analysis: {file_analysis}")
 
 
 
43
 
44
- answer = self.answer_question(question)
45
- reasoning.append(f"Answered: {answer}")
46
 
47
- return answer, " | ".join(reasoning)
 
 
 
 
 
 
 
 
 
 
48
 
49
- def analyze_file(self, file_path):
50
- if not HAS_VISION:
51
- return "Image analysis unavailable (missing dependencies)."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  try:
53
- with open(file_path, "rb") as f:
54
- img = Image.open(f).convert("RGB")
55
- inputs = self.vision_processor(images=img, return_tensors="pt")
56
- out = self.vision_model.generate(**inputs)
57
- caption = self.vision_processor.decode(out[0], skip_special_tokens=True)
58
- return f"Image caption: {caption}"
59
  except Exception as e:
60
- return f"File analysis failed: {e}"
61
-
62
- def answer_question(self, question):
63
- q = question.lower()
64
- if "capital of france" in q:
65
- return "Paris"
66
- if "12 * 8" in q or "12 times 8" in q:
67
- return "96"
68
- if "pride and prejudice" in q:
69
- return "Jane Austen"
70
- if "boiling point of water" in q:
71
- return "100"
72
- return "unknown"
73
-
74
- def run_and_submit_all(username):
75
- if not username or not username.strip():
76
- return "Please enter your username.", None
77
 
 
 
 
 
 
78
  try:
79
- questions = load_gaia_metadata()
80
- except Exception as e:
81
- return f"Failed to load GAIA metadata: {e}", None
82
-
83
- agent = GeneralAIAssistant()
84
- output_lines = []
85
- for item in questions:
86
- q = item.get("question")
87
- task_id = item.get("task_id")
88
- file_path = None
89
- if "file_name" in item and item["file_name"]:
90
- file_path = os.path.join(GAIA_FILES_BASE, item["file_name"])
91
- model_answer, reasoning_trace = agent(q, file_path)
92
- output_obj = {
93
- "task_id": task_id,
94
- "model_answer": model_answer,
95
- "reasoning_trace": reasoning_trace
96
- }
97
- output_lines.append(json.dumps(output_obj, ensure_ascii=False))
98
- # For Gradio, show as a single text output
99
- return f"Processed {len(output_lines)} questions for {username}.", "\n".join(output_lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- with gr.Blocks() as demo:
102
- gr.Markdown("# GAIA Multimodal Agent Evaluation Runner")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  gr.Markdown(
104
- """
105
- **Instructions:**
106
- 1. Enter your username.
107
- 2. Click 'Run Evaluation & Submit All Answers' to process all questions and see the results.
108
- 3. Output is in the required JSON-lines format.
109
- """
110
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
- username_input = gr.Textbox(label="Username", placeholder="Enter your username here")
113
- run_button = gr.Button("Run Evaluation & Submit All Answers")
114
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
115
- results_output = gr.Textbox(label="JSONL Output", lines=20, interactive=False)
116
-
 
 
 
 
 
 
 
117
  run_button.click(
118
- fn=run_and_submit_all,
119
- inputs=[username_input],
120
- outputs=[status_output, results_output]
121
  )
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  if __name__ == "__main__":
124
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
125
- print("Launching Gradio Interface for GAIA Agent Evaluation...")
126
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
  import os
4
+ from dotenv import load_dotenv
5
+ from PIL import Image
6
+ import io
7
+ import google.generativeai as genai
8
+ from huggingface_hub import HfApi # Not strictly needed for functionality but good for HF context
9
+ import json # For robust error logging of API responses
10
 
11
+ # Load environment variables from .env file for local development
12
+ load_dotenv()
13
+
14
+ # --- Configuration ---
15
+ # API URL for the GAIA course assignment (as per the template)
16
+ COURSE_API_URL = os.getenv("API_URL", "https://huggingface.co/spaces/agents-course/gaia_api_clone")
17
+
18
+ # Global variables for API keys, can be updated by UI or .env
19
+ HF_TOKEN = os.getenv("HF_TOKEN")
20
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
21
+ SERPAPI_API_KEY = os.getenv("SERPAPI_API_KEY")
22
+
23
+ # Configure Gemini once globally, can be reconfigured if key is input via UI
24
+ if GEMINI_API_KEY:
25
+ genai.configure(api_key=GEMINI_API_KEY)
26
+ else:
27
+ print("Warning: GEMINI_API_KEY not found in environment variables. Please provide it via UI or set it as an env var.")
28
 
29
+ # --- Tools ---
30
+ def search_web_serpapi(query: str, api_key: str) -> str:
31
+ """Performs a web search using SerpApi and returns formatted snippets."""
32
+ if not api_key:
33
+ return "Web search skipped: SERPAPI_API_KEY not configured."
34
+ try:
35
+ from serpapi import GoogleSearch
36
+ params = {
37
+ "q": query,
38
+ "api_key": api_key,
39
+ "num": 3 # Get top 3 results
40
+ }
41
+ search = GoogleSearch(params)
42
+ results = search.get_dict()
43
+
44
+ snippets = []
45
+ if "organic_results" in results:
46
+ for result in results.get("organic_results", [])[:3]: # Max 3 snippets
47
+ snippet = result.get("snippet", "")
48
+ title = result.get("title", "")
49
+ link = result.get("link", "")
50
+ if snippet: # Only include if snippet is not empty
51
+ snippets.append(f"Title: {title}\nSnippet: {snippet}\nSource: {link}")
52
+
53
+ if snippets:
54
+ return "Relevant information from web search:\n" + "\n\n".join(snippets)
55
  else:
56
+ return "No relevant snippets found from web search."
57
+ except ImportError:
58
+ return "SerpApi library not installed. Web search skipped."
59
+ except Exception as e:
60
+ return f"Web search failed: {str(e)}"
61
+
62
+ # --- LLM Interaction ---
63
+ def ask_gemini_model(prompt_text: str, image_bytes: bytes = None, api_key: str = None) -> str:
64
+ """
65
+ Asks the Gemini model a question, potentially with an image.
66
+ Uses gemini-1.5-flash for a balance of capability and speed.
67
+ """
68
+ current_gemini_key = api_key or GEMINI_API_KEY # Prioritize key passed directly (e.g. from UI)
69
+ if not current_gemini_key:
70
+ return "Error: GEMINI_API_KEY not configured."
71
+
72
+ try:
73
+ # Ensure genai is configured with the potentially updated key
74
+ if genai. ΰ€…ΰ€­ΰ₯€ΰ€·ΰ₯ΰ€Ÿ.api_key != current_gemini_key: # Accessing the configured key, 'ΰ€¬ΰ€Ώΰ€¨ΰ€Ύ' is a placeholder, use actual API if exists
75
+ genai.configure(api_key=current_gemini_key)
76
+
77
+ model_name = "gemini-1.5-flash-latest"
78
+
79
+ generation_config = genai.types.GenerationConfig(
80
+ candidate_count=1,
81
+ temperature=0.2, # Lower temperature for more factual and deterministic answers
82
+ max_output_tokens=2048, # GAIA answers are generally concise
83
+ )
84
+ safety_settings = [ # Standard safety settings
85
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
86
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
87
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
88
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
89
+ ]
90
+
91
+ model = genai.GenerativeModel(
92
+ model_name=model_name,
93
+ generation_config=generation_config,
94
+ safety_settings=safety_settings
95
+ )
96
+
97
+ content_parts = [prompt_text]
98
+ if image_bytes:
99
+ try:
100
+ img_pil = Image.open(io.BytesIO(image_bytes))
101
+ # Gemini API supports various image formats directly with PIL Image object
102
+ content_parts.append(img_pil)
103
+ except Exception as e:
104
+ return f"Error: Could not process image. {str(e)}"
105
+
106
+ response = model.generate_content(content_parts)
107
+ return response.text.strip()
108
+ except Exception as e:
109
+ print(f"Error calling Gemini API: {e}")
110
+ return f"Error: Could not get response from Gemini. {str(e)}"
111
+
112
+ # --- Agent Logic ---
113
+ def solve_single_question(question_data: dict, current_hf_token: str, current_gemini_key: str, current_serpapi_key: str) -> dict:
114
+ """Solves a single GAIA question."""
115
+ task_id = question_data["task_id"]
116
+ question_text = question_data["question"]
117
+ file_name = question_data.get("file_name") # Use .get() for optional field
118
+
119
+ print(f"\nProcessing Task ID: {task_id}")
120
+ print(f"Question: {question_text}")
121
+
122
+ file_context_for_prompt = ""
123
+ image_bytes_for_llm = None
124
+
125
+ if file_name:
126
+ print(f"File detected: {file_name}")
127
+ # File download URL - no auth headers as per template for GET /files
128
+ file_url = f"{COURSE_API_URL}/files/{task_id}"
129
+ try:
130
+ response = requests.get(file_url, timeout=30) # Added timeout
131
+ response.raise_for_status()
132
+ file_content = response.content
133
+
134
+ if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.webp', '.heic', '.heif')):
135
+ image_bytes_for_llm = file_content
136
+ file_context_for_prompt = f"An image named '{file_name}' is associated with this question and has been provided for analysis."
137
+ print(f"Image '{file_name}' downloaded ({len(file_content)} bytes) and will be sent to LLM.")
138
+ elif file_name.lower().endswith(('.txt', '.csv', '.json', '.md', '.html', '.xml')):
139
+ try:
140
+ decoded_content = file_content.decode('utf-8')
141
+ except UnicodeDecodeError:
142
+ decoded_content = file_content.decode('latin-1', errors='replace') # Fallback encoding
143
+ file_context_for_prompt = f"The content of the text-based file '{file_name}' is:\n{decoded_content}"
144
+ print(f"Text file '{file_name}' downloaded and content extracted.")
145
+ else:
146
+ file_context_for_prompt = f"A file named '{file_name}' was provided. Its content type is not automatically processed for inclusion in this text prompt, but if it's an image, it will be sent to the LLM."
147
+ print(f"File '{file_name}' downloaded, type handling is basic (passed as image if common image type).")
148
+ # Attempt to treat as image if type is ambiguous but potentially an image
149
+ try:
150
+ Image.open(io.BytesIO(file_content))
151
+ image_bytes_for_llm = file_content
152
+ file_context_for_prompt += " (Attempting to treat as image)."
153
+ print("Treated unknown file as potential image.")
154
+ except Exception:
155
+ print("Unknown file type is not a processable image.")
156
+
157
+
158
+ except requests.exceptions.RequestException as e:
159
+ print(f"Error downloading file '{file_name}' for task {task_id}: {e}")
160
+ file_context_for_prompt = f"Error: Could not download file '{file_name}'. This may impact the ability to answer the question."
161
+
162
+ # Web Search
163
+ print(f"Performing web search for: {question_text[:60]}...")
164
+ search_results_context = search_web_serpapi(question_text, current_serpapi_key)
165
+ print(f"Web search results snippet: {search_results_context[:100]}...")
166
 
167
+ # Construct prompt for Gemini
168
+ # This prompt is critical and needs to guide the LLM to produce EXACTLY the required output format.
169
+ prompt = f"""You are an expert AI assistant. Your task is to answer the following question.
170
+ Read the question carefully and provide only the direct answer.
171
+ Do NOT include any introductory phrases (e.g., "The answer is...", "Based on the information..."), explanations, or any text other than the answer itself.
172
+ Strictly adhere to any formatting requirements mentioned in the question (e.g., comma-separated list, specific order, capitalization, pluralization).
173
+ If the question asks for a list, provide only the list. If it asks for a specific value, provide only that value.
174
 
175
+ Question: "{question_text}"
176
+ """
177
+ if file_context_for_prompt:
178
+ prompt += f"\nContext from provided file ('{file_name}'):\n{file_context_for_prompt}\n"
179
+
180
+ if search_results_context and "skipped" not in search_results_context.lower() and "failed" not in search_results_context.lower():
181
+ prompt += f"\n{search_results_context}\n"
182
 
183
+ prompt += "\nAnswer:" # LLM should start its response right after this.
 
184
 
185
+ print(f"Prompt for LLM (first 150 chars): {prompt[:150].replace(chr(10), ' ')}...") # Log a snippet
186
+
187
+ llm_answer = ask_gemini_model(prompt, image_bytes_for_llm, current_gemini_key)
188
+
189
+ # Minimal cleanup, relying on good prompting.
190
+ final_answer = llm_answer.strip()
191
+ # Ensure no "FINAL ANSWER" text as per instructions
192
+ if "FINAL ANSWER:" in final_answer:
193
+ final_answer = final_answer.split("FINAL ANSWER:", 1)[-1].strip()
194
+ if "FINAL ANSWER" in final_answer: # A bit more general
195
+ final_answer = final_answer.replace("FINAL ANSWER", "").strip()
196
 
197
+
198
+ print(f"LLM Raw Answer for Task {task_id}: {llm_answer}")
199
+ print(f"Final Processed Answer for Task {task_id}: {final_answer}")
200
+
201
+ return {"task_id": task_id, "submitted_answer": final_answer}
202
+
203
+ # --- Gradio App Main Function ---
204
+ def run_assignment_flow(hf_username_or_spacename_ui: str, hf_token_ui: str, gemini_key_ui: str, serpapi_key_ui: str):
205
+ global HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY # Allow updating global vars if UI provides new keys
206
+
207
+ log_output = "Initializing assignment run...\n"
208
+
209
+ if not hf_username_or_spacename_ui:
210
+ return "Error: Hugging Face Username (or Space Name like 'user/RepoName') is required for submission.", "", "", ""
211
+
212
+ # Update API keys from UI if provided, otherwise use existing (from env vars or previous runs)
213
+ current_hf_token = hf_token_ui if hf_token_ui else HF_TOKEN
214
+ current_gemini_key = gemini_key_ui if gemini_key_ui else GEMINI_API_KEY
215
+ current_serpapi_key = serpapi_key_ui if serpapi_key_ui else SERPAPI_API_KEY
216
+
217
+ if not current_hf_token:
218
+ return "Error: Hugging Face Token is required for submission. Please provide it via UI or set HF_TOKEN environment variable.", "", "", ""
219
+ if not current_gemini_key:
220
+ return "Error: Gemini API Key is required. Please provide it via UI or set GEMINI_API_KEY environment variable.", "", "", ""
221
+
222
+ # Update global vars for subsequent calls within this session if UI provided them
223
+ HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY = current_hf_token, current_gemini_key, current_serpapi_key
224
+
225
+ # Re-configure Gemini if a new key was provided via UI
226
+ # This check is slightly complex because genai. ΰ€…ΰ€­ΰ₯€ΰ€·ΰ₯ΰ€Ÿ.api_key is not a public API.
227
+ # Instead, just reconfigure if current_gemini_key is valid.
228
+ if current_gemini_key:
229
  try:
230
+ genai.configure(api_key=current_gemini_key)
231
+ log_output += "Gemini API Key configured.\n"
 
 
 
 
232
  except Exception as e:
233
+ log_output += f"Error configuring Gemini with provided key: {e}\n"
234
+ return log_output, "", "", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
+
237
+ log_output += f"Using API URL: {COURSE_API_URL}\n"
238
+
239
+ # 1. Get questions (No auth header for GET /questions as per template)
240
+ questions_url = f"{COURSE_API_URL}/questions"
241
  try:
242
+ log_output += f"Fetching questions from {questions_url}...\n"
243
+ response = requests.get(questions_url, timeout=30)
244
+ response.raise_for_status()
245
+ questions = response.json()
246
+ log_output += f"Successfully fetched {len(questions)} questions.\n"
247
+ if not questions:
248
+ log_output += "No questions received. Check API or token if applicable.\n"
249
+ return log_output, "", "", ""
250
+ except requests.exceptions.RequestException as e:
251
+ log_output += f"Error fetching questions: {e}\nResponse text: {response.text if 'response' in locals() else 'N/A'}\n"
252
+ return log_output, "", "", ""
253
+ except json.JSONDecodeError as e:
254
+ log_output += f"Error decoding JSON from questions response: {e}. Response content: {response.text if 'response' in locals() else 'N/A'}\n"
255
+ return log_output, "", "", ""
256
+
257
+ # 2. Solve each question
258
+ all_answers = []
259
+ for q_data in questions:
260
+ if not isinstance(q_data, dict) or "task_id" not in q_data or "question" not in q_data:
261
+ log_output += f"Skipping invalid question data format: {q_data}\n"
262
+ all_answers.append({"task_id": q_data.get("task_id", f"unknown_task_{len(all_answers)}"), "submitted_answer": "Error: Invalid question data format"})
263
+ continue
264
+ try:
265
+ ans = solve_single_question(q_data, current_hf_token, current_gemini_key, current_serpapi_key)
266
+ all_answers.append(ans)
267
+ log_output += f"Processed Task ID: {ans['task_id']}, Answer Snippet: '{str(ans['submitted_answer'])[:50]}...'\n"
268
+ except Exception as e:
269
+ task_id_err = q_data.get('task_id', 'N/A')
270
+ log_output += f"Critical error solving question {task_id_err}: {e}\n"
271
+ all_answers.append({"task_id": task_id_err, "submitted_answer": f"Error processing question: {e}"})
272
+
273
+ if not all_answers or len(all_answers) != len(questions):
274
+ log_output += "Error: Number of answers does not match number of questions. Aborting submission.\n"
275
+ return log_output, json.dumps(all_answers, indent=2), "", ""
276
+
277
+ # 3. Prepare submission
278
+ username_for_payload = hf_username_or_spacename_ui
279
+ if "/" in hf_username_or_spacename_ui: # If "user/space" is given, extract "user" for payload
280
+ username_for_payload = hf_username_or_spacename_ui.split("/")[0]
281
+
282
+ space_id = os.getenv("SPACE_ID") # e.g. "YourUser/YourSpaceName"
283
+ if space_id:
284
+ agent_code_link = f"https://huggingface.co/spaces/{space_id}/tree/main"
285
+ else: # Fallback if not running on an HF Space (e.g. local dev)
286
+ log_output += "Warning: SPACE_ID env var not found. Constructing agent_code_link from input. Ensure this is correct for submission.\n"
287
+ if "/" in hf_username_or_spacename_ui:
288
+ # Use the full "user/space" if provided in the input field
289
+ agent_code_link = f"https://huggingface.co/spaces/{hf_username_or_spacename_ui}/tree/main"
290
+ else:
291
+ # If only username provided, append a placeholder - user must ensure this is correct
292
+ agent_code_link = f"https://huggingface.co/spaces/{hf_username_or_spacename_ui}/YOUR_SPACE_NAME_HERE/tree/main"
293
+ log_output += f"Constructed a placeholder code link: {agent_code_link}. Update 'YOUR_SPACE_NAME_HERE' if needed.\n"
294
+
295
+ log_output += f"Using Username for Payload: {username_for_payload}\n"
296
+ log_output += f"Using Agent Code Link: {agent_code_link}\n"
297
+
298
+ submission_data = {
299
+ "username": username_for_payload,
300
+ "agent_code": agent_code_link,
301
+ "answers": all_answers
302
+ }
303
 
304
+ # 4. Submit (Requires HF_TOKEN in header)
305
+ submit_url = f"{COURSE_API_URL}/submit"
306
+ log_output += f"Submitting answers to {submit_url}...\n"
307
+ headers_submit = {"Authorization": f"Bearer {current_hf_token}"}
308
+
309
+ try:
310
+ response = requests.post(submit_url, json=submission_data, headers=headers_submit, timeout=60)
311
+ response.raise_for_status()
312
+ submission_result = response.json()
313
+ log_output += f"Submission successful! Result: {submission_result}\n"
314
+
315
+ score = submission_result.get("score", "N/A")
316
+ # leaderboard_html = submission_result.get("leaderboard", "") # If API returns HTML
317
+
318
+ answers_str = json.dumps(all_answers, indent=2) # Nicely formatted JSON for display
319
+ result_str = f"Score: {score}\nFull Submission Result:\n{json.dumps(submission_result, indent=2)}"
320
+
321
+ return log_output, answers_str, result_str, agent_code_link
322
+
323
+ except requests.exceptions.RequestException as e:
324
+ err_msg = f"Error submitting answers: {e}."
325
+ if 'response' in locals() and response is not None:
326
+ err_msg += f" Status: {response.status_code}. Response: {response.text}"
327
+ log_output += f"{err_msg}\n"
328
+ return log_output, json.dumps(all_answers, indent=2), "Submission failed. Check logs.", agent_code_link
329
+ except json.JSONDecodeError as e: # If server returns non-JSON error
330
+ log_output += f"Error decoding JSON from submission response: {e}. Response content: {response.text if 'response' in locals() else 'N/A'}\n"
331
+ return log_output, json.dumps(all_answers, indent=2), "Submission failed to decode server response.", agent_code_link
332
+
333
+ # --- Gradio Interface Definition ---
334
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
335
+ gr.Markdown("# GAIA Agent - Hugging Face Agents Course Final Assignment πŸš€")
336
  gr.Markdown(
337
+ "This agent attempts to solve questions from a subset of the GAIA benchmark. "
338
+ "It uses Gemini for reasoning, SerpApi for web search, and handles file inputs."
 
 
 
 
339
  )
340
+
341
+ with gr.Accordion("Setup (API Keys & User Info - use Space Secrets for deployment)", open=False):
342
+ with gr.Row():
343
+ hf_username_input = gr.Textbox(
344
+ label="HF Username or Space Name",
345
+ placeholder="Enter your HF Username (e.g., 'MyUser') or Space Name (e.g. 'MyUser/MySpace')",
346
+ info="Username is for the submission payload. If Space Name (user/repo) is entered, 'user' part is taken as username. Space Name also helps form code link if not on HF Space."
347
+ )
348
+ with gr.Row():
349
+ hf_token_input = gr.Textbox(
350
+ label="Hugging Face Token (hf_xxx)",
351
+ type="password",
352
+ placeholder="Uses HF_TOKEN secret if blank"
353
+ )
354
+ gemini_api_key_input = gr.Textbox(
355
+ label="Gemini API Key (AIza...)",
356
+ type="password",
357
+ placeholder="Uses GEMINI_API_KEY secret if blank"
358
+ )
359
+ serpapi_api_key_input = gr.Textbox(
360
+ label="SerpApi API Key (serp_...)",
361
+ type="password",
362
+ placeholder="Uses SERPAPI_API_KEY secret if blank"
363
+ )
364
 
365
+ run_button = gr.Button("Run GAIA Assignment ✨", variant="primary")
366
+
367
+ gr.Markdown("## πŸ“Š Results & Logs")
368
+ with gr.Tabs():
369
+ with gr.TabItem("πŸ“œ Run Log"):
370
+ log_output_display = gr.Textbox(label="Full Log Output", lines=15, interactive=False, show_copy_button=True)
371
+ with gr.TabItem("πŸ“ Submitted Answers"):
372
+ answers_display = gr.Code(label="Answers Sent to API (JSON)", language="json", lines=15, interactive=False)
373
+ with gr.TabItem("πŸ† Submission Score & Details"):
374
+ submission_result_display = gr.Code(label="Score and Full API Response (JSON)", language="json", lines=15, interactive=False)
375
+ agent_code_link_display = gr.Textbox(label="Agent Code Link Used in Submission", interactive=False, show_copy_button=True)
376
+
377
  run_button.click(
378
+ run_assignment_flow,
379
+ inputs=[hf_username_input, hf_token_input, gemini_api_key_input, serpapi_api_key_input],
380
+ outputs=[log_output_display, answers_display, submission_result_display, agent_code_link_display]
381
  )
382
 
383
+ gr.Markdown("---")
384
+ gr.Markdown("### About GAIA")
385
+ gr.HTML("""
386
+ <p>GAIA is a benchmark for evaluating AI assistants on real-world tasks requiring reasoning, multimodal understanding, web Browse, and tool use. Tasks are conceptually simple for humans but challenging for current AI systems.</p>
387
+ <p><strong>Key GAIA Principles:</strong></p>
388
+ <ul>
389
+ <li>πŸ” Real-world difficulty</li>
390
+ <li>🧾 Human interpretability</li>
391
+ <li>πŸ›‘οΈ Non-gameability</li>
392
+ <li>🧰 Simplicity of evaluation (concise, factual answers)</li>
393
+ </ul>
394
+ <p>This agent aims for the <strong>30% or higher score</strong> required for the course on a filtered subset of Level 1 questions.</p>
395
+ """)
396
+
397
  if __name__ == "__main__":
398
+ # This allows running the Gradio app locally for testing.
399
+ # Hugging Face Spaces will use the demo.launch() from its own mechanisms or just run the file.
400
+ # For local: HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY should be in a .env file or entered in UI.
401
+ if not (HF_TOKEN and GEMINI_API_KEY and SERPAPI_API_KEY):
402
+ print("Warning: One or more API keys (HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY) are not set in environment variables.")
403
+ print("Please set them in a .env file or provide them via the UI for local execution.")
404
+
405
+ demo.launch(debug=True) # debug=True for more detailed Gradio logs locally