from fastapi import APIRouter, HTTPException, Depends
from fastapi.responses import JSONResponse
from typing import Dict, Any, List
from pydantic import BaseModel
from datetime import datetime
import psutil
import asyncio
from sqlalchemy.orm import Session
from ..services.websocket_manager import websocket_manager
from ..agents.base_agent import BaseAgent
from ..database import get_db
from ..models.health_check import DBHealthCheck
import os
import sys
router = APIRouter()
class HealthStatus(BaseModel):
"""System health status model"""
status: str
timestamp: datetime
uptime: float
memory_usage: Dict[str, float]
cpu_usage: float
active_sessions: int
llm_status: Dict[str, str]
version: str = "2.0.0"
class ComponentStatus(BaseModel):
"""Individual component status"""
name: str
status: str
last_check: datetime
details: Dict[str, Any] = {}
@router.get("/health", response_model=HealthStatus)
async def get_health_status():
"""
Get comprehensive system health status
Returns detailed information about system performance,
active sessions, and component status.
"""
try:
# Get system metrics
memory = psutil.virtual_memory()
cpu_percent = psutil.cpu_percent(interval=1)
# Get active sessions count
active_sessions = len(websocket_manager.active_connections)
# Check LLM status
llm_status = await _check_llm_status()
# Calculate uptime (simplified)
uptime = psutil.boot_time()
current_time = datetime.now().timestamp()
uptime_seconds = current_time - uptime
health_status = HealthStatus(
status="healthy" if cpu_percent < 80 and memory.percent < 85 else "warning",
timestamp=datetime.now(),
uptime=uptime_seconds,
memory_usage={
"total": round(memory.total / (1024**3), 2), # GB
"available": round(memory.available / (1024**3), 2), # GB
"percent": round(memory.percent, 1),
"used": round(memory.used / (1024**3), 2) # GB
},
cpu_usage=round(cpu_percent, 1),
active_sessions=active_sessions,
llm_status=llm_status
)
return health_status
except Exception as e:
raise HTTPException(
status_code=500,
detail={
"error": "Failed to get health status",
"message": str(e),
"type": "health_check_error"
}
)
@router.get("/health/detailed")
async def get_detailed_health():
"""
Get detailed health information for all components
Provides comprehensive status for each system component
including agents, database connections, and external services.
"""
try:
components = []
# Check WebSocket Manager
ws_status = await _check_websocket_status()
components.append(ComponentStatus(
name="WebSocket Manager",
status=ws_status["status"],
last_check=datetime.now(),
details=ws_status["details"]
))
# Check AI Agents
agent_status = await _check_agents_status()
components.append(ComponentStatus(
name="AI Agents",
status=agent_status["status"],
last_check=datetime.now(),
details=agent_status["details"]
))
# Check LLM Services
llm_detailed = await _check_llm_detailed_status()
components.append(ComponentStatus(
name="LLM Services",
status=llm_detailed["status"],
last_check=datetime.now(),
details=llm_detailed["details"]
))
# Check System Resources
system_status = await _check_system_resources()
components.append(ComponentStatus(
name="System Resources",
status=system_status["status"],
last_check=datetime.now(),
details=system_status["details"]
))
# Overall status
overall_status = "healthy"
if any(comp.status == "error" for comp in components):
overall_status = "error"
elif any(comp.status == "warning" for comp in components):
overall_status = "warning"
return {
"overall_status": overall_status,
"timestamp": datetime.now().isoformat(),
"components": [comp.model_dump() for comp in components],
"summary": {
"total_components": len(components),
"healthy": len([c for c in components if c.status == "healthy"]),
"warning": len([c for c in components if c.status == "warning"]),
"error": len([c for c in components if c.status == "error"])
}
}
except Exception as e:
raise HTTPException(
status_code=500,
detail={
"error": "Failed to get detailed health status",
"message": str(e),
"type": "detailed_health_error"
}
)
@router.get("/health/metrics")
async def get_system_metrics():
"""
Get real-time system metrics
Returns current system performance metrics for monitoring.
"""
try:
# CPU metrics
cpu_percent = psutil.cpu_percent(interval=1)
cpu_count = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
# Memory metrics
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
# Disk metrics
disk = psutil.disk_usage('/')
# Network metrics (if available)
try:
network = psutil.net_io_counters()
network_stats = {
"bytes_sent": network.bytes_sent,
"bytes_recv": network.bytes_recv,
"packets_sent": network.packets_sent,
"packets_recv": network.packets_recv
}
except Exception:
network_stats = {"error": "Network stats unavailable"}
# Process information
process = psutil.Process()
process_info = {
"pid": process.pid,
"memory_percent": round(process.memory_percent(), 2),
"cpu_percent": round(process.cpu_percent(), 2),
"num_threads": process.num_threads(),
"create_time": process.create_time()
}
return {
"timestamp": datetime.now().isoformat(),
"cpu": {
"percent": round(cpu_percent, 1),
"count": cpu_count,
"frequency": {
"current": round(cpu_freq.current, 0) if cpu_freq else None,
"min": cpu_freq.min if cpu_freq else None,
"max": round(cpu_freq.max, 0) if cpu_freq else None
}
},
"memory": {
"total": memory.total,
"available": memory.available,
"percent": round(memory.percent, 1),
"used": memory.used,
"free": memory.free
},
"swap": {
"total": swap.total,
"used": swap.used,
"free": swap.free,
"percent": round(swap.percent, 1)
},
"disk": {
"total": disk.total,
"used": disk.used,
"free": disk.free,
"percent": round((disk.used / disk.total) * 100, 1)
},
"network": network_stats,
"process": process_info,
"active_sessions": len(websocket_manager.active_connections)
}
except Exception as e:
raise HTTPException(
status_code=500,
detail={
"error": "Failed to get system metrics",
"message": str(e),
"type": "metrics_error"
}
)
@router.post("/health/test-llm")
async def test_llm_connectivity():
"""
Test LLM connectivity and response
Performs a simple test to verify that LLM services are responding correctly.
"""
try:
# Create a test agent to check LLM connectivity
test_agent = BaseAgent()
# Test each LLM provider
results = {}
# Test Groq
try:
groq_llm = test_agent._initialize_groq_llm()
if groq_llm:
test_response = await groq_llm.ainvoke("Hello, this is a connectivity test.")
results["groq"] = {
"status": "healthy",
"response_length": len(str(test_response)),
"latency": "< 1s" # Simplified
}
else:
results["groq"] = {"status": "unavailable", "error": "Failed to initialize"}
except Exception as e:
results["groq"] = {"status": "error", "error": str(e)}
# Test Gemini
try:
gemini_llm = test_agent._initialize_gemini_llm()
if gemini_llm:
test_response = await gemini_llm.ainvoke("Hello, this is a connectivity test.")
results["gemini"] = {
"status": "healthy",
"response_length": len(str(test_response)),
"latency": "< 1s" # Simplified
}
else:
results["gemini"] = {"status": "unavailable", "error": "Failed to initialize"}
except Exception as e:
results["gemini"] = {"status": "error", "error": str(e)}
# Test Ollama
try:
ollama_llm = test_agent._initialize_ollama_llm()
if ollama_llm:
test_response = await ollama_llm.ainvoke("Hello, this is a connectivity test.")
results["ollama"] = {
"status": "healthy",
"response_length": len(str(test_response)),
"latency": "< 1s" # Simplified
}
else:
results["ollama"] = {"status": "unavailable", "error": "Failed to initialize"}
except Exception as e:
results["ollama"] = {"status": "error", "error": str(e)}
# Determine overall LLM status
healthy_count = len([r for r in results.values() if r["status"] == "healthy"])
overall_status = "healthy" if healthy_count > 0 else "error"
return {
"overall_status": overall_status,
"timestamp": datetime.now().isoformat(),
"providers": results,
"summary": {
"total_providers": len(results),
"healthy_providers": healthy_count,
"primary_available": results.get("groq", {}).get("status") == "healthy"
}
}
except Exception as e:
raise HTTPException(
status_code=500,
detail={
"error": "Failed to test LLM connectivity",
"message": str(e),
"type": "llm_test_error"
}
)
# Helper functions for health checks
async def _check_llm_status() -> Dict[str, str]:
"""Check basic LLM availability"""
try:
# Check environment variables
groq_available = bool(os.getenv("GROQ_API_KEY"))
gemini_available = bool(os.getenv("GEMINI_API_KEY"))
ollama_available = True # Assume local Ollama is available
return {
"groq": "available" if groq_available else "unavailable",
"gemini": "available" if gemini_available else "unavailable",
"ollama": "available" if ollama_available else "unavailable"
}
except Exception:
return {
"groq": "unknown",
"gemini": "unknown",
"ollama": "unknown"
}
async def _check_websocket_status() -> Dict[str, Any]:
"""Check WebSocket manager status"""
try:
active_connections = len(websocket_manager.active_connections)
return {
"status": "healthy",
"details": {
"active_connections": active_connections,
"max_connections": 1000, # Configurable limit
"connection_health": "good" if active_connections < 500 else "warning"
}
}
except Exception as e:
return {
"status": "error",
"details": {"error": str(e)}
}
async def _check_agents_status() -> Dict[str, Any]:
"""Check AI agents status"""
try:
# Simple check - try to import agents
from ..agents.reasoner_agent import ReasonerAgent
from ..agents.question_generator_agent import QuestionGeneratorAgent
from ..agents.explanation_agent import ExplanationAgent
return {
"status": "healthy",
"details": {
"reasoner_agent": "available",
"question_generator_agent": "available",
"explanation_agent": "available",
"orchestrator": "available"
}
}
except Exception as e:
return {
"status": "error",
"details": {"error": str(e)}
}
async def _check_llm_detailed_status() -> Dict[str, Any]:
"""Check detailed LLM status"""
try:
llm_status = await _check_llm_status()
available_count = len([status for status in llm_status.values() if status == "available"])
status = "healthy" if available_count > 0 else "error"
if available_count == 1:
status = "warning" # Only one provider available
return {
"status": status,
"details": {
"providers": llm_status,
"available_count": available_count,
"fallback_ready": available_count > 1
}
}
except Exception as e:
return {
"status": "error",
"details": {"error": str(e)}
}
@router.get("/health/db")
async def get_db_health(db: Session = Depends(get_db)):
"""
Check database connectivity and health.
Performs a simple write and read operation to verify that the
database is connected and responsive.
"""
try:
# Create a new health check record
health_check = DBHealthCheck(status="ok")
db.add(health_check)
db.commit()
db.refresh(health_check)
# Clean up old records (optional)
# db.query(DBHealthCheck).filter(DBHealthCheck.id != health_check.id).delete()
# db.commit()
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
"message": "Database connection successful.",
"db_record": {
"id": health_check.id,
"status": health_check.status,
"timestamp": health_check.timestamp.isoformat()
}
}
except Exception as e:
raise HTTPException(
status_code=500,
detail={
"error": "Database health check failed",
"message": str(e),
"type": "db_health_error"
}
)
async def _check_system_resources() -> Dict[str, Any]:
"""Check system resource status"""
try:
memory = psutil.virtual_memory()
cpu_percent = psutil.cpu_percent(interval=0.1)
# Determine status based on resource usage
status = "healthy"
if memory.percent > 85 or cpu_percent > 80:
status = "warning"
if memory.percent > 95 or cpu_percent > 95:
status = "error"
return {
"status": status,
"details": {
"memory_percent": round(memory.percent, 1),
"cpu_percent": round(cpu_percent, 1),
"available_memory_gb": round(memory.available / (1024**3), 2),
"total_memory_gb": round(memory.total / (1024**3), 2)
}
}
except Exception as e:
return {
"status": "error",
"details": {"error": str(e)}
}