ashishja commited on
Commit
f4eeecb
·
verified ·
1 Parent(s): f906de9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -312
app.py CHANGED
@@ -3,268 +3,12 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
-
7
- # Try to import Google ADK components, fallback to simple agent if not available
8
- try:
9
- from google.genai import types
10
- from agent import session_service, APP_NAME, USER_ID, SESSION_ID, runner
11
- GOOGLE_ADK_AVAILABLE = True
12
- print("✅ Google ADK components loaded successfully")
13
- except ImportError as e:
14
- print(f"⚠️ Google ADK not available: {e}")
15
- print("🔄 Falling back to simple HTTP-based agent")
16
- GOOGLE_ADK_AVAILABLE = False
17
 
18
  # (Keep Constants as is)
19
  # --- Constants ---
20
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
21
 
22
- # --- Fallback Simple Agent for when Google ADK is not available ---
23
- class SimpleAgent:
24
- def __init__(self):
25
- print("SimpleAgent initialized - using basic HTTP requests")
26
-
27
- def __call__(self, question: str) -> str:
28
- print(f"SimpleAgent received question (first 50 chars): {question[:50]}...")
29
-
30
- try:
31
- # Analyze the question to understand what's needed
32
- question_lower = question.lower()
33
-
34
- # Detect GAIA-style complex questions
35
- if self._is_complex_gaia_question(question):
36
- return self._handle_complex_question(question)
37
-
38
- # Check if it's a math question
39
- elif any(word in question_lower for word in ['calculate', 'sum', 'total', 'add', 'multiply', 'divide']):
40
- return self._try_basic_math(question)
41
-
42
- # Check if it's asking for a count or number
43
- elif any(word in question_lower for word in ['how many', 'count', 'number of']):
44
- return "I would need to analyze the data to count the items. [SimpleAgent - limited capabilities]"
45
-
46
- # Check if it's asking about a file
47
- elif 'file' in question_lower or 'excel' in question_lower or 'csv' in question_lower:
48
- return "I would need to download and analyze the file to answer this question. [SimpleAgent - limited capabilities]"
49
-
50
- # Check if it's asking about a person or entity
51
- elif any(word in question_lower for word in ['who is', 'who are', 'what is']):
52
- return "I would need to search for information about this topic. [SimpleAgent - limited capabilities]"
53
-
54
- # Default response
55
- else:
56
- return f"I received your question but need more advanced capabilities to answer it properly. Question: {question[:200]}... [SimpleAgent - Google ADK not available]"
57
-
58
- except Exception as e:
59
- return f"Error processing question: {str(e)} [SimpleAgent]"
60
-
61
- def _is_complex_gaia_question(self, question):
62
- """Detect if this is a complex GAIA-style question requiring multiple steps"""
63
- indicators = [
64
- 'painting', 'film', 'movie', 'ocean liner', 'ship', 'menu',
65
- 'clockwise', 'order', 'arrangement', 'position',
66
- 'comma-separated', 'list', 'plural form',
67
- 'served as part of', 'later used as', 'floating prop'
68
- ]
69
- question_lower = question.lower()
70
- return sum(1 for indicator in indicators if indicator in question_lower) >= 3
71
-
72
- def _handle_complex_question(self, question):
73
- """Handle complex GAIA questions with basic analysis"""
74
- question_lower = question.lower()
75
-
76
- # Identify what the question is asking for
77
- steps_needed = []
78
-
79
- if 'painting' in question_lower:
80
- steps_needed.append("🎨 Analyze painting/image")
81
- if any(word in question_lower for word in ['film', 'movie']):
82
- steps_needed.append("🎬 Research film information")
83
- if any(word in question_lower for word in ['ocean liner', 'ship']):
84
- steps_needed.append("🚢 Research ship/vessel details")
85
- if 'menu' in question_lower:
86
- steps_needed.append("📋 Find historical menu information")
87
- if any(word in question_lower for word in ['clockwise', 'order', 'arrangement']):
88
- steps_needed.append("🔄 Analyze spatial arrangement")
89
-
90
- analysis = f"This appears to be a complex GAIA question requiring multiple steps:\n"
91
- for i, step in enumerate(steps_needed, 1):
92
- analysis += f"{i}. {step}\n"
93
-
94
- analysis += "\nI would need advanced capabilities including:\n"
95
- analysis += "- Image analysis for visual content\n"
96
- analysis += "- Web search for historical/factual information\n"
97
- analysis += "- Multi-step reasoning to connect different pieces of information\n"
98
- analysis += "\n[SimpleAgent - Complex GAIA question detected but cannot solve]"
99
-
100
- return analysis
101
-
102
- def _try_basic_math(self, question):
103
- """Try to extract and solve basic math from the question"""
104
- try:
105
- # Very basic math extraction - look for numbers
106
- import re
107
- numbers = re.findall(r'\d+\.?\d*', question)
108
- if len(numbers) >= 2:
109
- nums = [float(n) for n in numbers[:2]]
110
- if 'add' in question.lower() or 'sum' in question.lower():
111
- result = nums[0] + nums[1]
112
- return f"Basic calculation: {nums[0]} + {nums[1]} = {result} [SimpleAgent - basic math]"
113
- elif 'multiply' in question.lower():
114
- result = nums[0] * nums[1]
115
- return f"Basic calculation: {nums[0]} × {nums[1]} = {result} [SimpleAgent - basic math]"
116
-
117
- return "I can see this involves math but need more advanced capabilities to solve it. [SimpleAgent - limited math]"
118
- except:
119
- return "I can see this involves math but couldn't parse it. [SimpleAgent - limited math]"
120
-
121
- # --- Google ADK Agent Wrapper ---
122
- # ----- USING THE ACTUAL GOOGLE ADK AGENT FROM AGENT.PY ------
123
- class GoogleADKAgent:
124
- def __init__(self):
125
- print("GoogleADKAgent initialized with Google ADK runner and agents.")
126
-
127
- try:
128
- # Use the pre-configured runner and root_agent from agent.py
129
- self.runner = runner
130
- self.session_service = session_service
131
- self.app_name = APP_NAME
132
- self.user_id = USER_ID
133
- self.question_counter = 0 # To create unique session IDs for each question
134
- self.initialized = True
135
- print("✅ Google ADK Agent successfully initialized using pre-configured runner")
136
-
137
- except Exception as e:
138
- print(f"❌ Failed to initialize Google ADK Agent: {e}")
139
- self.initialized = False
140
- raise e
141
-
142
- def __call__(self, question: str) -> str:
143
- print(f"Agent received question (first 50 chars): {question[:50]}...")
144
-
145
- if not self.initialized:
146
- return "Google ADK Agent not properly initialized"
147
-
148
- try:
149
- # Use the default session instead of creating new ones
150
- # This avoids the async session creation issue
151
- session_id_to_use = SESSION_ID
152
- print(f"🚀 Using default session: {session_id_to_use}")
153
-
154
- # Create the query content
155
- query_content = types.Content(
156
- role='user',
157
- parts=[types.Part(text=question)]
158
- )
159
-
160
- # Run the agent synchronously using the runner with correct parameters
161
- events = list(self.runner.run(
162
- user_id=self.user_id,
163
- session_id=session_id_to_use,
164
- new_message=query_content
165
- ))
166
-
167
- print(f"📊 Generated {len(events)} events")
168
-
169
- # Debug: Print event details
170
- for i, event in enumerate(events):
171
- print(f"Event {i}: author={getattr(event, 'author', 'unknown')}, content_type={type(getattr(event, 'content', None))}")
172
- if hasattr(event, 'content') and event.content and hasattr(event.content, 'parts'):
173
- for j, part in enumerate(event.content.parts):
174
- if hasattr(part, 'text') and part.text:
175
- print(f" Part {j}: {part.text[:100]}...")
176
-
177
- # Extract the final answer from the events
178
- final_answer = "No response generated."
179
-
180
- # Extract the final answer with GAIA-specific processing
181
- final_answer = self._extract_gaia_answer(events)
182
-
183
- # Clean up the answer for exact matching
184
- final_answer = self._clean_answer_for_exact_match(final_answer)
185
-
186
- print(f"Agent returning answer: {final_answer[:100]}...")
187
- return final_answer
188
-
189
- except Exception as e:
190
- error_msg = f"Error running Google ADK agent: {str(e)}"
191
- print(error_msg)
192
- return error_msg
193
-
194
- def _extract_gaia_answer(self, events):
195
- """Extract the final answer from events with GAIA-specific logic"""
196
- final_answer = "No response generated."
197
-
198
- # Collect all text responses from the agent
199
- all_responses = []
200
- for event in events:
201
- if event.content and event.content.parts:
202
- for part in event.content.parts:
203
- if part.text and part.text.strip():
204
- text = part.text.strip()
205
- # Skip system messages and tool calls, but keep substantial responses
206
- if (not text.startswith("I'll") and
207
- not text.startswith("Let me") and
208
- not text.startswith("I need to") and
209
- len(text) > 10):
210
- all_responses.append(text)
211
-
212
- # For GAIA questions, prefer the last substantial response
213
- if all_responses:
214
- # Look for responses that seem like final answers
215
- for response in reversed(all_responses):
216
- # Skip responses that are clearly intermediate steps
217
- if not any(phrase in response.lower() for phrase in [
218
- "let me", "i need to", "first", "next", "then", "now i'll"
219
- ]):
220
- final_answer = response
221
- break
222
-
223
- # If no clear final answer, use the last response
224
- if final_answer == "No response generated.":
225
- final_answer = all_responses[-1]
226
- else:
227
- # Fallback: get any text response
228
- for event in reversed(events):
229
- if event.content and event.content.parts:
230
- for part in event.content.parts:
231
- if part.text and part.text.strip():
232
- final_answer = part.text.strip()
233
- break
234
- if final_answer != "No response generated.":
235
- break
236
-
237
- return final_answer
238
-
239
- def _clean_answer_for_exact_match(self, answer):
240
- """Clean the answer for exact matching requirements"""
241
- if not answer or answer == "No response generated.":
242
- return answer
243
-
244
- # Remove common prefixes that agents might add
245
- prefixes_to_remove = [
246
- "The answer is: ",
247
- "Answer: ",
248
- "Final answer: ",
249
- "FINAL ANSWER: ",
250
- "Based on my analysis, ",
251
- "The result is: ",
252
- ]
253
-
254
- cleaned = answer
255
- for prefix in prefixes_to_remove:
256
- if cleaned.startswith(prefix):
257
- cleaned = cleaned[len(prefix):]
258
-
259
- # Remove trailing explanations in brackets or parentheses
260
- import re
261
- cleaned = re.sub(r'\s*\[.*?\]\s*$', '', cleaned)
262
- cleaned = re.sub(r'\s*\(.*?\)\s*$', '', cleaned)
263
-
264
- # Clean up whitespace
265
- cleaned = cleaned.strip()
266
-
267
- return cleaned
268
 
269
  def run_and_submit_all( profile: gr.OAuthProfile | None):
270
  """
@@ -287,21 +31,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
287
 
288
  # 1. Instantiate Agent ( modify this part to create your agent)
289
  try:
290
- if GOOGLE_ADK_AVAILABLE:
291
- agent = GoogleADKAgent()
292
- print("✅ Using Google ADK Agent")
293
- else:
294
- agent = SimpleAgent()
295
- print("⚠️ Using Simple Agent (Google ADK not available)")
296
  except Exception as e:
297
  print(f"Error instantiating agent: {e}")
298
- # Fallback to simple agent if Google ADK fails
299
- try:
300
- agent = SimpleAgent()
301
- print("🔄 Fallback to Simple Agent due to error")
302
- except Exception as e2:
303
- print(f"Error with fallback agent: {e2}")
304
- return f"Error initializing any agent: {e}, {e2}", None
305
  # 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)
306
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
307
  print(agent_code)
@@ -334,20 +67,17 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
334
  for item in questions_data:
335
  task_id = item.get("task_id")
336
  question_text = item.get("question")
337
- file_name = item.get("file_name", "")
338
-
339
  if not task_id or question_text is None:
340
  print(f"Skipping item with missing task_id or question: {item}")
341
  continue
342
-
343
- # Enhance question with file information if available
344
- enhanced_question = question_text
345
  if file_name:
346
- file_url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
347
- enhanced_question = f"{question_text}\n\nFile available at: {file_url}"
348
-
349
  try:
350
- submitted_answer = agent(enhanced_question)
351
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
352
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
353
  except Exception as e:
@@ -409,42 +139,17 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
409
 
410
  # --- Build Gradio Interface using Blocks ---
411
  with gr.Blocks() as demo:
412
- gr.Markdown("# 🤖 GAIA Benchmark Agent Evaluation")
413
-
414
- # Add dynamic status message based on agent availability
415
- if GOOGLE_ADK_AVAILABLE:
416
- status_msg = "✅ **Google ADK Agent Active** - Full capabilities for complex GAIA questions including multi-step reasoning, web search, code execution, file analysis, and multimodal understanding."
417
- else:
418
- status_msg = "⚠️ **Simple Agent Active** - Limited capabilities. Google ADK not available in this environment. Can detect GAIA question types but cannot solve them."
419
-
420
- gr.Markdown(f"**Agent Status:** {status_msg}")
421
-
422
  gr.Markdown(
423
  """
424
- ## About GAIA Benchmark
425
-
426
- This evaluation uses questions from the **GAIA benchmark** - a challenging dataset that tests AI agents on:
427
- - 🔍 **Multi-step reasoning** across different domains
428
- - 🖼️ **Multimodal understanding** (text, images, files)
429
- - 🔗 **Multi-hop information retrieval**
430
- - 📊 **Structured output formatting**
431
- - 🎯 **Exact answer matching**
432
-
433
- **Example GAIA Question:**
434
- *"Which of the fruits shown in the 2008 painting 'Embroidery from Uzbekistan' were served as part of the October 1949 breakfast menu for the ocean liner that was later used as a floating prop for the film 'The Last Voyage'?"*
435
-
436
- ---
437
-
438
  **Instructions:**
439
- 1. **Clone this space** and customize the agent code for your approach
440
- 2. **Log in** to your Hugging Face account using the button below
441
- 3. **Run Evaluation** to test your agent on 20 filtered GAIA questions
442
- 4. **Submit answers** for scoring with exact match evaluation
443
-
444
- **Target:** Aim for ~30% accuracy on Level 1 GAIA questions (current benchmark performance)
445
-
446
  ---
447
- **Note:** Evaluation may take several minutes as the agent processes complex multi-step questions.
 
 
448
  """
449
  )
450
 
@@ -483,4 +188,4 @@ if __name__ == "__main__":
483
  print("-"*(60 + len(" App Starting ")) + "\n")
484
 
485
  print("Launching Gradio Interface for Basic Agent Evaluation...")
486
- demo.launch(debug=True, share=True)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from agent import BasicAgent
 
 
 
 
 
 
 
 
 
 
7
 
8
  # (Keep Constants as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  def run_and_submit_all( profile: gr.OAuthProfile | None):
14
  """
 
31
 
32
  # 1. Instantiate Agent ( modify this part to create your agent)
33
  try:
34
+ agent = BasicAgent()
 
 
 
 
 
35
  except Exception as e:
36
  print(f"Error instantiating agent: {e}")
37
+ return f"Error initializing agent: {e}", None
 
 
 
 
 
 
38
  # 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)
39
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
40
  print(agent_code)
 
67
  for item in questions_data:
68
  task_id = item.get("task_id")
69
  question_text = item.get("question")
 
 
70
  if not task_id or question_text is None:
71
  print(f"Skipping item with missing task_id or question: {item}")
72
  continue
73
+ file_name = item.get("file_name")
74
+ file_ext = None
75
+ file_url = None
76
  if file_name:
77
+ file_ext = file_name.split(".")[-1]
78
+ file_url = f"{api_url}/files/{task_id}"
 
79
  try:
80
+ submitted_answer = agent(question_text, file_url, file_ext)
81
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
82
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
83
  except Exception as e:
 
139
 
140
  # --- Build Gradio Interface using Blocks ---
141
  with gr.Blocks() as demo:
142
+ gr.Markdown("# Basic Agent Evaluation Runner")
 
 
 
 
 
 
 
 
 
143
  gr.Markdown(
144
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  **Instructions:**
146
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
147
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
148
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
 
 
149
  ---
150
+ **Disclaimers:**
151
+ 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).
152
+ 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.
153
  """
154
  )
155
 
 
188
  print("-"*(60 + len(" App Starting ")) + "\n")
189
 
190
  print("Launching Gradio Interface for Basic Agent Evaluation...")
191
+ demo.launch(debug=True, share=False)