Spaces:
Running on Zero
Running on Zero
File size: 7,518 Bytes
5e0b6f8 | 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 | """
FastAPI service - the pipeline behind the Vercel site.
Auth
----
* Service calls (Next.js server routes): `Authorization: Bearer <BACKEND_SECRET>`.
* 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: <name>\\ndata: <json>\\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()
|