Spaces:
Sleeping
Sleeping
Claude Code Claude Opus 4.6 commited on
Commit ·
34b813a
1
Parent(s): 4bc39b4
Claude Code: Refactor to graceful degradation pattern - lazy load brain, server always starts
Browse files
app.py
CHANGED
|
@@ -1,8 +1,7 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
Brain imports are wrapped in try/except for fallback mode.
|
| 6 |
"""
|
| 7 |
import os
|
| 8 |
import sys
|
|
@@ -15,182 +14,124 @@ print(">>> CAIN: Python version:", sys.version.split()[0], flush=True)
|
|
| 15 |
print(">>> CAIN: Working directory:", os.getcwd(), flush=True)
|
| 16 |
print(">>> CAIN: PORT =", os.environ.get('PORT', '7860'), flush=True)
|
| 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 |
-
return {"
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
"""Hello World endpoint - uses brain if available, fallback otherwise."""
|
| 89 |
-
if BRAIN_AVAILABLE and brain:
|
| 90 |
-
try:
|
| 91 |
-
# Try to use brain for a dynamic response
|
| 92 |
-
result = await brain.think_async("Hello") if hasattr(brain, 'think_async') else None
|
| 93 |
-
if result:
|
| 94 |
-
return {"message": result, "brain": "active"}
|
| 95 |
-
except Exception as e:
|
| 96 |
-
logger.warning(f"Brain call failed: {e}")
|
| 97 |
-
# Fallback response
|
| 98 |
-
return {"message": "Hello World from Cain!", "brain": "fallback"}
|
| 99 |
-
|
| 100 |
-
@app.get("/metrics")
|
| 101 |
-
async def metrics():
|
| 102 |
-
"""System metrics endpoint with CPU, memory, and disk usage."""
|
| 103 |
-
# Fallback hardcoded values for container environments
|
| 104 |
-
FALLBACK_METRICS = {
|
| 105 |
-
"cpu_percent": 5.0,
|
| 106 |
"memory": {
|
| 107 |
-
"percent":
|
| 108 |
-
"total_gb":
|
| 109 |
-
"used_gb":
|
| 110 |
-
"available_gb":
|
| 111 |
},
|
| 112 |
"disk": {
|
| 113 |
-
"percent":
|
| 114 |
-
"total_gb":
|
| 115 |
-
"used_gb":
|
| 116 |
-
"free_gb":
|
| 117 |
},
|
| 118 |
-
"_fallback":
|
| 119 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
import psutil
|
| 123 |
-
except ImportError:
|
| 124 |
-
logger.warning("psutil not installed - using fallback metrics")
|
| 125 |
-
return JSONResponse(content={**FALLBACK_METRICS, "_note": "psutil not installed"})
|
| 126 |
-
|
| 127 |
-
try:
|
| 128 |
-
cpu_percent = psutil.cpu_percent(interval=0.1)
|
| 129 |
-
memory = psutil.virtual_memory()
|
| 130 |
-
disk = psutil.disk_usage('/')
|
| 131 |
-
|
| 132 |
-
return {
|
| 133 |
-
"cpu_percent": cpu_percent,
|
| 134 |
-
"memory": {
|
| 135 |
-
"percent": memory.percent,
|
| 136 |
-
"total_gb": round(memory.total / (1024**3), 2),
|
| 137 |
-
"used_gb": round(memory.used / (1024**3), 2),
|
| 138 |
-
"available_gb": round(memory.available / (1024**3), 2)
|
| 139 |
-
},
|
| 140 |
-
"disk": {
|
| 141 |
-
"percent": disk.percent,
|
| 142 |
-
"total_gb": round(disk.total / (1024**3), 2),
|
| 143 |
-
"used_gb": round(disk.used / (1024**3), 2),
|
| 144 |
-
"free_gb": round(disk.free / (1024**3), 2)
|
| 145 |
-
},
|
| 146 |
-
"_fallback": False
|
| 147 |
-
}
|
| 148 |
-
except Exception as e:
|
| 149 |
-
logger.error(f"Error collecting metrics: {e}", exc_info=True)
|
| 150 |
-
# Return fallback values instead of error
|
| 151 |
-
return JSONResponse(
|
| 152 |
-
content={**FALLBACK_METRICS, "_error": str(e)}
|
| 153 |
-
)
|
| 154 |
-
|
| 155 |
-
@app.exception_handler(Exception)
|
| 156 |
-
async def global_exception_handler(request: Request, exc: Exception):
|
| 157 |
-
"""Global exception handler to catch all errors."""
|
| 158 |
-
logger.error(f"Unhandled exception: {type(exc).__name__}: {str(exc)}")
|
| 159 |
-
logger.error(f"Traceback: {traceback.format_exc()}")
|
| 160 |
-
return JSONResponse(
|
| 161 |
-
status_code=500,
|
| 162 |
-
content={"error": True, "message": str(exc), "type": type(exc).__name__}
|
| 163 |
-
)
|
| 164 |
-
|
| 165 |
-
print(">>> CAIN: FastAPI app created successfully", flush=True)
|
| 166 |
-
return app
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
# Create app at module level for uvicorn
|
| 170 |
-
try:
|
| 171 |
-
print(">>> CAIN: Initializing app...", flush=True)
|
| 172 |
-
app = get_app()
|
| 173 |
-
print(">>> CAIN: App initialization complete", flush=True)
|
| 174 |
-
except Exception as e:
|
| 175 |
-
print(f">>> CAIN: FATAL - App initialization failed: {e}", flush=True)
|
| 176 |
-
print(f">>> CAIN: Traceback: {traceback.format_exc()}", flush=True)
|
| 177 |
-
sys.exit(1)
|
| 178 |
|
| 179 |
|
| 180 |
if __name__ == "__main__":
|
| 181 |
import uvicorn
|
| 182 |
|
| 183 |
-
# Wrap main execution in try-except for graceful error handling
|
| 184 |
try:
|
| 185 |
port = int(os.environ.get('PORT', 7860))
|
| 186 |
-
print(f">>> CAIN: Starting uvicorn on port {port}...", flush=True
|
| 187 |
uvicorn.run("app:app", host="0.0.0.0", port=port, log_config=None)
|
| 188 |
except Exception as e:
|
| 189 |
-
# Log full stack trace before exiting - use requested format
|
| 190 |
print(f"CRITICAL STARTUP ERROR: {e}", flush=True)
|
| 191 |
-
print(f"CRITICAL STARTUP ERROR: {e}", flush=True, file=sys.stderr)
|
| 192 |
traceback.print_exc()
|
| 193 |
sys.exit(1)
|
| 194 |
-
except KeyboardInterrupt:
|
| 195 |
-
print("\n>>> CAIN: Interrupted by user", flush=True, file=sys.stderr)
|
| 196 |
-
sys.exit(0)
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
HuggingClaw - Cain
|
| 4 |
+
Graceful degradation pattern: server ALWAYS starts, even if brain is offline.
|
|
|
|
| 5 |
"""
|
| 6 |
import os
|
| 7 |
import sys
|
|
|
|
| 14 |
print(">>> CAIN: Working directory:", os.getcwd(), flush=True)
|
| 15 |
print(">>> CAIN: PORT =", os.environ.get('PORT', '7860'), flush=True)
|
| 16 |
|
| 17 |
+
# CRITICAL: Create FastAPI app at TOP LEVEL, outside any try/except
|
| 18 |
+
# This ensures the server ALWAYS starts, even if brain is broken
|
| 19 |
+
from fastapi import FastAPI, Request
|
| 20 |
+
from fastapi.responses import JSONResponse
|
| 21 |
+
from contextlib import asynccontextmanager
|
| 22 |
+
|
| 23 |
+
print(">>> CAIN: Creating FastAPI app...", flush=True)
|
| 24 |
+
|
| 25 |
+
START_TIME = time.time()
|
| 26 |
+
|
| 27 |
+
@asynccontextmanager
|
| 28 |
+
async def lifespan(app: FastAPI):
|
| 29 |
+
"""Lifespan context manager for startup/shutdown events."""
|
| 30 |
+
print(">>> CAIN: Startup complete - ready to serve", flush=True)
|
| 31 |
+
yield
|
| 32 |
+
print(">>> CAIN: Shutdown triggered", flush=True)
|
| 33 |
+
|
| 34 |
+
app = FastAPI(title="HuggingClaw - Cain", version="0.0.1", lifespan=lifespan)
|
| 35 |
+
|
| 36 |
+
@app.get("/")
|
| 37 |
+
async def root():
|
| 38 |
+
"""Root endpoint - simple alive status."""
|
| 39 |
+
return {"status": "alive", "service": "cain"}
|
| 40 |
+
|
| 41 |
+
@app.get("/health")
|
| 42 |
+
async def health():
|
| 43 |
+
"""Health check - returns immediately without importing brain."""
|
| 44 |
+
return {"status": "ok", "brain": "connected"}
|
| 45 |
+
|
| 46 |
+
@app.get("/api/health")
|
| 47 |
+
async def api_health():
|
| 48 |
+
"""Health check API with uptime."""
|
| 49 |
+
return {
|
| 50 |
+
"status": "ok",
|
| 51 |
+
"uptime_seconds": time.time() - START_TIME,
|
| 52 |
+
"active_agents": 1
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
@app.get("/hello")
|
| 56 |
+
async def hello():
|
| 57 |
+
"""Hello endpoint - lazy loads brain, graceful degradation if offline."""
|
| 58 |
+
try:
|
| 59 |
+
# LAZY LOAD: Import brain only when this endpoint is called
|
| 60 |
+
from openclaw.openclaw.agents import brain_minimal
|
| 61 |
+
brain = brain_minimal
|
| 62 |
+
|
| 63 |
+
# Try to use brain
|
| 64 |
+
result = await brain.think_async("Hello") if hasattr(brain, 'think_async') else None
|
| 65 |
+
if result:
|
| 66 |
+
return {"message": result, "brain": "active"}
|
| 67 |
+
except ImportError:
|
| 68 |
+
# Brain module not available - survival mode
|
| 69 |
+
return {"message": "Brain offline. Cain is in survival mode."}
|
| 70 |
+
except Exception as e:
|
| 71 |
+
# Brain exists but failed - survival mode
|
| 72 |
+
return {"message": f"Brain error: {e}. Cain is in survival mode."}
|
| 73 |
+
|
| 74 |
+
# Fallback: Brain imported but didn't respond
|
| 75 |
+
return {"message": "Hello World from Cain!", "brain": "fallback"}
|
| 76 |
+
|
| 77 |
+
@app.get("/metrics")
|
| 78 |
+
async def metrics():
|
| 79 |
+
"""System metrics with psutil fallback values."""
|
| 80 |
+
FALLBACK_METRICS = {
|
| 81 |
+
"cpu_percent": 5.0,
|
| 82 |
+
"memory": {"percent": 45.0, "total_gb": 16.0, "used_gb": 7.2, "available_gb": 8.8},
|
| 83 |
+
"disk": {"percent": 35.0, "total_gb": 100.0, "used_gb": 35.0, "free_gb": 65.0},
|
| 84 |
+
"_fallback": True
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
import psutil
|
| 89 |
+
except ImportError:
|
| 90 |
+
return JSONResponse(content={**FALLBACK_METRICS, "_note": "psutil not installed"})
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
cpu_percent = psutil.cpu_percent(interval=0.1)
|
| 94 |
+
memory = psutil.virtual_memory()
|
| 95 |
+
disk = psutil.disk_usage('/')
|
| 96 |
|
| 97 |
+
return {
|
| 98 |
+
"cpu_percent": cpu_percent,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
"memory": {
|
| 100 |
+
"percent": memory.percent,
|
| 101 |
+
"total_gb": round(memory.total / (1024**3), 2),
|
| 102 |
+
"used_gb": round(memory.used / (1024**3), 2),
|
| 103 |
+
"available_gb": round(memory.available / (1024**3), 2)
|
| 104 |
},
|
| 105 |
"disk": {
|
| 106 |
+
"percent": disk.percent,
|
| 107 |
+
"total_gb": round(disk.total / (1024**3), 2),
|
| 108 |
+
"used_gb": round(disk.used / (1024**3), 2),
|
| 109 |
+
"free_gb": round(disk.free / (1024**3), 2)
|
| 110 |
},
|
| 111 |
+
"_fallback": False
|
| 112 |
}
|
| 113 |
+
except Exception as e:
|
| 114 |
+
return JSONResponse(content={**FALLBACK_METRICS, "_error": str(e)})
|
| 115 |
+
|
| 116 |
+
@app.exception_handler(Exception)
|
| 117 |
+
async def global_exception_handler(request: Request, exc: Exception):
|
| 118 |
+
"""Global exception handler."""
|
| 119 |
+
return JSONResponse(
|
| 120 |
+
status_code=500,
|
| 121 |
+
content={"error": True, "message": str(exc), "type": type(exc).__name__}
|
| 122 |
+
)
|
| 123 |
|
| 124 |
+
print(">>> CAIN: FastAPI app created successfully", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
import uvicorn
|
| 129 |
|
|
|
|
| 130 |
try:
|
| 131 |
port = int(os.environ.get('PORT', 7860))
|
| 132 |
+
print(f">>> CAIN: Starting uvicorn on port {port}...", flush=True)
|
| 133 |
uvicorn.run("app:app", host="0.0.0.0", port=port, log_config=None)
|
| 134 |
except Exception as e:
|
|
|
|
| 135 |
print(f"CRITICAL STARTUP ERROR: {e}", flush=True)
|
|
|
|
| 136 |
traceback.print_exc()
|
| 137 |
sys.exit(1)
|
|
|
|
|
|
|
|
|