"""HTTP API: POST /v1/coach turns one session of measurements (and optional timing) into the coaching response (v2.0). Run: uvicorn ai_coach.api:create_app --factory --host 0.0.0.0 --port 8000 (needs the `api` extra: pip install ".[api]") The service never raises for model, network or storage trouble (it returns a rule-based note and says so in `source`), so the only client errors are malformed input (422), a missing or wrong API key (401) and an oversized body (413). """ from __future__ import annotations import hmac import json import logging from contextlib import asynccontextmanager from typing import Any from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request from fastapi.responses import JSONResponse from .config import Settings, get_settings from .input_builder import InputError from .observability import configure_logging from .response import CoachResponse from .service import CoachService log = logging.getLogger(__name__) def create_app(settings: Settings | None = None, service: CoachService | None = None) -> FastAPI: settings = settings or get_settings() if settings.environment == "prod" and settings.api_key is None: raise RuntimeError("COACH_API_KEY must be set when COACH_ENV=prod") @asynccontextmanager async def lifespan(app: FastAPI): configure_logging(settings) app.state.service = service or CoachService(settings) yield app = FastAPI( title="AI Coach Agent", version="2", lifespan=lifespan, docs_url="/docs" if settings.environment != "prod" else None ) expected = settings.api_key.get_secret_value() if settings.api_key else None def require_key(x_api_key: str | None = Header(default=None)) -> None: if expected is not None and not (x_api_key and hmac.compare_digest(x_api_key.encode(), expected.encode())): raise HTTPException(status_code=401, detail="missing or invalid X-API-Key") @app.get("/healthz") def healthz() -> dict[str, str]: """Liveness: the process is up.""" return {"status": "ok"} @app.get("/readyz") def readyz(request: Request) -> dict[str, Any]: """Readiness: the service is built. `llm` says whether notes can come from the model or only from rules.""" svc: CoachService = request.app.state.service return {"status": "ready", "llm": svc.settings.llm_enabled, "model": svc.settings.model} @app.post("/v1/coach", response_model=CoachResponse, dependencies=[Depends(require_key)]) async def coach( request: Request, level: str | None = Query(default=None, description="hs_jv | hs_varsity | college, if not in the session"), ) -> CoachResponse: declared = request.headers.get("content-length") if declared and declared.isdigit() and int(declared) > settings.max_body_bytes: raise HTTPException(status_code=413, detail="session too large") body = await request.body() if len(body) > settings.max_body_bytes: raise HTTPException(status_code=413, detail="session too large") try: session = json.loads(body) except ValueError as exc: raise HTTPException(status_code=422, detail=f"body is not valid JSON: {exc}") from exc if not isinstance(session, dict): raise HTTPException(status_code=422, detail="body must be a JSON object") svc: CoachService = request.app.state.service try: return await svc.arespond(session, level=level) except InputError as exc: raise HTTPException(status_code=422, detail=str(exc)) from exc @app.get("/v1/usage", dependencies=[Depends(require_key)]) def usage(request: Request, days: int = Query(default=7, ge=1, le=90)) -> dict[str, Any]: """Requests, tokens, cache hit rate and cost for the last `days` days (same numbers as ai-coach-report).""" return request.app.state.service.ledger.summary(days) @app.exception_handler(Exception) async def unexpected(_: Request, exc: Exception) -> JSONResponse: log.exception("unhandled error") # the redaction filter strips secrets; the client gets no internals return JSONResponse(status_code=500, content={"detail": "internal error"}) return app