Spaces:
Running
Running
File size: 22,786 Bytes
226ac39 f5a1bc3 226ac39 227cb22 226ac39 f5a1bc3 226ac39 be4eb33 b8bcf55 226ac39 b8bcf55 226ac39 b8bcf55 226ac39 f5a1bc3 226ac39 ba50130 226ac39 ba50130 226ac39 ba50130 f5a1bc3 4eacfaa ba50130 226ac39 f5a1bc3 4eacfaa f5a1bc3 226ac39 f5a1bc3 226ac39 f5a1bc3 226ac39 b213e33 226ac39 fde5dd3 226ac39 fde5dd3 226ac39 eeeb8b7 226ac39 eeeb8b7 226ac39 eeeb8b7 226ac39 eeeb8b7 226ac39 eeeb8b7 226ac39 eeeb8b7 226ac39 48520bd 226ac39 |
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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 |
"""
FastAPI Application for Google Cloud Run
Thin HTTP wrapper around DataScienceCopilot - No logic changes, just API exposure.
"""
import os
import sys
import tempfile
import shutil
import time
from pathlib import Path
from typing import Optional, Dict, Any, List
import logging
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request
from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
# Import from parent package
from src.orchestrator import DataScienceCopilot
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize FastAPI
app = FastAPI(
title="Data Science Agent API",
description="Cloud Run wrapper for autonomous data science workflows",
version="1.0.0"
)
# Enable CORS for frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure this properly in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize agent once (singleton pattern for stateless service)
# Agent itself is stateless - no conversation memory between requests
agent: Optional[DataScienceCopilot] = None
# Global progress tracking (in-memory for simplicity)
progress_store: Dict[str, List[Dict[str, Any]]] = {}
# Mount static files for React frontend
frontend_path = Path(__file__).parent.parent.parent / "FRRONTEEEND" / "dist"
if frontend_path.exists():
app.mount("/assets", StaticFiles(directory=str(frontend_path / "assets")), name="assets")
logger.info(f"β
Frontend assets mounted from {frontend_path}")
@app.on_event("startup")
async def startup_event():
"""Initialize DataScienceCopilot on service startup."""
global agent
try:
logger.info("Initializing DataScienceCopilot...")
provider = os.getenv("LLM_PROVIDER", "mistral")
# Auto-enable compact prompts for Mistral/Groq (smaller context windows)
use_compact = provider.lower() in ["mistral", "groq"]
agent = DataScienceCopilot(
reasoning_effort="medium",
provider=provider,
use_compact_prompts=use_compact
)
logger.info(f"β
Agent initialized with provider: {agent.provider}")
if use_compact:
logger.info("π§ Compact prompts enabled for small context window")
except Exception as e:
logger.error(f"β Failed to initialize agent: {e}")
raise
@app.get("/api/health")
async def root():
"""Health check endpoint."""
return {
"service": "Data Science Agent API",
"status": "healthy",
"provider": agent.provider if agent else "not initialized",
"tools_available": len(agent.tool_functions) if agent else 0
}
@app.get("/api/progress/{session_id}")
async def get_progress(session_id: str):
"""Get progress updates for a specific session."""
return {
"session_id": session_id,
"steps": progress_store.get(session_id, [])
}
@app.get("/health")
async def health_check():
"""
Health check for Cloud Run.
Returns 200 if service is ready to accept requests.
"""
if agent is None:
raise HTTPException(status_code=503, detail="Agent not initialized")
return {
"status": "healthy",
"agent_ready": True,
"provider": agent.provider,
"tools_count": len(agent.tool_functions)
}
class AnalysisRequest(BaseModel):
"""Request model for analysis endpoint (JSON body)."""
task_description: str
target_col: Optional[str] = None
use_cache: bool = True
max_iterations: int = 20
@app.post("/run")
async def run_analysis(
file: Optional[UploadFile] = File(None, description="Dataset file (CSV or Parquet) - optional for follow-up requests"),
task_description: str = Form(..., description="Natural language task description"),
target_col: Optional[str] = Form(None, description="Target column name for prediction"),
use_cache: bool = Form(True, description="Enable caching for expensive operations"),
max_iterations: int = Form(20, description="Maximum workflow iterations"),
session_id: Optional[str] = Form(None, description="Session ID for follow-up requests")
) -> JSONResponse:
"""
Run complete data science workflow on uploaded dataset.
This is a thin wrapper - all logic lives in DataScienceCopilot.analyze().
Args:
file: CSV or Parquet file upload
task_description: Natural language description of the task
target_col: Optional target column for ML tasks
use_cache: Whether to use cached results
max_iterations: Maximum number of workflow steps
Returns:
JSON response with analysis results, workflow history, and execution stats
Example:
```bash
curl -X POST http://localhost:8080/run \
-F "file=@data.csv" \
-F "task_description=Analyze this dataset and predict house prices" \
-F "target_col=price"
```
"""
if agent is None:
raise HTTPException(status_code=503, detail="Agent not initialized")
# Handle follow-up requests (no file, using session memory)
if file is None:
logger.info(f"Follow-up request without file, using session memory")
logger.info(f"Task: {task_description}")
# Initialize progress tracking
session_key = session_id or "default"
progress_store[session_key] = []
def progress_callback(tool_name: str, status: str):
"""Callback to track progress"""
progress_store[session_key].append({
"tool": tool_name,
"status": status,
"timestamp": time.time()
})
# Set progress callback on existing agent
agent.progress_callback = progress_callback
try:
# Agent's session memory should resolve file_path from context
result = agent.analyze(
file_path="", # Empty - will be resolved by session memory
task_description=task_description,
target_col=target_col,
use_cache=use_cache,
max_iterations=max_iterations
)
logger.info(f"Follow-up analysis completed: {result.get('status')}")
# Make result JSON serializable
def make_json_serializable(obj):
if isinstance(obj, dict):
return {k: make_json_serializable(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [make_json_serializable(item) for item in obj]
elif hasattr(obj, '__class__') and obj.__class__.__name__ in ['Figure', 'Axes', 'Artist']:
return f"<{obj.__class__.__name__} object - see artifacts>"
elif isinstance(obj, (str, int, float, bool, type(None))):
return obj
else:
try:
return str(obj)
except:
return f"<{type(obj).__name__}>"
serializable_result = make_json_serializable(result)
return JSONResponse(
content={
"success": result.get("status") == "success",
"result": serializable_result,
"metadata": {
"filename": "session_context",
"task": task_description,
"target": target_col,
"provider": agent.provider,
"follow_up": True
}
},
status_code=200
)
except Exception as e:
logger.error(f"Follow-up analysis failed: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": str(e),
"error_type": type(e).__name__,
"message": "Follow-up request failed. Make sure you've uploaded a file first."
}
)
# Validate file format for new uploads
filename = file.filename.lower()
if not (filename.endswith('.csv') or filename.endswith('.parquet')):
raise HTTPException(
status_code=400,
detail="Invalid file format. Only CSV and Parquet files are supported."
)
# Use /tmp for Cloud Run (ephemeral storage)
temp_dir = Path("/tmp") / "data_science_agent"
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = None
try:
# Save uploaded file to temporary location
temp_file_path = temp_dir / file.filename
logger.info(f"Saving uploaded file to: {temp_file_path}")
with open(temp_file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
logger.info(f"File saved successfully: {file.filename} ({os.path.getsize(temp_file_path)} bytes)")
# Initialize progress tracking for this session
session_key = session_id or "default"
progress_store[session_key] = []
def progress_callback(tool_name: str, status: str):
"""Callback to track progress"""
progress_store[session_key].append({
"tool": tool_name,
"status": status,
"timestamp": time.time()
})
# Set progress callback on existing agent
agent.progress_callback = progress_callback
# Call existing agent logic
logger.info(f"Starting analysis with task: {task_description}")
result = agent.analyze(
file_path=str(temp_file_path),
task_description=task_description,
target_col=target_col,
use_cache=use_cache,
max_iterations=max_iterations
)
logger.info(f"Analysis completed: {result.get('status')}")
# Filter out non-JSON-serializable objects (like matplotlib/plotly Figures)
def make_json_serializable(obj):
"""Recursively convert objects to JSON-serializable format."""
if isinstance(obj, dict):
return {k: make_json_serializable(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [make_json_serializable(item) for item in obj]
elif hasattr(obj, '__class__') and obj.__class__.__name__ in ['Figure', 'Axes', 'Artist']:
# Skip matplotlib/plotly Figure objects
return f"<{obj.__class__.__name__} object - see artifacts>"
elif isinstance(obj, (str, int, float, bool, type(None))):
return obj
else:
# Try to convert to string for other types
try:
return str(obj)
except:
return f"<{type(obj).__name__}>"
serializable_result = make_json_serializable(result)
# Return result with progress tracking
return JSONResponse(
content={
"success": result.get("status") == "success",
"result": serializable_result,
"progress": progress_store.get(session_key, []),
"session_id": session_key,
"metadata": {
"filename": file.filename,
"task": task_description,
"target": target_col,
"provider": agent.provider
}
},
status_code=200
)
except Exception as e:
logger.error(f"Analysis failed: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": str(e),
"error_type": type(e).__name__,
"message": "Analysis workflow failed. Check logs for details."
}
)
finally:
# Keep temporary file for session continuity (follow-up requests)
# Files in /tmp are automatically cleaned up by the OS
# For HuggingFace Spaces: space restart clears /tmp
# For production: implement session-based cleanup after timeout
pass
@app.post("/profile")
async def profile_dataset(
file: UploadFile = File(..., description="Dataset file (CSV or Parquet)")
) -> JSONResponse:
"""
Quick dataset profiling without full workflow.
Returns basic statistics, data types, and quality issues.
Useful for initial data exploration without running full analysis.
Example:
```bash
curl -X POST http://localhost:8080/profile \
-F "file=@data.csv"
```
"""
if agent is None:
raise HTTPException(status_code=503, detail="Agent not initialized")
filename = file.filename.lower()
if not (filename.endswith('.csv') or filename.endswith('.parquet')):
raise HTTPException(
status_code=400,
detail="Invalid file format. Only CSV and Parquet files are supported."
)
temp_dir = Path("/tmp") / "data_science_agent"
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file_path = None
try:
# Save file temporarily
temp_file_path = temp_dir / file.filename
with open(temp_file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Import profiling tool directly
from tools.data_profiling import profile_dataset as profile_tool
from tools.data_profiling import detect_data_quality_issues
# Run profiling tools
logger.info(f"Profiling dataset: {file.filename}")
profile_result = profile_tool(str(temp_file_path))
quality_result = detect_data_quality_issues(str(temp_file_path))
return JSONResponse(
content={
"success": True,
"filename": file.filename,
"profile": profile_result,
"quality_issues": quality_result
},
status_code=200
)
except Exception as e:
logger.error(f"Profiling failed: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": str(e),
"error_type": type(e).__name__
}
)
finally:
if temp_file_path and temp_file_path.exists():
try:
temp_file_path.unlink()
except Exception as e:
logger.warning(f"Failed to cleanup temp file: {e}")
@app.get("/tools")
async def list_tools():
"""
List all available tools in the agent.
Returns tool names organized by category.
Useful for understanding agent capabilities.
"""
if agent is None:
raise HTTPException(status_code=503, detail="Agent not initialized")
from tools.tools_registry import get_tools_by_category
return {
"total_tools": len(agent.tool_functions),
"tools_by_category": get_tools_by_category(),
"all_tools": list(agent.tool_functions.keys())
}
class ChatMessage(BaseModel):
"""Chat message model."""
role: str # 'user' or 'assistant'
content: str
class ChatRequest(BaseModel):
"""Chat request model."""
messages: List[ChatMessage]
stream: bool = False
@app.post("/chat")
async def chat(request: ChatRequest) -> JSONResponse:
"""
Chat endpoint for conversational interface.
Processes chat messages and returns agent responses.
Uses the same underlying agent as /run but in chat format.
Args:
request: Chat request with message history
Returns:
JSON response with agent's reply
"""
if agent is None:
raise HTTPException(status_code=503, detail="Agent not initialized")
try:
# Extract the latest user message
user_messages = [msg for msg in request.messages if msg.role == "user"]
if not user_messages:
raise HTTPException(status_code=400, detail="No user message found")
latest_message = user_messages[-1].content
# Check for API key
api_key = os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY")
if not api_key:
raise HTTPException(
status_code=500,
detail="GOOGLE_API_KEY or GEMINI_API_KEY not configured. Please set the environment variable."
)
# Use Google Gemini API
import google.generativeai as genai
logger.info(f"Configuring Gemini with API key (length: {len(api_key)})")
genai.configure(api_key=api_key)
# Safety settings for data science content
safety_settings = [
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
]
# Initialize Gemini model (system_instruction not supported in this SDK version)
model = genai.GenerativeModel(
model_name=os.getenv("GEMINI_MODEL", "gemini-2.5-flash-lite"),
generation_config={"temperature": 0.7},
safety_settings=safety_settings
)
# System message will be prepended to first user message
system_msg = "You are a Senior Data Science Autonomous Agent. You help users with end-to-end machine learning, data profiling, visualization, and strategic insights. Use a professional, technical yet accessible tone. Provide code snippets in Python if requested. You have access to tools for data analysis, ML training, visualization, and more.\\n\\n"
# Convert messages to Gemini format (exclude system message, just conversation)
chat_history = []
first_user_msg = True
for msg in request.messages[:-1]: # Exclude the latest message
content = msg.content
# Prepend system instruction to first user message
if first_user_msg and msg.role == "user":
content = system_msg + content
first_user_msg = False
chat_history.append({
"role": "user" if msg.role == "user" else "model",
"parts": [content]
})
# Start chat with history
chat = model.start_chat(history=chat_history)
# Send the latest message
response = chat.send_message(latest_message)
assistant_message = response.text
return JSONResponse(
content={
"success": True,
"message": assistant_message,
"model": "gemini-2.0-flash-exp",
"provider": "gemini"
},
status_code=200
)
except Exception as e:
logger.error(f"Chat failed: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail={
"error": str(e),
"error_type": type(e).__name__
}
)
# Error handlers
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
"""Custom error response format."""
return JSONResponse(
status_code=exc.status_code,
content={
"success": False,
"error": exc.detail,
"status_code": exc.status_code
}
)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
"""Catch-all error handler."""
logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
return JSONResponse(
status_code=500,
content={
"success": False,
"error": "Internal server error",
"detail": str(exc),
"error_type": type(exc).__name__
}
)
@app.get("/outputs/{file_path:path}")
async def serve_output_files(file_path: str):
"""
Serve generated output files (reports, plots, models, etc.).
"""
output_path = Path("./outputs") / file_path
if not output_path.exists():
raise HTTPException(status_code=404, detail=f"File not found: {file_path}")
if not output_path.is_file():
raise HTTPException(status_code=400, detail="Path is not a file")
# Security: prevent directory traversal
try:
output_path.resolve().relative_to(Path("./outputs").resolve())
except ValueError:
raise HTTPException(status_code=403, detail="Access denied")
# Determine media type based on file extension
media_type = None
if file_path.endswith('.html'):
media_type = "text/html"
elif file_path.endswith('.csv'):
media_type = "text/csv"
elif file_path.endswith('.json'):
media_type = "application/json"
elif file_path.endswith('.png'):
media_type = "image/png"
elif file_path.endswith('.jpg') or file_path.endswith('.jpeg'):
media_type = "image/jpeg"
return FileResponse(output_path, media_type=media_type)
@app.get("/{full_path:path}")
async def serve_frontend(full_path: str):
"""
Serve React frontend for all non-API routes.
This should be the last route defined.
"""
frontend_path = Path(__file__).parent.parent.parent / "FRRONTEEEND" / "dist"
# Try to serve the requested file
file_path = frontend_path / full_path
if file_path.is_file():
return FileResponse(file_path)
# Default to index.html for client-side routing
index_path = frontend_path / "index.html"
if index_path.exists():
return FileResponse(index_path)
# Frontend not built
raise HTTPException(
status_code=404,
detail="Frontend not found. Please build the frontend first: cd FRRONTEEEND && npm run build"
)
# Cloud Run listens on PORT environment variable
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", 8080))
uvicorn.run(
"app:app",
host="0.0.0.0",
port=port,
log_level="info"
)
|