""" FastAPI service - the pipeline behind the Vercel site. Auth ---- * Service calls (Next.js server routes): `Authorization: Bearer `. * User calls (browser): `Authorization: Bearer cp1.<...>` user token minted by the Next.js server from its Auth.js session (controlplane/api/tokens.py). Every thread / message / cache operation is scoped by the user id INSIDE the token. Streaming: POST /api/query and /api/resume return Server-Sent Events (`event: \\ndata: \\n\\n`) produced by controlplane.api.chat.run_chat. Run: python start.py (CP_SERVE=api, the default) or uvicorn controlplane.api.server:app --port 7860 """ from __future__ import annotations import json import os from typing import Any, Dict, Iterator, Optional from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse from pydantic import BaseModel, Field from controlplane.api import otp from controlplane.api.chat import run_chat from controlplane.api.tokens import verify_user_token from controlplane.app import store, warm from controlplane.cache import get_cache from controlplane.config import KB_DESCRIPTIONS, KB_IDS, KB_LABELS, settings from controlplane.prompts import DEMO_PROMPTS def _secret() -> str: s = os.getenv("BACKEND_SECRET", "").strip() if not s: raise HTTPException(503, "BACKEND_SECRET is not configured on the server") return s def _bearer(request: Request) -> str: h = request.headers.get("authorization", "") return h[7:].strip() if h.lower().startswith("bearer ") else "" def service_auth(request: Request) -> None: import hmac if not hmac.compare_digest(_bearer(request), _secret()): raise HTTPException(401, "unauthorized") def user_auth(request: Request) -> Dict[str, Any]: payload = verify_user_token(_bearer(request), _secret()) if not payload: raise HTTPException(401, "unauthorized") return payload def _hourly_limit() -> int: try: return int(os.getenv("CP_USER_HOURLY_LIMIT", "40")) except ValueError: return 40 # ------------------------------------------------------------------ models ---- class UpsertIn(BaseModel): email: str name: str = "" provider: str = "google" class EmailIn(BaseModel): email: str class VerifyIn(BaseModel): email: str code: str class QueryIn(BaseModel): query: str = Field(min_length=1, max_length=2000) thread_id: Optional[str] = None forced_kb: Optional[str] = None class ResumeIn(BaseModel): thread_id: str graph_thread: str reply: str = Field(min_length=1, max_length=2000) # ------------------------------------------------------------------ app ---- def _sse(events: Iterator[tuple[str, dict]]) -> Iterator[bytes]: for name, data in events: yield f"event: {name}\ndata: {json.dumps(data, default=str, ensure_ascii=False)}\n\n".encode("utf-8") def _stream(gen_factory): """Start the generator eagerly so pre-stream errors become HTTP status codes.""" try: gen = gen_factory() first = next(gen) except PermissionError: raise HTTPException(404, "thread not found") except LookupError as e: if "hitl_expired" in str(e): raise HTTPException(410, "hitl_expired") raise except RuntimeError as e: if "rate_limited" in str(e): raise HTTPException(429, f"You've reached the limit of {_hourly_limit()} questions per hour " "for this demo. Please try again a little later.") raise except StopIteration: gen, first = iter(()), None def _chain(): if first is not None: yield first yield from gen return StreamingResponse( _sse(_chain()), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no", "Connection": "keep-alive"}, ) def create_app() -> FastAPI: app = FastAPI(title="ControlPlane.ai API", docs_url=None, redoc_url=None) origins = [o.strip() for o in os.getenv("ALLOWED_ORIGINS", "").split(",") if o.strip()] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["Authorization", "Content-Type"], max_age=600, ) hourly = _hourly_limit() @app.get("/api/health") def health(): return {"ok": True, "warm": warm.status(), "llm": settings.has_any_llm(), "db": store.backend_name()} @app.get("/api/meta") def meta(user=Depends(user_auth)): return { "kbs": [{"id": k, "label": KB_LABELS.get(k, k), "description": KB_DESCRIPTIONS.get(k, "")} for k in KB_IDS], "demo_prompts": DEMO_PROMPTS, "hourly_limit": hourly, "user": {"id": user["uid"], "email": user["email"], "name": user["name"]}, } # ---- service-to-service (Next.js server routes) ---- @app.post("/api/auth/upsert", dependencies=[Depends(service_auth)]) def auth_upsert(body: UpsertIn): if not otp.valid_email(body.email): raise HTTPException(422, "invalid e-mail") return store.upsert_user(body.email, body.name, body.provider) @app.post("/api/auth/otp/send", dependencies=[Depends(service_auth)]) def otp_send(body: EmailIn): ok, message = otp.request_code(body.email) return {"ok": ok, "message": message} @app.post("/api/auth/otp/verify", dependencies=[Depends(service_auth)]) def otp_verify(body: VerifyIn): user, message = otp.check_code(body.email, body.code) return {"ok": user is not None, "message": message, "user": user} # ---- per-user data ---- @app.get("/api/threads") def threads(user=Depends(user_auth)): return {"threads": store.list_threads(user["uid"])} @app.get("/api/threads/{thread_id}") def thread(thread_id: str, user=Depends(user_auth)): if not store.owns_thread(user["uid"], thread_id): raise HTTPException(404, "thread not found") history, state = store.load_thread(user["uid"], thread_id) return {"id": thread_id, "history": history, "state": state} @app.delete("/api/threads/{thread_id}") def delete_thread(thread_id: str, user=Depends(user_auth)): store.delete_thread(user["uid"], thread_id) return {"ok": True} @app.get("/api/cache") def cache_size(user=Depends(user_auth)): return {"size": len(get_cache(user["uid"]))} @app.delete("/api/cache") def cache_clear(user=Depends(user_auth)): get_cache(user["uid"]).clear() return {"ok": True} # ---- the pipeline ---- @app.post("/api/query") def query(body: QueryIn, user=Depends(user_auth)): forced = body.forced_kb if body.forced_kb in KB_IDS else None return _stream(lambda: run_chat(user["uid"], query=body.query.strip(), thread_id=body.thread_id, forced_kb=forced, hourly_limit=hourly)) @app.post("/api/resume") def resume(body: ResumeIn, user=Depends(user_auth)): return _stream(lambda: run_chat(user["uid"], query=None, thread_id=body.thread_id, forced_kb=None, resume=body.reply.strip(), graph_thread=body.graph_thread, hourly_limit=hourly)) return app app = create_app()