Spaces:
Running
Running
File size: 16,523 Bytes
3a4bdd3 c14a92e 565a379 3a4bdd3 565a379 3a4bdd3 d1ec696 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 c00b41f ed6c1cd 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 d1ec696 3a4bdd3 d1ec696 21a19e7 3a4bdd3 21a19e7 3a4bdd3 21a19e7 3a4bdd3 21a19e7 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 c14a92e 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 c00b41f 3a4bdd3 c00b41f c14a92e 3a4bdd3 ac078d2 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 3a4bdd3 c14a92e 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 565a379 3a4bdd3 cc2fef3 c14a92e 3a4bdd3 | 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 | """
main.py β FastAPI entry point for MathMinds AI
"""
import os
import sys
import asyncio
import logging
import uuid
import time
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
# Windows async fix
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
os.environ["DISABLE_MODEL_SOURCE_CHECK"] = "True"
from fastapi import FastAPI, HTTPException, status, Depends, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from app.core.limiter import limiter
from app.core.orchestrator import Orchestrator
from app.core.schemas import (
SolveRequest,
ChatSession,
Message,
SessionRename,
)
from app.core.logging_config import configure_logging
from app.core.settings import settings
from app.core.errors import AppError, ErrorCodes
from app.api.deps import (
get_orchestrator,
get_redis_pool,
get_mongo_client,
get_db_manager,
get_redis_client,
)
from app.core.security import get_current_user
# Logging
configure_logging()
logger = logging.getLogger(__name__)
MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5MB limit
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# LIFESPAN
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting MathMinds AI")
try:
get_redis_pool()
get_mongo_client()
get_orchestrator()
logger.info("Startup complete")
except Exception as e:
logger.critical(f"Startup failure: {e}")
yield
logger.info("Shutting down MathMinds")
try:
from app.api.deps import close_redis, close_mongo
close_redis()
close_mongo()
logger.info("Shutdown complete")
except Exception as e:
logger.error(f"Shutdown error: {e}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FASTAPI APP
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(
title="MathMinds AI API",
description="AI-powered math solver API",
version="1.0.0",
lifespan=lifespan,
)
# Rate limiter
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# CORS
allowed_origins = os.getenv("ALLOWED_ORIGINS", "*").split(",")
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# MIDDLEWARE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request_id = str(uuid.uuid4())
request.state.request_id = request_id
start_time = time.time()
logger.info(
"Request started",
extra={
"request_id": request_id,
"path": request.url.path,
"method": request.method,
},
)
response = await call_next(request)
duration = time.time() - start_time
response.headers["X-Request-ID"] = request_id
logger.info(
"Request finished",
extra={
"request_id": request_id,
"status_code": response.status_code,
"duration": duration,
},
)
return response
@app.middleware("http")
async def timeout_middleware(request: Request, call_next):
try:
return await asyncio.wait_for(call_next(request), timeout=120)
except asyncio.TimeoutError:
logger.error(f"Timeout: {request.url.path}")
return JSONResponse(
status_code=504,
content={"detail": "Request timed out"},
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# EXCEPTION HANDLERS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
request_id = getattr(request.state, "request_id", "unknown")
logger.error(
f"[{request_id}] Unhandled error: {exc}",
exc_info=True
)
return JSONResponse(
status_code=500,
content={
"status": "error",
"error": "Internal Server Error",
"metadata": {
"request_id": request_id,
"timestamp": datetime.now(timezone.utc).isoformat(),
},
},
)
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError):
mapping = {
ErrorCodes.INPUT_VALIDATION_ERROR: 400,
ErrorCodes.RESOURCE_NOT_FOUND: 404,
ErrorCodes.RATE_LIMIT_EXCEEDED: 429,
ErrorCodes.DEPENDENCY_ERROR: 503,
ErrorCodes.GEMINI_ERROR: 503,
}
status_code = mapping.get(exc.code, 500)
request_id = getattr(request.state, "request_id", "unknown")
return JSONResponse(
status_code=status_code,
content={
"status": "error",
"error": exc.message,
"error_code": exc.code,
"metadata": {
"request_id": request_id,
"timestamp": datetime.now(timezone.utc).isoformat(),
},
},
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# GENERAL ROUTES
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/")
async def root():
return {"message": "MathMinds API running"}
@app.get("/version")
async def version():
return {
"version": "1.0.0",
"build": os.getenv("BUILD_ID"),
"commit": os.getenv("GIT_SHA"),
}
@app.get("/health")
async def health():
health: Dict[str, Any] = {
"status": "healthy",
"timestamp": datetime.now(timezone.utc).isoformat(),
"services": {},
}
try:
# 2s timeout for Redis
ping_task = asyncio.to_thread(get_redis_client().ping)
await asyncio.wait_for(ping_task, timeout=2.0)
health["services"]["redis"] = "healthy"
except Exception as e:
health["services"]["redis"] = str(e)
health["status"] = "degraded"
try:
# 2s timeout for Mongo
mongo_ping = asyncio.to_thread(get_mongo_client().admin.command, "ping")
await asyncio.wait_for(mongo_ping, timeout=2.0)
health["services"]["mongodb"] = "healthy"
except Exception as e:
health["services"]["mongodb"] = str(e)
health["status"] = "degraded"
return health
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# SOLVE ROUTE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/solve")
@limiter.limit("5/minute")
async def solve_problem(
request: Request,
solve_req: SolveRequest,
orchestrator: Orchestrator = Depends(get_orchestrator),
current_user: dict = Depends(get_current_user),
):
"""
Solve a math problem and return the result.
"""
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
if not solve_req.effective_text and not solve_req.image:
raise HTTPException(
status_code=400,
detail="Either text or image must be provided",
)
if solve_req.image and len(solve_req.image) > MAX_IMAGE_SIZE:
raise HTTPException(
status_code=413,
detail="Image too large",
)
logger.info(
"Solve request received",
extra={
"request_id": request_id,
"user_id": current_user["uid"],
"session_id": solve_req.session_id,
},
)
try:
result = await orchestrator.solve_problem(
query=solve_req.effective_text,
image=solve_req.image,
user_id=current_user["uid"],
session_id=solve_req.session_id,
request_id=request_id,
)
return JSONResponse(status_code=200, content=result)
except Exception as e:
logger.error(f"Solve error: {e}")
raise HTTPException(
status_code=500,
detail="Internal processing error",
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ANALYZE ROUTE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/analyze")
@limiter.limit("5/minute")
async def analyze_problem(
request: Request,
solve_req: SolveRequest,
orchestrator: Orchestrator = Depends(get_orchestrator),
current_user: dict = Depends(get_current_user),
):
"""Analyze user's work and grade it."""
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
if not solve_req.image:
raise HTTPException(
status_code=400,
detail="An image of the user's work must be provided for analysis.",
)
if len(solve_req.image) > MAX_IMAGE_SIZE:
raise HTTPException(status_code=413, detail="Image too large")
logger.info("Analyze request received", extra={"request_id": request_id, "user_id": current_user["uid"]})
try:
result = await orchestrator.solve_problem(
query=solve_req.effective_text,
image=solve_req.image,
user_id=current_user["uid"],
session_id=solve_req.session_id,
request_id=request_id,
mode="analyzer"
)
return JSONResponse(status_code=200, content=result)
except Exception as e:
logger.error(f"Analyze error: {e}")
raise HTTPException(status_code=500, detail="Internal processing error")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# TUTOR ROUTE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/tutor")
@limiter.limit("5/minute")
async def tutor_problem(
request: Request,
solve_req: SolveRequest,
orchestrator: Orchestrator = Depends(get_orchestrator),
current_user: dict = Depends(get_current_user),
):
"""Socratic tutoring session endpoint."""
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
if not solve_req.effective_text and not solve_req.image:
raise HTTPException(status_code=400, detail="Either text or image must be provided")
if solve_req.image and len(solve_req.image) > MAX_IMAGE_SIZE:
raise HTTPException(status_code=413, detail="Image too large")
logger.info("Tutor request received", extra={"request_id": request_id, "user_id": current_user["uid"]})
try:
result = await orchestrator.solve_problem(
query=solve_req.effective_text,
image=solve_req.image,
user_id=current_user["uid"],
session_id=solve_req.session_id,
request_id=request_id,
mode="tutor"
)
return JSONResponse(status_code=200, content=result)
except Exception as e:
logger.error(f"Tutor error: {e}")
raise HTTPException(status_code=500, detail="Internal processing error")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CHAT ROUTES
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/chat/sessions", response_model=List[ChatSession])
async def list_sessions(
current_user: dict = Depends(get_current_user),
db_manager=Depends(get_db_manager),
):
return db_manager.list_sessions(current_user["uid"])
@app.post("/chat/sessions", response_model=ChatSession)
async def create_session(
current_user: dict = Depends(get_current_user),
db_manager=Depends(get_db_manager),
):
session_id = str(uuid.uuid4())
title = "New Chat"
if db_manager.create_session(current_user["uid"], session_id, title):
return {
"session_id": session_id,
"title": title,
"created_at": datetime.now(timezone.utc),
}
raise HTTPException(500, "Failed to create session")
@app.get("/chat/sessions/{session_id}/messages", response_model=List[Message])
async def get_messages(
session_id: str,
current_user: dict = Depends(get_current_user),
db_manager=Depends(get_db_manager),
):
history = db_manager.get_chat_history(current_user["uid"], session_id)
if history is None:
raise HTTPException(404, "Session not found")
return history
@app.patch("/chat/sessions/{session_id}")
async def rename_session(
session_id: str,
rename_data: SessionRename,
current_user: dict = Depends(get_current_user),
db_manager=Depends(get_db_manager),
):
if db_manager.rename_session(
current_user["uid"],
session_id,
rename_data.title,
):
return {"status": "success"}
raise HTTPException(404, "Session not found")
@app.delete("/chat/sessions/{session_id}")
async def delete_session(
session_id: str,
current_user: dict = Depends(get_current_user),
db_manager=Depends(get_db_manager),
):
if db_manager.delete_session(current_user["uid"], session_id):
return {"status": "success"}
raise HTTPException(404, "Session not found")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ENTRY POINT
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 8080))
uvicorn.run(
app,
host="0.0.0.0",
port=port,
) |