"""FastAPI factory: the /v1 routes, the legacy routes of the original Space, errors, limits, queue and cache.""" from __future__ import annotations import base64 import binascii import hashlib import json import logging import os import threading import time from collections import OrderedDict from contextlib import asynccontextmanager from pathlib import Path import pydantic from fastapi import FastAPI, HTTPException, Request from fastapi.exception_handlers import request_validation_exception_handler from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse, PlainTextResponse from starlette.concurrency import run_in_threadpool from .auth import Gate, bearer from .registry import Model, Registry from .schemas import ApiError, PredictionRequest, PredictResponse from .usage import Usage, keyed log = logging.getLogger("squadds_ml_api") SERVICE = "SQuADDS ML API" MB = 2**20 MIN_THICKNESS_UM = 1.0 REFUSAL = {400: "invalid_input", 422: "invalid_input", 401: "auth", 403: "auth", 404: "unknown_model", 413: "size", 429: "rate_limited", 503: "unavailable"} class Runner: """One prediction at a time; at most `depth` requests in flight (running + waiting), the next one gets 429.""" def __init__(self, depth: int): self.lock = threading.Lock() self.slots = threading.BoundedSemaphore(depth) class Cache: def __init__(self, size: int = 64): self.size, self.data, self.lock = size, OrderedDict(), threading.Lock() def get(self, k): with self.lock: if k in self.data: self.data.move_to_end(k) return self.data[k] return None def put(self, k, v): with self.lock: self.data[k] = v while len(self.data) > self.size: self.data.popitem(last=False) class RateLimiter: """Token bucket per client IP: `per_minute` requests, refilled continuously (0 disables it).""" def __init__(self, per_minute: int): self.rate, self.buckets, self.lock = per_minute, {}, threading.Lock() def allow(self, ip: str) -> bool: if self.rate <= 0: return True now = time.monotonic() with self.lock: tokens, last = self.buckets.get(ip, (float(self.rate), now)) tokens = min(float(self.rate), tokens + (now - last) * self.rate / 60.0) ok = tokens >= 1.0 self.buckets[ip] = (tokens - 1.0 if ok else tokens, now) if len(self.buckets) > 10000: self.buckets.clear() return ok def client_ip(request: Request) -> str: fwd = request.headers.get("x-forwarded-for") return fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "?") PREDICT_OPENAPI = { "requestBody": { "required": True, "content": { "application/json": { "schema": { "type": "object", "properties": { "inputs": {"description": "The model's inputs (see GET /v1/models/{model_id}/schema); file " "models take the file as inputs.file_base64"}, "options": {"type": "object"}, }, "required": ["inputs"], } }, "multipart/form-data": { "schema": { "type": "object", "properties": { "file": {"type": "string", "format": "binary"}, "inputs": {"type": "string", "description": "JSON of the other input fields"}, "options": {"type": "string", "description": "JSON of the options"}, }, "required": ["file"], } }, }, } } def create_app(root: Path, registry_file: Path | None = None, load: bool = True) -> FastAPI: root = Path(root) reg = Registry(root, registry_file or os.environ.get("SQUADDS_ML_API_REGISTRY")) gate = Gate(os.environ.get("SQUADDS_ML_API_ORG", "SQuADDS")) depth = int(os.environ.get("SQUADDS_ML_API_QUEUE", "8")) runner = Runner(depth) cache = Cache(int(os.environ.get("SQUADDS_ML_API_CACHE", "64"))) limiter = RateLimiter(int(os.environ.get("SQUADDS_ML_API_RATE_PER_MIN", "60"))) built = root / "IMAGE_BUILT_AT" build_info = { "squadds_commit": reg.lock_info.get("squadds", {}).get("commit"), "squadds_dirty": reg.lock_info.get("squadds", {}).get("dirty"), "registry_sha256": reg.sha256, "image_built_at": built.read_text().strip() if built.exists() else None, } @asynccontextmanager async def lifespan(_app): if load: reg.start(exit_on_failure=os.environ.get("SQUADDS_ML_API_EXIT_ON_LOAD_FAILURE") == "1") yield app = FastAPI( title=SERVICE, version="2.0.0", description="HTTP API for the machine-learning models of SQuADDS. Every model is an entry of the registry; " "`/v1` is the API, and the original routes `/health`, `/models` and `/predict` are kept unchanged.\n\n" "If you use SQuADDS or QCap in your work, please cite [Shanto et al., Quantum 8, 1465 (2024)]" "(https://doi.org/10.22331/q-2024-09-09-1465) and [Shanto, Das and Levenson-Falk, arXiv:2611.22057 (2026)]" "(https://arxiv.org/abs/2611.22057).", lifespan=lifespan, ) app.state.registry, app.state.cache, app.state.runner = reg, cache, runner app.state.usage = Usage("api") @app.middleware("http") async def _count(request: Request, call_next): """Aggregate daily counts of the predict routes (squadds_ml_api.usage); responses are passed through untouched.""" path = request.url.path route = "legacy" if path == "/predict" else "v1" if path.startswith("/v1/models/") and path.endswith("/predict") else None if route is None or request.method != "POST": return await call_next(request) t0, u = time.perf_counter(), app.state.usage try: response = await call_next(request) except Exception: u.inc("errors") raise mid = path.split("/")[3] if route == "v1" else getattr(request.state, "usage_model", None) u.seen("distinct_users", keyed("ip", client_ip(request))) u.inc("calls_by_route", route) u.inc("calls_by_model", mid if mid in reg.models else "other") code = response.status_code if code < 400: u.latency(time.perf_counter() - t0) if getattr(request.state, "usage_cached", False): u.inc("cache_hits") elif code in REFUSAL: u.inc("refusals", REFUSAL[code]) else: u.inc("errors") return response @app.exception_handler(ApiError) async def _api_error(_request: Request, exc: ApiError): return JSONResponse(exc.body(), status_code=exc.status, headers=exc.headers) @app.exception_handler(RequestValidationError) async def _validation(request: Request, exc: RequestValidationError): if request.url.path.startswith("/v1"): err = ApiError(422, "validation_error", "the request does not match the schema", request.path_params.get("model_id"), details=jsonable(exc.errors())) return JSONResponse(err.body(), status_code=422) return await request_validation_exception_handler(request, exc) def member(request: Request) -> bool | None: tok = bearer(request.headers) if tok is None: return None try: return gate.is_member(tok) except Exception as exc: # noqa: BLE001 raise ApiError(503, "loading", f"could not verify the token with Hugging Face: {exc}", headers={"Retry-After": "30"}) from exc def visible(m: Model, who: bool | None) -> bool: return m.status == "ready" and (m.visibility == "public" or (m.visibility == "gated" and who is True)) def access(model_id: str, request: Request, need_ready: bool = True) -> Model: m = reg.models.get(model_id) if m is None or m.visibility == "hidden" or m.status != "ready": raise ApiError(404, "unknown_model", f"unknown model '{model_id}'", model_id) if m.visibility == "gated": who = member(request) if who is None: raise ApiError(401, "auth_required", "this model needs 'Authorization: Bearer ' " "of a member of the SQuADDS organization", model_id) if not who: raise ApiError(403, "forbidden", "this token does not belong to a member of the SQuADDS organization", model_id) if need_ready and m.state != "ready": if m.state == "failed": raise ApiError(500, "inference_error", f"model failed to load: {m.error}", model_id) raise ApiError(503, "loading", "the model is still loading", model_id, headers={"Retry-After": "10"}) return m def entry(m: Model) -> dict: s = m.spec return { "id": m.id, "family": s.get("family"), "display_name": s["display_name"], "description": s["description"], "tags": s.get("tags", []), "input_kind": getattr(m.adapter_cls, "input_kind", None), "visibility": m.visibility, "revision": m.revision, "status": m.state, } def rate(request: Request) -> None: if not limiter.allow(client_ip(request)): raise ApiError(429, "rate_limited", f"more than {limiter.rate} requests per minute from this address", headers={"Retry-After": "60"}) def run_predict(m: Model, inputs, options, data: bytes | None) -> dict: t0 = time.perf_counter() key = hashlib.sha256(json.dumps([m.id, m.revision, inputs, options], sort_keys=True, default=str).encode() + (data or b"")).hexdigest() def hit(v): return {**v, "timing_s": {"total": round(time.perf_counter() - t0, 6), "queue": 0.0}, "cached": True} v = cache.get(key) if v is not None: return hit(v) if not runner.slots.acquire(blocking=False): raise ApiError(429, "busy", "the server is busy; retry later", m.id, headers={"Retry-After": "30"}) try: tq = time.perf_counter() with runner.lock: queue_s = time.perf_counter() - tq v = cache.get(key) if v is not None: return hit(v) try: out = m.adapter.predict(inputs, file=data, options=options) except pydantic.ValidationError as exc: raise ApiError(422, "validation_error", "the inputs do not match the schema", m.id, details=jsonable(exc.errors())) from exc except ValueError as exc: if getattr(exc, "too_large", False): raise ApiError(413, "too_large", str(exc), m.id) from exc raise ApiError(400, "invalid_input", str(exc), m.id) from exc except Exception as exc: # noqa: BLE001 log.exception("inference error in %s", m.id) raise ApiError(500, "inference_error", f"{type(exc).__name__}: {exc}", m.id) from exc finally: runner.slots.release() v = { "model_id": m.id, "family": m.spec["family"], "revision": m.revision, "outputs": out["outputs"], "metadata": out.get("metadata", {}), } cache.put(key, v) timing = {"total": round(time.perf_counter() - t0, 6), "queue": round(queue_s, 6)} timing.update({k: round(x, 6) if isinstance(x, float) else x for k, x in (out.get("timing_s") or {}).items()}) return {**v, "timing_s": timing, "cached": False} def request_schema(m: Model) -> dict: ad = m.adapter ins = ad.InputModel.model_json_schema() if getattr(ad, "batch", False): items = {"type": "array", "items": ins, "maxItems": m.limits.get("max_batch_rows", 1000)} ins = {"anyOf": [ins, items]} opts = ad.OptionsModel.model_json_schema() if getattr(ad, "OptionsModel", None) else {"type": "object"} return {"type": "object", "properties": {"inputs": ins, "options": opts}, "required": ["inputs"]} # ---------- root and /v1 ---------- @app.get("/") def root_route() -> dict: return { "service": SERVICE, "docs": "/docs", "openapi": "/openapi.json", "llms_txt": "/llms.txt", "v1": {"health": "/v1/health", "models": "/v1/models", "model": "/v1/models/{model_id}", "schema": "/v1/models/{model_id}/schema", "predict": "/v1/models/{model_id}/predict"}, "models_endpoint": "/models", "predict_endpoint": "/predict", } @app.get("/llms.txt", response_class=PlainTextResponse, include_in_schema=False) def llms_txt() -> str: lines = [f"# {SERVICE}", "", "> HTTP API for the machine-learning models of SQuADDS (Superconducting Qubit And Device Design and " "Simulation). Every model is listed by GET /v1/models, which is the source of truth.", "", "## Use it", "", "- GET /v1/models: the available models, with their inputs and outputs", "- GET /v1/models/{model_id}: one model, with units, limits and an example request", "- GET /v1/models/{model_id}/schema?format=tool: a ready tool definition for an AI agent", "- POST /v1/models/{model_id}/predict: JSON body {\"inputs\": {...}, \"options\": {...}}, " "or a multipart upload for models that take a file", "- GET /openapi.json and /docs: the full OpenAPI description", "", "## Models", ""] lines += [f"- {m.id}: {m.spec['display_name']}. {m.spec['description']}" for m in reg.models.values() if visible(m, None)] lines += ["", "## More", "", "- SQuADDS documentation: https://lfl-lab.github.io/SQuADDS/", "- Code: https://github.com/LFL-Lab/SQuADDS", "- Python client: squadds.ml.client in the SQuADDS package", ""] qcap = any("qcap" in m.id for m in reg.models.values() if visible(m, None)) lines += ["## Cite", "", f"If you use SQuADDS{' or QCap' if qcap else ''} in your work, please cite:", "", "- S. Shanto et al., SQuADDS: A validated design database and simulation workflow for superconducting " "qubit design, Quantum 8, 1465 (2024), https://doi.org/10.22331/q-2024-09-09-1465"] if qcap: lines.append("- S. A. Shanto, S. Das and E. Levenson-Falk, QCap: a physics-corrected graph neural network for the " "capacitance matrix of any planar superconducting device layout, arXiv:2611.22057 (2026), " "https://arxiv.org/abs/2611.22057") lines.append("") return "\n".join(lines) @app.get("/v1/health", tags=["v1"]) def health_v1(request: Request) -> dict: who = member(request) return {"status": "ok", "models": {m.id: m.state for m in reg.models.values() if visible(m, who)}, "build": build_info} @app.get("/v1/models", tags=["v1"]) def models_v1(request: Request) -> dict: who = member(request) return {"models": [entry(m) for m in reg.models.values() if visible(m, who)]} @app.get("/v1/models/{model_id}", tags=["v1"]) def model_v1(model_id: str, request: Request) -> dict: m = access(model_id, request) out = {**entry(m), **m.adapter.describe(), "limits": {**m.limits, "queue_depth": depth}} if m.spec.get("numbers"): out["numbers"] = m.spec["numbers"] if m.spec.get("example"): ex = json.loads((root / m.spec["example"]).read_text()) out["example"] = {k: ex[k] for k in ("file", "request") if k in ex} return out @app.get("/v1/models/{model_id}/schema", tags=["v1"]) def schema_v1(model_id: str, request: Request, format: str = "json") -> dict: m = access(model_id, request) req = request_schema(m) if format == "tool": how = (" Send a GDS file as inputs.file_base64." if m.adapter.input_kind == "file" else "") return {"name": f"squadds_{m.id}", "description": f"{m.spec['display_name']}: {m.spec['description']} POST the input to " f"/v1/models/{m.id}/predict.{how}", "input_schema": req} if format != "json": raise ApiError(400, "invalid_input", "format must be 'json' or 'tool'", model_id) return {"request": req, "response": PredictResponse.model_json_schema()} @app.post("/v1/models/{model_id}/predict", tags=["v1"], response_model=PredictResponse, openapi_extra=PREDICT_OPENAPI) async def predict_v1(model_id: str, request: Request): rate(request) m = access(model_id, request) file_model = m.adapter.input_kind == "file" max_bytes = int(float(m.limits.get("max_upload_mb", 20)) * MB) length = request.headers.get("content-length") if length and length.isdigit() and int(length) > max_bytes * 1.4 + MB: raise ApiError(413, "too_large", f"request larger than {max_bytes // MB} MB", model_id) data = None if request.headers.get("content-type", "").startswith("multipart/form-data"): if not file_model: raise ApiError(400, "invalid_input", "this model takes a JSON body", model_id) form = await request.form() up = form.get("file") if up is None or isinstance(up, str): raise ApiError(400, "invalid_input", "multipart requests need the file in the field 'file'", model_id) data = await up.read(max_bytes + 1) try: inputs = json.loads(form.get("inputs") or "{}") options = json.loads(form.get("options") or "{}") except json.JSONDecodeError as exc: raise ApiError(400, "invalid_input", f"the fields 'inputs' and 'options' must be JSON: {exc}", model_id) from exc else: try: body = await request.json() except (json.JSONDecodeError, UnicodeDecodeError) as exc: raise ApiError(400, "invalid_input", "the body must be JSON (or multipart for file models)", model_id) from exc if not isinstance(body, dict) or "inputs" not in body: raise ApiError(422, "validation_error", "the body must be an object with 'inputs'", model_id) inputs, options = body["inputs"], body.get("options") or {} if file_model and isinstance(inputs, dict) and inputs.get("file_base64") is not None: inputs = dict(inputs) try: data = base64.b64decode(inputs.pop("file_base64"), validate=True) except (binascii.Error, ValueError, TypeError) as exc: raise ApiError(400, "invalid_input", "inputs.file_base64 is not valid base64", model_id) from exc if not isinstance(options, dict): raise ApiError(422, "validation_error", "options must be an object", model_id) check_thickness(m, inputs) if data is not None and len(data) > max_bytes: raise ApiError(413, "too_large", f"file larger than {max_bytes // MB} MB", model_id) out = await run_in_threadpool(run_predict, m, inputs, options, data) request.state.usage_cached = out["cached"] return out # ---------- legacy routes of the original Space (same shapes, {"detail": ...} errors) ---------- def legacy_models() -> list[Model]: return [m for m in reg.models.values() if m.spec.get("legacy_predict")] def legacy_ready() -> list[str]: return [m.id for m in legacy_models() if m.status == "ready" and m.visibility == "public"] @app.get("/health", tags=["legacy"]) def health() -> dict: return {"status": "ok", "available_models": legacy_ready(), "bundle_root": str(root)} @app.get("/models", tags=["legacy"]) def list_models() -> dict: out = [] for m in legacy_models(): d = m.adapter.describe() if m.adapter is not None else {} out.append({ "id": m.id, "display_name": m.spec["display_name"], "description": m.spec["description"], "status": m.status, "status_detail": m.spec.get("status_detail", ""), "input_units": d.get("input_units", {}), "output_units": d.get("output_units", {}), "tags": m.spec.get("tags", []), }) return {"models": out} @app.post("/predict", tags=["legacy"]) def predict(body: PredictionRequest, request: Request) -> dict: request.state.usage_model = body.model_id if not limiter.allow(client_ip(request)): raise HTTPException(429, f"more than {limiter.rate} requests per minute from this address", headers={"Retry-After": "60"}) m = reg.models.get(body.model_id) if m is None or not m.spec.get("legacy_predict") or (m.visibility != "public" and m.status == "ready"): raise HTTPException(400, f"Unknown model_id '{body.model_id}'. Available models: {legacy_ready()}.") if m.status != "ready": raise HTTPException( 400, f"Model '{m.id}' is not deployable in this bundle: {m.spec.get('status_detail') or m.status}.") if m.state != "ready": raise HTTPException(503 if m.state != "failed" else 500, f"Model '{m.id}' is {m.state}.") try: v = run_predict(m, body.inputs, body.options.model_dump(), None) request.state.usage_cached = v["cached"] except ApiError as exc: if exc.status in (400, 413, 422): raise HTTPException(400, exc.message) from exc if exc.status == 429: raise HTTPException(429, exc.message, headers=exc.headers) from exc raise HTTPException(500, f"Unexpected inference error for model '{m.id}': {exc.message}") from exc out = {"model_id": m.id, "display_name": m.spec["display_name"], "predictions": v["outputs"]["predictions"], "metadata": v["metadata"]} if "scaled_predictions" in v["outputs"]: out["scaled_predictions"] = v["outputs"]["scaled_predictions"] return out return app def check_thickness(m: Model, inputs) -> None: """Capacitance models: substrates thinner than MIN_THICKNESS_UM are refused before any solve.""" if m.spec.get("family") != "planar_capacitance" or not isinstance(inputs, dict) or inputs.get("thickness_um") is None: return try: t = float(inputs["thickness_um"]) except (TypeError, ValueError): return if not t >= MIN_THICKNESS_UM: raise ApiError(400, "invalid_input", f"thickness_um must be at least {MIN_THICKNESS_UM:g} (got {inputs['thickness_um']!r}); " "the models are tested on substrates of 10-1000 um", m.id) def jsonable(x): return json.loads(json.dumps(x, default=str))