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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serve the trained checkpoint through the TypeSafe decision API."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import binascii
|
| 7 |
+
import hmac
|
| 8 |
+
import os
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
import uuid
|
| 12 |
+
from _thread import LockType
|
| 13 |
+
from collections.abc import AsyncIterator
|
| 14 |
+
from contextlib import asynccontextmanager
|
| 15 |
+
from dataclasses import dataclass, field
|
| 16 |
+
from datetime import datetime, timezone
|
| 17 |
+
from io import BytesIO
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import TYPE_CHECKING, Annotated, Literal, cast
|
| 20 |
+
|
| 21 |
+
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
| 22 |
+
from fastapi.exceptions import RequestValidationError
|
| 23 |
+
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
| 24 |
+
from PIL import Image, UnidentifiedImageError
|
| 25 |
+
from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator
|
| 26 |
+
from starlette.concurrency import run_in_threadpool
|
| 27 |
+
from starlette.middleware.base import RequestResponseEndpoint
|
| 28 |
+
|
| 29 |
+
from autojev.types import Answer, DecisionInput, DecisionResponse, JSONValue, Question as DecisionQuestion
|
| 30 |
+
|
| 31 |
+
if TYPE_CHECKING:
|
| 32 |
+
from autojev.model import DecisionModel
|
| 33 |
+
|
| 34 |
+
type Content = str | dict[str, JsonValue] | list[JsonValue]
|
| 35 |
+
DEFAULT_MODEL = "autojev-qwen3.8-27b"
|
| 36 |
+
ALIASES = {"autojev", "jev-latest", "jev-preview", "jev-1.13.0", DEFAULT_MODEL}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass
|
| 40 |
+
class Service:
|
| 41 |
+
model: DecisionModel | None = None
|
| 42 |
+
name: str = DEFAULT_MODEL
|
| 43 |
+
checkpoint: str = "checkpoints/selected"
|
| 44 |
+
release_date: str = ""
|
| 45 |
+
lock: LockType = field(default_factory=threading.Lock)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
service = Service()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Question(BaseModel):
|
| 52 |
+
model_config = ConfigDict(extra="forbid")
|
| 53 |
+
instructions: Content | None = None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Choice(Question):
|
| 57 |
+
type: Literal["choice"]
|
| 58 |
+
criteria: dict[str, Content | None] = Field(min_length=1, max_length=255)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class Score(Question):
|
| 62 |
+
type: Literal["score"]
|
| 63 |
+
criteria: list[Content] = Field(min_length=2, max_length=10)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Noul(Question):
|
| 67 |
+
type: Literal["noul"]
|
| 68 |
+
criteria: dict[Literal["true", "false"], Content | None] | None = None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class EvaluationRequest(BaseModel):
|
| 72 |
+
model_config = ConfigDict(extra="forbid")
|
| 73 |
+
model: str
|
| 74 |
+
state: Content
|
| 75 |
+
questions: dict[str, Annotated[Choice | Score | Noul, Field(discriminator="type")]] = Field(min_length=1)
|
| 76 |
+
images: list[str] = Field(default_factory=list, max_length=4)
|
| 77 |
+
|
| 78 |
+
@field_validator("model")
|
| 79 |
+
@classmethod
|
| 80 |
+
def known_model(cls, value: str) -> str:
|
| 81 |
+
if value not in ALIASES | {service.name}:
|
| 82 |
+
raise ValueError(f"Unknown model. Use {service.name} or jev-latest.")
|
| 83 |
+
return value
|
| 84 |
+
|
| 85 |
+
@field_validator("images")
|
| 86 |
+
@classmethod
|
| 87 |
+
def valid_images(cls, values: list[str]) -> list[str]:
|
| 88 |
+
for value in values:
|
| 89 |
+
if len(value) > 12_000_000:
|
| 90 |
+
raise ValueError("Each image must be at most 8 MB before base64 encoding.")
|
| 91 |
+
header, separator, encoded = value.partition(",")
|
| 92 |
+
if not separator or header not in {
|
| 93 |
+
"data:image/png;base64", "data:image/jpeg;base64", "data:image/webp;base64",
|
| 94 |
+
}:
|
| 95 |
+
raise ValueError("Images must be base64 PNG, JPEG, or WebP data URLs.")
|
| 96 |
+
try:
|
| 97 |
+
content = base64.b64decode(encoded, validate=True)
|
| 98 |
+
if len(content) > 8_000_000:
|
| 99 |
+
raise ValueError("Each image must be at most 8 MB.")
|
| 100 |
+
with Image.open(BytesIO(content)) as image:
|
| 101 |
+
if image.width * image.height > 16_000_000:
|
| 102 |
+
raise ValueError("Each image must have at most 16 million pixels.")
|
| 103 |
+
if image.format not in {"PNG", "JPEG", "WEBP"}:
|
| 104 |
+
raise ValueError("Unsupported image format.")
|
| 105 |
+
image.verify()
|
| 106 |
+
except (binascii.Error, OSError, SyntaxError, UnidentifiedImageError, Image.DecompressionBombError) as error:
|
| 107 |
+
raise ValueError("Invalid image data.") from error
|
| 108 |
+
return values
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def authenticate(authorization: str | None = Header(default=None)) -> None:
|
| 112 |
+
key = os.getenv("AUTOJEV_API_KEY")
|
| 113 |
+
if key and not hmac.compare_digest((authorization or "").encode(), f"Bearer {key}".encode()):
|
| 114 |
+
raise HTTPException(401, "Missing or invalid API key.", headers={"WWW-Authenticate": "Bearer"})
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@asynccontextmanager
|
| 118 |
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
| 119 |
+
from autojev.model import DecisionModel
|
| 120 |
+
|
| 121 |
+
service.checkpoint = os.getenv("AUTOJEV_CHECKPOINT", "checkpoints/selected")
|
| 122 |
+
service.model = await run_in_threadpool(DecisionModel, checkpoint=service.checkpoint)
|
| 123 |
+
service.name = f"autojev-{service.model.base_model.rsplit('/', 1)[-1].lower()}"
|
| 124 |
+
modified = (Path(service.checkpoint) / "decision_config.json").stat().st_mtime
|
| 125 |
+
service.release_date = datetime.fromtimestamp(modified, timezone.utc).date().isoformat()
|
| 126 |
+
try:
|
| 127 |
+
yield
|
| 128 |
+
finally:
|
| 129 |
+
service.model = None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
app = FastAPI(title="AutoJev", version="0.2.0", lifespan=lifespan)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@app.middleware("http")
|
| 136 |
+
async def request_metadata(request: Request, call_next: RequestResponseEndpoint) -> Response:
|
| 137 |
+
started, identifier = time.perf_counter(), uuid.uuid4().hex
|
| 138 |
+
response = await call_next(request)
|
| 139 |
+
response.headers["x-typesafe-request-id"] = identifier
|
| 140 |
+
response.headers["x-request-id"] = identifier
|
| 141 |
+
response.headers["server-timing"] = f"total;dur={(time.perf_counter() - started) * 1000:.1f}"
|
| 142 |
+
return response
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@app.exception_handler(RequestValidationError)
|
| 146 |
+
async def validation_error(request: Request, error: RequestValidationError) -> JSONResponse:
|
| 147 |
+
return JSONResponse(status_code=422, content={"detail": [
|
| 148 |
+
{"loc": item["loc"], "msg": item["msg"], "type": item["type"]}
|
| 149 |
+
for item in error.errors()
|
| 150 |
+
]})
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
|
| 154 |
+
def playground() -> str:
|
| 155 |
+
return Path(__file__).with_name("playground.html").read_text()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@app.get("/health", response_model=None)
|
| 159 |
+
def health() -> dict[str, JSONValue]:
|
| 160 |
+
return {"status": "ready" if service.model is not None else "loading", "model": service.name,
|
| 161 |
+
"checkpoint": service.checkpoint, "authentication": bool(os.getenv("AUTOJEV_API_KEY")),
|
| 162 |
+
"modalities": ["text", "image"]}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@app.get("/v1/models", dependencies=[Depends(authenticate)], response_model=None)
|
| 166 |
+
def models() -> dict[str, JSONValue]:
|
| 167 |
+
return {"models": [
|
| 168 |
+
{"name": name, "description": "Local AutoJev text and image decisions.", "release_date": service.release_date}
|
| 169 |
+
for name in sorted(ALIASES | {service.name})
|
| 170 |
+
]}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def predict(model: DecisionModel, body: EvaluationRequest) -> DecisionResponse:
|
| 174 |
+
import torch
|
| 175 |
+
from autojev.model import answer
|
| 176 |
+
|
| 177 |
+
questions = {key: cast(DecisionQuestion, question.model_dump(exclude_none=True))
|
| 178 |
+
for key, question in body.questions.items()}
|
| 179 |
+
identifiers = list(questions)
|
| 180 |
+
rows: list[DecisionInput] = [{"state": body.state, "question": question, "images": list(body.images)}
|
| 181 |
+
for question in questions.values()]
|
| 182 |
+
answers: dict[str, Answer] = {}
|
| 183 |
+
input_tokens = 0
|
| 184 |
+
with torch.inference_mode():
|
| 185 |
+
for start in range(0, len(rows), 8):
|
| 186 |
+
batch = model.prepare(rows[start:start + 8])
|
| 187 |
+
distributions: list[list[float]] = (model(batch) / model.temperature).softmax(-1).cpu().tolist()
|
| 188 |
+
for identifier, values, count in zip(identifiers[start:start + 8], distributions, batch.counts, strict=True):
|
| 189 |
+
answers[identifier] = answer(questions[identifier], values[:count])
|
| 190 |
+
input_tokens += batch.input_tokens
|
| 191 |
+
return {"model": service.name, "answers": answers, "usage": {"input_tokens": input_tokens, "output_tokens": 0}}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@app.post("/v1/systemone", dependencies=[Depends(authenticate)], response_model=None)
|
| 195 |
+
async def system_one(body: EvaluationRequest) -> DecisionResponse:
|
| 196 |
+
model = service.model
|
| 197 |
+
if model is None:
|
| 198 |
+
raise HTTPException(503, "The model is not ready.")
|
| 199 |
+
if not service.lock.acquire(blocking=False):
|
| 200 |
+
raise HTTPException(529, "The model is busy. Retry shortly.", headers={"Retry-After": "1"})
|
| 201 |
+
try:
|
| 202 |
+
return await run_in_threadpool(predict, model, body)
|
| 203 |
+
except ValueError as error:
|
| 204 |
+
raise HTTPException(422, str(error)) from error
|
| 205 |
+
finally:
|
| 206 |
+
service.lock.release()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def main() -> None:
|
| 210 |
+
import uvicorn
|
| 211 |
+
|
| 212 |
+
uvicorn.run("autojev.server:app", host=os.getenv("AUTOJEV_HOST", "127.0.0.1"), port=int(os.getenv("PORT", "8000")))
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
main()
|