File size: 2,580 Bytes
267266e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import math
from typing import Any, Mapping

import httpx

from app.config import Settings


class RemoteModelError(RuntimeError):
    pass


class RemoteModelClient:
    """Hosted-model transport; adjust only this file when its API is known."""

    def __init__(self, settings: Settings) -> None:
        self._url = settings.remote_model_url
        self._token = settings.remote_model_api_token
        self._timeout = settings.remote_model_timeout_seconds

    @property
    def configured(self) -> bool:
        return bool(self._url)

    async def predict(self, rows: list[Mapping[str, Any]]) -> list[float]:
        if not self._url:
            raise RemoteModelError("REMOTE_MODEL_URL is not configured")

        headers = {"Accept": "application/json"}
        if self._token:
            headers["Authorization"] = f"Bearer {self._token}"

        payload = {"rows": [self._json_safe(dict(row)) for row in rows]}
        try:
            async with httpx.AsyncClient(timeout=self._timeout) as client:
                response = await client.post(self._url, json=payload, headers=headers)
                response.raise_for_status()
                body = response.json()
        except (httpx.HTTPError, ValueError) as exc:
            raise RemoteModelError(f"Hosted model request failed: {exc}") from exc

        probabilities = body.get("probabilities") if isinstance(body, dict) else None
        if not isinstance(probabilities, list) or len(probabilities) != len(rows):
            raise RemoteModelError(
                "Hosted model must return {'probabilities': [..]} in input order"
            )

        try:
            result = [float(value) for value in probabilities]
        except (TypeError, ValueError) as exc:
            raise RemoteModelError("Hosted model returned non-numeric probabilities") from exc

        if any(not math.isfinite(value) or not 0.0 <= value <= 1.0 for value in result):
            raise RemoteModelError("Hosted probabilities must be finite and between 0 and 1")
        return result

    @staticmethod
    def _json_safe(row: dict[str, Any]) -> dict[str, Any]:
        safe: dict[str, Any] = {}
        for key, value in row.items():
            if value is None:
                safe[key] = None
                continue
            try:
                value = value.item()
            except AttributeError:
                pass
            safe[key] = value if not isinstance(value, float) or math.isfinite(value) else None
        return safe