File size: 1,636 Bytes
4807d4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""An HTTP server for a Discerna model: `POST /v1/decide` takes a request and returns its answers.

    discerna serve --model <owner>/Discerna-v1-475M   # or a local model folder

Errors: a request beyond the model's limits is HTTP 413 with "unsupported" in the body, an invalid
body is 422, anything else is 500.
"""

from __future__ import annotations

import threading

from fastapi import FastAPI, HTTPException

from discerna import __version__
from discerna.contract import DecisionRequest
from discerna.engine import Discerna, Unsupported


def create_app(model: Discerna) -> FastAPI:
    app = FastAPI(title="Discerna", version=__version__)
    lock = threading.Lock()  # one forward pass at a time: torch models are not thread-safe

    @app.get("/healthz")
    def healthz() -> dict:
        return {"ok": True}

    @app.get("/v1/models")
    def models() -> dict:
        return {"data": [{"id": model.name, "modalities": ["text", "image"] if model.accepts_images else ["text"],
                          "device": str(model.device), "dtype": str(model.dtype).removeprefix("torch.")}]}

    @app.post("/v1/decide")
    def decide(request: DecisionRequest) -> dict:
        with lock:
            result = model.decide_batch([request])[0]
        if isinstance(result, Unsupported):
            raise HTTPException(status_code=413, detail={"error": "unsupported", "reason": str(result)})
        if isinstance(result, Exception):
            raise HTTPException(status_code=500, detail={"error": type(result).__name__, "reason": str(result)})
        return result.model_dump(mode="json", exclude_none=True)

    return app