"""Live decision API, Jev / SystemOne compatible. POST /v1/systemone {"model"?, "state", "questions"} -> {"model", "answers", "usage"} (Jev's route) POST /v1/decisions same body and response (the name OpenRouter, Portkey and Perplexity use) GET /v1/models the served model, question types and limits GET /health liveness: the process and the engine thread are up GET /ready readiness: the model is loaded and warmed up (send traffic only after 200) GET /metrics Prometheus metrics Settings (environment): DECIDER_ADAPTER trained model folder (has decider_config.json) required DECIDER_API_KEYS comma-separated keys, or DECIDER_API_KEYS_FILE (one per line) DECIDER_ALLOW_NO_AUTH=1 run without keys (local testing only) DECIDER_RATE_RPM requests per minute per key (default 600) DECIDER_RATE_TPM input tokens per minute per key (default 4,000,000) DECIDER_MAX_WAIT_MS batching window (default 4) DECIDER_MAX_BATCH_TOKENS padded tokens per GPU batch (default 65536) DECIDER_MAX_QUEUE passes waiting before 503 (default 2048) DECIDER_REQUIRE_FAST_KERNELS=1 refuse to start without flash-linear-attention / causal-conv1d DECIDER_DEVICE, DECIDER_MODEL_NAME, DECIDER_TIMEOUT_S (default 30) Errors: {"error": {"type", "message"}} with 400 invalid request, 401 bad key, 413 over a Jev token limit, 429 rate limited (Retry-After), 503 overloaded or not ready, 504 timeout, 500 bug. Request contents are never logged; logs carry a key id (hash prefix), sizes and latency. """ import asyncio import hashlib import hmac import json import logging import os import threading import time import uuid from fastapi import FastAPI, Request from fastapi.concurrency import run_in_threadpool from fastapi.responses import JSONResponse, PlainTextResponse from prometheus_client import CONTENT_TYPE_LATEST, Counter, Gauge, Histogram, generate_latest import schema from engine import DecisionEngine, Overloaded, RequestTooLarge logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") log = logging.getLogger("decider.api") MODEL_NAME = os.environ.get("DECIDER_MODEL_NAME", "decider-2b") MAX_BODY_BYTES = 8 * 1024 * 1024 TIMEOUT_S = float(os.environ.get("DECIDER_TIMEOUT_S", "30")) RATE_RPM = float(os.environ.get("DECIDER_RATE_RPM", "600")) RATE_TPM = float(os.environ.get("DECIDER_RATE_TPM", "4000000")) REQUESTS = Counter("decider_requests_total", "API requests", ["route", "status"]) LATENCY = Histogram("decider_request_seconds", "Request latency", ["route"], buckets=(0.01, 0.025, 0.05, 0.1, 0.2, 0.35, 0.5, 1, 2, 5, 10, 30)) TOKENS = Counter("decider_input_tokens_total", "Input tokens decided") QUESTIONS = Counter("decider_questions_total", "Questions answered", ["type"]) BATCH_PASSES = Histogram("decider_batch_passes", "Passes per GPU batch", buckets=(1, 2, 4, 8, 16, 32, 64)) BATCH_SECONDS = Histogram("decider_batch_seconds", "GPU time per batch", buckets=(0.005, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56)) QUEUE = Gauge("decider_queue_passes", "Passes waiting for the GPU") READY = Gauge("decider_ready", "1 once the model is loaded and warmed up") def load_keys(): keys = [k.strip() for k in os.environ.get("DECIDER_API_KEYS", "").split(",") if k.strip()] path = os.environ.get("DECIDER_API_KEYS_FILE") if path: with open(path) as file: keys += [line.strip() for line in file if line.strip() and not line.startswith("#")] if not keys and os.environ.get("DECIDER_ALLOW_NO_AUTH") != "1": raise SystemExit("Set DECIDER_API_KEYS or DECIDER_API_KEYS_FILE (or DECIDER_ALLOW_NO_AUTH=1 for local tests).") return keys KEYS = load_keys() def key_id(key): return hashlib.sha256(key.encode()).hexdigest()[:10] if key else "anonymous" class RateLimiter: """Per-key token buckets for requests per minute and input tokens per minute (per replica).""" def __init__(self, rpm, tpm): self.limits = {"requests": rpm, "tokens": tpm} self.buckets = {} self.lock = threading.Lock() def _bucket(self, key, kind, now): capacity = self.limits[kind] level, last = self.buckets.get((key, kind), (capacity, now)) level = min(capacity, level + (now - last) * capacity / 60.0) return level, capacity def take(self, key, kind, amount): """Spend `amount`; returns seconds to wait if the bucket is short, else 0.""" now = time.monotonic() with self.lock: level, capacity = self._bucket(key, kind, now) if amount > level: self.buckets[(key, kind)] = (level, now) return (amount - level) * 60.0 / capacity self.buckets[(key, kind)] = (level - amount, now) return 0.0 app = FastAPI(title="Decider", version="3") limiter = RateLimiter(RATE_RPM, RATE_TPM) engine = None def error(status, kind, message, headers=None): return JSONResponse(status_code=status, content={"error": {"type": kind, "message": message}}, headers=headers) @app.on_event("startup") def start(): global engine adapter = os.environ.get("DECIDER_ADAPTER") if not adapter: raise SystemExit("Set DECIDER_ADAPTER to the trained model folder.") engine = DecisionEngine( adapter, os.environ.get("DECIDER_DEVICE", "cuda"), MODEL_NAME, max_batch_tokens=int(os.environ.get("DECIDER_MAX_BATCH_TOKENS", "65536")), max_wait_ms=float(os.environ.get("DECIDER_MAX_WAIT_MS", "4")), max_queue=int(os.environ.get("DECIDER_MAX_QUEUE", "2048")), require_fast_kernels=os.environ.get("DECIDER_REQUIRE_FAST_KERNELS") == "1") engine.observers.append(lambda passes, tokens, seconds: (BATCH_PASSES.observe(passes), BATCH_SECONDS.observe(seconds))) engine.warmup() READY.set(1) log.info("ready: model %s, config %s, kernels %s, keys %d", MODEL_NAME, engine.config, engine.kernels, len(KEYS)) def authorize(request): """The caller's key, '' when auth is off, or None when the key is wrong.""" if not KEYS: return "" header = request.headers.get("authorization", "") given = header[7:].strip() if header.lower().startswith("bearer ") else "" for key in KEYS: if given and hmac.compare_digest(given, key): return key return None async def decide(request: Request, route: str): started = time.monotonic() request_id = uuid.uuid4().hex[:12] def finish(response, status, **fields): REQUESTS.labels(route, str(status)).inc() LATENCY.labels(route).observe(time.monotonic() - started) log.info("request %s %s status %s %.0f ms %s", request_id, route, status, 1000 * (time.monotonic() - started), " ".join(f"{k}={v}" for k, v in fields.items())) response.headers["x-request-id"] = request_id return response key = authorize(request) if key is None: return finish(error(401, "authentication_error", "missing or invalid API key"), 401) who = key_id(key) if engine is None or not engine.ready: return finish(error(503, "unavailable", "the model is loading"), 503, key=who) wait = limiter.take(who, "requests", 1) if wait: return finish(error(429, "rate_limit_error", "too many requests", {"Retry-After": str(int(wait) + 1)}), 429, key=who) raw = await request.body() if len(raw) > MAX_BODY_BYTES: return finish(error(413, "request_too_large", f"body is over {MAX_BODY_BYTES} bytes"), 413, key=who) try: body = json.loads(raw) except ValueError: return finish(error(400, "invalid_request_error", "body is not valid JSON"), 400, key=who) try: pending, passes = await run_in_threadpool(engine.prepare, body) except schema.SchemaError as problem: return finish(error(400, "invalid_request_error", str(problem)), 400, key=who) except RequestTooLarge as problem: return finish(error(413, "request_too_large", str(problem)), 413, key=who) wait = limiter.take(who, "tokens", pending.input_tokens) if wait: return finish(error(429, "rate_limit_error", "input token rate exceeded", {"Retry-After": str(int(wait) + 1)}), 429, key=who, tokens=pending.input_tokens) try: if engine.queue.qsize() + len(passes) > engine.queue.maxsize: raise Overloaded("the decision queue is full") for p in passes: engine.queue.put_nowait(p) QUEUE.set(engine.queue.qsize()) response = await asyncio.wait_for(asyncio.wrap_future(pending.future), TIMEOUT_S) except Overloaded: return finish(error(503, "overloaded", "the server is at capacity; retry shortly", {"Retry-After": "1"}), 503, key=who) except asyncio.TimeoutError: pending.future.cancel() # its queued passes are skipped return finish(error(504, "timeout", f"no decision within {TIMEOUT_S:.0f} s"), 504, key=who) except Exception: log.exception("request %s failed", request_id) return finish(error(500, "internal_error", f"the decision failed (request {request_id})"), 500, key=who) TOKENS.inc(pending.input_tokens) for question in body["questions"].values(): QUESTIONS.labels(question["type"]).inc() return finish(JSONResponse(response), 200, key=who, questions=len(body["questions"]), tokens=pending.input_tokens, passes=len(passes)) @app.post("/v1/systemone") async def systemone(request: Request): return await decide(request, "systemone") @app.post("/v1/decisions") async def decisions(request: Request): return await decide(request, "decisions") @app.get("/v1/models") def models(): return {"object": "list", "data": [{ "id": MODEL_NAME, "object": "model", "format": "systemone", "question_types": list(schema.QUESTION_TYPES), "limits": {"request_tokens": schema.MAX_REQUEST_TOKENS, "state_plus_question_tokens": schema.MAX_STATE_PLUS_QUESTION_TOKENS, "questions": schema.MAX_QUESTIONS, "options": schema.MAX_OPTIONS}, "rate_limits": {"requests_per_minute": RATE_RPM, "input_tokens_per_minute": RATE_TPM}}]} @app.get("/health") def health(): alive = engine is not None and engine._worker.is_alive() return JSONResponse({"status": "ok" if alive else "starting"}, status_code=200 if alive or engine is None else 500) @app.get("/ready") def ready(): if engine is None or not engine.ready: return JSONResponse({"status": "loading"}, status_code=503) return {"status": "ready", "model": MODEL_NAME, "kernels": engine.kernels} @app.get("/metrics") def metrics(): if engine is not None: QUEUE.set(engine.queue.qsize()) return PlainTextResponse(generate_latest(), media_type=CONTENT_TYPE_LATEST)