Spaces:
Sleeping
Sleeping
Download src/coveragecheck/web/api.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/web/api.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/web/api.py
-
curl -L -o api.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/web/api.py
11.9 kB
| """Step 9: the web app's HTTP layer (FastAPI). It serves the React app (web/dist) and: | |
| GET /api/info systems, model, today, questions left today, the not-advice notice | |
| POST /api/ask {question, system, day?, history?} -> a server-sent event stream of | |
| engine.events() (one JSON object per "data:" line) | |
| uv run python -m coveragecheck.web.api # http://127.0.0.1:8000 (HOST/PORT env) | |
| One process, one port: on the Hugging Face Docker Space (Step 10) the same uvicorn | |
| serves the built frontend and the API. Guards for a public demo on a 2-core box and a | |
| small API budget (config WEB_*): at most WEB_MAX_RUNNING questions at once (more get | |
| HTTP 429 "busy", not a queue), WEB_DAILY_QUESTIONS per UTC day, per visitor | |
| WEB_CLIENT_RUNNING at once and WEB_CLIENT_DAILY per day, a WEB_DEADLINE_S deadline | |
| per question (C stops between graph nodes when its visitor leaves), and a keep-alive | |
| comment every WEB_PING_S while a step runs. | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| import os | |
| import queue | |
| import threading | |
| import time | |
| from collections.abc import AsyncIterator, Callable, Iterator | |
| from contextlib import asynccontextmanager | |
| from datetime import UTC, date, datetime | |
| from pathlib import Path | |
| from typing import Literal | |
| from fastapi import FastAPI, HTTPException, Request | |
| from fastapi.responses import StreamingResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel, ConfigDict, Field, field_validator | |
| from starlette.exceptions import HTTPException as StarletteHTTPException | |
| from coveragecheck import config | |
| from coveragecheck.web.engine import NOT_ADVICE, Engine | |
| from coveragecheck.web.followup import HistoryTurn | |
| log = logging.getLogger(__name__) | |
| DONE = object() # end of a question's events, put on its queue by the worker thread | |
| BUSY = "The demo is answering other questions right now. Please try again in a minute." | |
| SPENT = "Today's question limit for this demo is reached. Please come back tomorrow." | |
| LATE = "This question took too long and was stopped. Please try again." | |
| CLIENT_SPENT = "You have asked today's maximum number of questions. Please come back tomorrow." | |
| SERVER = "Something went wrong." | |
| class AskRequest(BaseModel): | |
| """A visitor's question. day: the policy date (versions in force on it); default | |
| today, as the held-out run used for questions without a date. history: the earlier | |
| turns of the conversation (a follow-up is rewritten from the last few of them).""" | |
| model_config = ConfigDict(extra="forbid") | |
| question: str = Field(min_length=3, max_length=config.WEB_MAX_QUESTION_CHARS) | |
| system: Literal[config.WEB_SYSTEMS] # type: ignore[valid-type] | |
| day: date | None = None | |
| history: list[HistoryTurn] = Field( | |
| default_factory=list, max_length=config.WEB_HISTORY_MAX_TURNS | |
| ) | |
| def stripped(cls, value: str) -> str: | |
| value = value.strip() | |
| if len(value) < 3: | |
| raise ValueError("the question is empty") | |
| return value | |
| def plausible(cls, value: date | None) -> date | None: | |
| if value is not None and not date(1990, 1, 1) <= value <= date(2100, 12, 31): | |
| raise ValueError("the policy date must be between 1990 and 2100") | |
| return value | |
| class Gate: | |
| """Admission for live questions: at most `running` at once and `daily` per UTC day | |
| in all (the API budget), and per visitor at most `client_running` at once and | |
| `client_daily` per day (9a audit: one visitor could hold every slot or spend the | |
| whole day's budget). admit(client) returns None (admitted: call release(client) | |
| when done) or why not; a refusal never counts against any budget.""" | |
| def __init__( | |
| self, | |
| running: int, | |
| daily: int, | |
| today: Callable[[], date], | |
| client_running: int = 1, | |
| client_daily: int | None = None, | |
| ): | |
| self.running, self.daily, self.today = running, daily, today | |
| self.client_running = client_running | |
| self.client_daily = daily if client_daily is None else client_daily | |
| self.day, self.count, self.lock = None, 0, threading.Lock() | |
| self.busy: dict[str, int] = {} # client -> questions running | |
| self.used: dict[str, int] = {} # client -> questions today | |
| def roll(self) -> None: | |
| """A new UTC day resets the day's counts (call with the lock held).""" | |
| if self.day != self.today(): | |
| self.day, self.count, self.used = self.today(), 0, {} | |
| def left(self) -> int: | |
| with self.lock: | |
| self.roll() | |
| return self.daily - self.count | |
| def admit(self, client: str = "") -> str | None: | |
| with self.lock: | |
| self.roll() | |
| if self.count >= self.daily: | |
| return SPENT | |
| if self.used.get(client, 0) >= self.client_daily: | |
| return CLIENT_SPENT | |
| running = sum(self.busy.values()) | |
| if running >= self.running or self.busy.get(client, 0) >= self.client_running: | |
| return BUSY | |
| self.count += 1 | |
| self.used[client] = self.used.get(client, 0) + 1 | |
| self.busy[client] = self.busy.get(client, 0) + 1 | |
| return None | |
| def release(self, client: str = "") -> None: | |
| with self.lock: | |
| self.busy[client] -= 1 | |
| if not self.busy[client]: | |
| del self.busy[client] | |
| def utc_today() -> date: | |
| return datetime.now(UTC).date() | |
| def client_of(request: Request) -> str: | |
| """Who is asking, for the per-visitor limits: the LAST X-Forwarded-For hop (the one | |
| the hosting proxy adds; earlier hops are whatever the visitor sent, so trusting | |
| the first would let anyone pick a fresh identity per request), else the socket's | |
| address. Step 10: check what the Hugging Face proxy sends.""" | |
| forwarded = request.headers.get("x-forwarded-for", "") | |
| hops = [h.strip() for h in forwarded.split(",") if h.strip()] | |
| if hops: | |
| return hops[-1] | |
| return request.client.host if request.client else "" | |
| def sse(event: dict) -> str: | |
| """One server-sent event: a "data:" line of JSON and a blank line.""" | |
| return f"data: {json.dumps(event, ensure_ascii=False)}\n\n" | |
| def start(events: Iterator[dict], release: Callable[[], None], cancel: threading.Event): | |
| """Run engine.events() in a worker thread (the systems are blocking code), now; each | |
| event arrives on the returned queue already as server-sent-event text (an event | |
| that won't serialise becomes an error event, 9a audit), then DONE. Started by the | |
| request handler, not by the response stream, so the slot is released even if the | |
| visitor leaves before the stream starts (an async generator that never starts runs | |
| no `finally`). When `cancel` is set (the visitor left, or the deadline passed), the | |
| worker stops at the next event: System C then stops between graph nodes, so an | |
| abandoned question pays for no further LLM call (A and B are one call each and | |
| finish it). The slot is freed only when the worker ends.""" | |
| inbox: queue.Queue = queue.Queue() | |
| def work() -> None: | |
| try: | |
| for event in events: | |
| if cancel.is_set(): | |
| break | |
| inbox.put(sse(event)) # an unserialisable event raises: handled below | |
| except Exception: # engine.events never raises; sse() can (9a audit) | |
| log.exception("event stream failed") | |
| inbox.put(sse({"type": "error", "kind": "server", "message": SERVER})) | |
| finally: | |
| close = getattr(events, "close", None) | |
| if close: | |
| close() # a generator stopped early: run its cleanup (closes C's graph) | |
| inbox.put(DONE) | |
| release() | |
| threading.Thread(target=work, daemon=True).start() | |
| return inbox | |
| async def relay( | |
| inbox: queue.Queue, cancel: threading.Event, ping_s: float, deadline_s: float | |
| ) -> AsyncIterator[str]: | |
| """A worker's events, as they come. While a step runs, a comment line goes out every | |
| ping_s so proxies keep the connection open; past deadline_s an error event ends the | |
| stream. However the stream ends (done, deadline, the visitor gone), the worker is | |
| told to stop.""" | |
| ends = time.monotonic() + deadline_s | |
| try: | |
| while True: | |
| left = ends - time.monotonic() | |
| if left <= 0: | |
| yield sse({"type": "error", "kind": "deadline", "message": LATE}) | |
| return | |
| try: | |
| text = await asyncio.to_thread(inbox.get, True, min(ping_s, left)) | |
| except queue.Empty: | |
| yield ": ping\n\n" | |
| continue | |
| if text is DONE: | |
| return | |
| yield text | |
| finally: | |
| cancel.set() | |
| class SpaFiles(StaticFiles): | |
| """The built React app; an unknown path that is not an API call gets index.html, so | |
| the app's own routes (e.g. /architecture) survive a page reload.""" | |
| async def get_response(self, path: str, scope): | |
| try: | |
| return await super().get_response(path, scope) | |
| except StarletteHTTPException as missing: # FastAPI's HTTPException is a SUBclass | |
| if missing.status_code != 404 or path.startswith("api"): | |
| raise | |
| return await super().get_response("index.html", scope) | |
| def create_app( | |
| load_engine: Callable[[], Engine], | |
| dist: Path | None, | |
| gate: Gate | None = None, | |
| ping_s: float = config.WEB_PING_S, | |
| deadline_s: float = config.WEB_DEADLINE_S, | |
| ) -> FastAPI: | |
| """The app. load_engine runs once at startup (in a thread: ~15 s of model loading); | |
| dist: the built frontend to serve at "/", or None (API only, e.g. under `npm run | |
| dev`, which proxies /api here).""" | |
| gate = gate or Gate( | |
| config.WEB_MAX_RUNNING, | |
| config.WEB_DAILY_QUESTIONS, | |
| utc_today, | |
| config.WEB_CLIENT_RUNNING, | |
| config.WEB_CLIENT_DAILY, | |
| ) | |
| async def lifespan(app: FastAPI): | |
| app.state.engine = await asyncio.to_thread(load_engine) | |
| yield | |
| app = FastAPI(title="CoverageCheck", lifespan=lifespan) | |
| def info() -> dict: | |
| return { | |
| "systems": list(config.WEB_SYSTEMS), | |
| "model": app.state.engine.model, | |
| "today": utc_today().isoformat(), | |
| "questions_left": gate.left(), | |
| "not_advice": NOT_ADVICE, | |
| } | |
| def ask(body: AskRequest, request: Request) -> StreamingResponse: | |
| client = client_of(request) | |
| refused = gate.admit(client) | |
| if refused: | |
| raise HTTPException(status_code=429, detail=refused) | |
| day = body.day or utc_today() | |
| events = app.state.engine.events(body.system, body.question, day, body.history) | |
| cancel = threading.Event() | |
| inbox = start(events, lambda: gate.release(client), cancel) | |
| return StreamingResponse( | |
| relay(inbox, cancel, ping_s, deadline_s), | |
| media_type="text/event-stream", | |
| headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, | |
| ) | |
| if dist is not None and (dist / "index.html").exists(): | |
| app.mount("/", SpaFiles(directory=dist, html=True), name="web") | |
| return app | |
| def main() -> None: | |
| import uvicorn | |
| logging.basicConfig(level=logging.INFO) | |
| app = create_app(Engine.load, config.WEB_DIST_DIR) | |
| # open streams would hold a shutdown up to the deadline; the host kills us sooner | |
| uvicorn.run( | |
| app, | |
| host=os.environ.get("HOST", config.WEB_HOST), | |
| port=int(os.environ.get("PORT", config.WEB_PORT)), | |
| timeout_graceful_shutdown=config.WEB_SHUTDOWN_S, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |