Spaces:
Running
Running
File size: 14,777 Bytes
9a6a4dc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
"""Enhanced GAIA Agent - Complete Phase 1-6 Deployment"""
import os
import gradio as gr
import requests
import pandas as pd
import sys
import traceback
from pathlib import Path
from typing import Optional, List, Union
# Load environment variables from .env file if it exists
def load_env_file():
"""Load environment variables from .env file if it exists."""
env_file = Path('.env')
if env_file.exists():
with open(env_file, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
# Load environment variables at startup
load_env_file()
# Environment setup for HuggingFace Space deployment
def setup_environment():
"""Setup environment variables for HuggingFace Space deployment."""
print("Setting up environment for HuggingFace Space...")
# Check if we're running in HuggingFace Space
space_host = os.getenv("SPACE_HOST")
space_id = os.getenv("SPACE_ID")
if space_host or space_id:
print(f"β
Running in HuggingFace Space: {space_id}")
print(f"β
Space host: {space_host}")
else:
print("βΉοΈ Running locally or environment variables not set")
# Verify API keys are available (they should be in HF Spaces secrets)
required_keys = ["MISTRAL_API_KEY", "EXA_API_KEY", "FIRECRAWL_API_KEY"]
missing_keys = []
for key in required_keys:
if os.getenv(key):
print(f"β
{key} found in environment")
else:
print(f"β οΈ {key} not found in environment")
missing_keys.append(key)
if missing_keys:
print(f"β οΈ Missing API keys: {missing_keys}")
print("βΉοΈ These should be set as HuggingFace Spaces secrets")
return len(missing_keys) == 0
# Initialize environment
ENV_READY = setup_environment()
# Import Complete Enhanced GAIA Agent
try:
from agents.complete_enhanced_gaia_agent import enhanced_gaia_agent
ENHANCED_AGENT_AVAILABLE = True
print("β
Successfully imported Complete Enhanced GAIA Agent (Phase 1-6)")
print(f"π Agent status: {enhanced_gaia_agent.get_status()}")
except Exception as e:
print(f"β Could not import Complete Enhanced GAIA Agent: {e}")
print("Traceback:", traceback.format_exc())
ENHANCED_AGENT_AVAILABLE = False
# Fallback to original agent if enhanced version fails
if not ENHANCED_AGENT_AVAILABLE:
try:
from agents.enhanced_unified_agno_agent import GAIAAgent
FALLBACK_AGNO_AVAILABLE = True
print("β
Fallback: Successfully imported Enhanced Unified AGNO Agent")
except Exception as e:
print(f"β Could not import fallback agent: {e}")
FALLBACK_AGNO_AVAILABLE = False
else:
FALLBACK_AGNO_AVAILABLE = False
# Constants
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
class DeploymentReadyGAIAAgent:
"""Complete Enhanced GAIA Agent with Phase 1-6 capabilities."""
def __init__(self):
print("DeploymentReadyGAIAAgent initializing...")
# Try enhanced agent first
if ENHANCED_AGENT_AVAILABLE and ENV_READY:
try:
self.agent = enhanced_gaia_agent
print("π Using Complete Enhanced GAIA Agent with Phase 1-6 improvements")
print(f"π Total tools available: {self.agent.get_status()['total_tools']}")
self.agent_type = "complete_enhanced"
except Exception as e:
print(f"β Complete Enhanced GAIA Agent initialization failed: {e}")
print("π Falling back to original agent...")
# Fall back to original agent
if FALLBACK_AGNO_AVAILABLE:
try:
self.agent = GAIAAgent()
print("π Using Enhanced Unified AGNO Agent (fallback)")
self.agent_type = "fallback_agno"
except Exception as e2:
print(f"β Fallback agent initialization also failed: {e2}")
raise RuntimeError(f"Both agents failed: Enhanced={e}, Fallback={e2}")
else:
raise RuntimeError(f"Enhanced agent failed and fallback not available: {e}")
elif FALLBACK_AGNO_AVAILABLE and ENV_READY:
try:
self.agent = GAIAAgent()
print("π Using Enhanced Unified AGNO Agent (fallback)")
self.agent_type = "fallback_agno"
except Exception as e:
print(f"β Fallback agent initialization failed: {e}")
raise RuntimeError(f"Fallback agent required but failed to initialize: {e}")
else:
missing_reqs = []
if not ENHANCED_AGENT_AVAILABLE and not FALLBACK_AGNO_AVAILABLE:
missing_reqs.append("No agent available (both enhanced and fallback import failed)")
if not ENV_READY:
missing_reqs.append("Environment not ready (check API keys)")
error_msg = f"Agent not available: {', '.join(missing_reqs)}"
print(f"β {error_msg}")
print("π‘ Required: MISTRAL_API_KEY, EXA_API_KEY, FIRECRAWL_API_KEY")
raise RuntimeError(error_msg)
def __call__(self, question: str, files: Optional[List[Union[str, dict]]] = None) -> str:
print(f"Agent ({self.agent_type}) received question: {question[:100]}...")
if files:
print(f"Agent received {len(files)} files: {files}")
try:
# Pass files to the underlying agent if it supports them
if hasattr(self.agent, '__call__') and 'files' in self.agent.__call__.__code__.co_varnames:
answer = self.agent(question, files)
else:
# Fallback for agents that don't support files parameter
answer = self.agent(question)
print(f"Agent response: {answer}")
return answer
except Exception as e:
print(f"Error in DeploymentReadyGAIAAgent: {e}")
traceback.print_exc()
return "unknown"
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""Fetch questions, run agent, submit answers, and display results."""
# Determine HF Space Runtime URL and Repo URL
space_id = os.getenv("SPACE_ID", "JoachimVC/gaia-enhanced-agent")
if profile:
username = f"{profile.username}"
print(f"User logged in: {username}")
else:
print("User not logged in.")
return "Please Login to Hugging Face with the button.", None
# Determine agent_code URL
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
print(f"Agent code URL: {agent_code}")
# API URLs
api_base = DEFAULT_API_URL
questions_url = f"{api_base}/questions"
submit_url = f"{api_base}/submit"
try:
# 1. Fetch Questions
print("Fetching questions...")
response = requests.get(questions_url, timeout=30)
response.raise_for_status()
questions_data = response.json()
print(f"Fetched {len(questions_data)} questions.")
# 2. Initialize Agent
agent = DeploymentReadyGAIAAgent()
# 3. Process Questions
results_log = []
answers_payload = []
print(f"Running enhanced agent on {len(questions_data)} questions...")
for i, question_data in enumerate(questions_data):
task_id = question_data.get("task_id", f"task_{i}")
question_text = question_data.get("question", "")
file_name = question_data.get("file_name", "")
print(f"Processing question {i+1}/{len(questions_data)}: {task_id}")
if file_name:
print(f"π Question has attached file: {file_name}")
try:
# Prepare files list if file is attached
files = None
if file_name and file_name.strip():
files = [file_name.strip()]
print(f"π Passing file to agent: {files}")
# Call agent with files if available
if files:
submitted_answer = agent(question_text, files)
else:
submitted_answer = agent(question_text)
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
except Exception as e:
print(f"Error processing question {task_id}: {e}")
traceback.print_exc()
error_answer = "unknown"
answers_payload.append({"task_id": task_id, "submitted_answer": error_answer})
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer})
if not answers_payload:
print("Agent did not produce any answers to submit.")
return "No answers to submit.", pd.DataFrame()
# 4. Prepare Submission
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
status_update = f"Enhanced agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
print(status_update)
# 5. Submit
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
response = requests.post(submit_url, json=submission_data, timeout=30)
# Enhanced error handling for 422 errors
if response.status_code == 422:
print(f"422 Unprocessable Entity Error Details:")
print(f"Response text: {response.text}")
try:
error_details = response.json()
print(f"Error JSON: {error_details}")
except:
print("Could not parse error response as JSON")
response.raise_for_status()
final_status = response.text
print(f"Submission successful: {final_status}")
results_df = pd.DataFrame(results_log)
return final_status, results_df
except requests.exceptions.HTTPError as e:
error_detail = f"Server responded with status {e.response.status_code}."
try:
error_json = e.response.json()
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except requests.exceptions.JSONDecodeError:
error_detail += f" Response: {e.response.text[:500]}"
status_message = f"Submission Failed: {error_detail}"
print(status_message)
results_df = pd.DataFrame(results_log) if 'results_log' in locals() else pd.DataFrame()
return status_message, results_df
except Exception as e:
status_message = f"An unexpected error occurred: {e}"
print(status_message)
traceback.print_exc()
results_df = pd.DataFrame(results_log) if 'results_log' in locals() else pd.DataFrame()
return status_message, results_df
# Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("# Complete Enhanced GAIA Agent - Phase 1-6 Deployment")
gr.Markdown(
"""
**π Complete Enhanced GAIA Agent with All Phase 1-6 Improvements**
**Instructions:**
1. Log in to your Hugging Face account using the button below.
2. Click 'Run Evaluation & Submit All Answers' to test the complete enhanced system.
**β¨ Phase 1-6 Enhanced Capabilities:**
**Phase 1 - Web Research Enhancement:**
- β
Advanced web search with Exa API integration
- β
Specialized Wikipedia research tools
- β
Multi-source research orchestration
- β
AGNO-compatible research wrappers
**Phase 2 - Audio Processing Implementation:**
- β
Audio transcription with Faster-Whisper (European open-source)
- β
Recipe and educational content analysis
- β
Multi-format audio support
**Phase 3 - Mathematical Code Execution:**
- β
Advanced mathematical engine with SymPy
- β
Secure Python code execution
- β
AST parsing and code analysis
- β
AGNO-compatible math tools
**Phase 4 - Excel Data Analysis Enhancement:**
- β
Advanced Excel file processing
- β
Financial calculations and analysis
- β
Excel formula evaluation
**Phase 5 - Advanced Video Analysis Enhancement:**
- β
Object detection and counting
- β
Computer vision engine
- β
Scene analysis and description
**Phase 6 - Complex Text Processing Enhancement:**
- β
RTL (Right-to-Left) text processing
- β
Multi-orientation OCR
- β
Advanced linguistic pattern recognition
**π― Expected Performance:**
- **Baseline:** 6/20 questions (30%)
- **Enhanced Target:** 16-18/20 questions (80-90%)
- **Improvement Factor:** 2.5-3x performance increase
**π§ Technical Features:**
- β
28+ tools with graceful degradation
- β
European open-source compliance
- β
Zero temperature for consistent results
- β
Comprehensive error handling
- β
AGNO native orchestration
"""
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(
fn=run_and_submit_all,
outputs=[status_output, results_table]
)
if __name__ == "__main__":
print("\n" + "-"*30 + " Enhanced GAIA Agent Starting " + "-"*30)
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID")
if space_host_startup:
print(f"β
SPACE_HOST found: {space_host_startup}")
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
else:
print("βΉοΈ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup:
print(f"β
SPACE_ID found: {space_id_startup}")
else:
print("βΉοΈ SPACE_ID environment variable not found, using default.")
print("-"*70)
demo.launch()
|