physionlabs 0.1.0rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- physionlabs/__init__.py +92 -0
- physionlabs/_client.py +79 -0
- physionlabs/_poll.py +42 -0
- physionlabs/_transport.py +201 -0
- physionlabs/errors.py +171 -0
- physionlabs/models.py +651 -0
- physionlabs/py.typed +0 -0
- physionlabs/resources/__init__.py +5 -0
- physionlabs/resources/account.py +39 -0
- physionlabs/resources/evaluations.py +206 -0
- physionlabs/resources/videos.py +142 -0
- physionlabs-0.1.0rc1.dist-info/METADATA +111 -0
- physionlabs-0.1.0rc1.dist-info/RECORD +16 -0
- physionlabs-0.1.0rc1.dist-info/WHEEL +4 -0
- physionlabs-0.1.0rc1.dist-info/licenses/LICENSE +202 -0
- physionlabs-0.1.0rc1.dist-info/licenses/NOTICE +4 -0
physionlabs/__init__.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""physionlabs -- official Python client for the Galileo video evaluation API.
|
|
2
|
+
|
|
3
|
+
from physionlabs import Galileo
|
|
4
|
+
|
|
5
|
+
galileo = Galileo()
|
|
6
|
+
evaluation = galileo.evaluations.create_and_wait(
|
|
7
|
+
prompt="A red ball rolls off a table and bounces twice.",
|
|
8
|
+
video={"url": "https://cdn.example.com/red-ball.mp4"},
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
The response models in `physionlabs.models` are GENERATED from the API's OpenAPI
|
|
12
|
+
description (`openapi/galileo-v1.yaml`), so a field cannot be wrong here without
|
|
13
|
+
being wrong in the contract. They do not enforce the contract's value ranges --
|
|
14
|
+
see `scripts/generate_models.py` for why a client must not refuse to parse its
|
|
15
|
+
own server's output.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from ._client import DEFAULT_BASE_URL, Galileo
|
|
21
|
+
from .errors import (
|
|
22
|
+
APIError,
|
|
23
|
+
AuthenticationError,
|
|
24
|
+
ConnectionError,
|
|
25
|
+
GalileoError,
|
|
26
|
+
InsufficientCreditsError,
|
|
27
|
+
InvalidRequestError,
|
|
28
|
+
NotFoundError,
|
|
29
|
+
PollTimeoutError,
|
|
30
|
+
RateLimitError,
|
|
31
|
+
ServerError,
|
|
32
|
+
)
|
|
33
|
+
from .models import (
|
|
34
|
+
Account,
|
|
35
|
+
BoundingBox,
|
|
36
|
+
BoxKeyframe,
|
|
37
|
+
Credits,
|
|
38
|
+
Evaluation,
|
|
39
|
+
EvaluationList,
|
|
40
|
+
EvaluationResult,
|
|
41
|
+
EvaluationSummary,
|
|
42
|
+
Glitch,
|
|
43
|
+
GlitchRegion,
|
|
44
|
+
GlitchType,
|
|
45
|
+
Model,
|
|
46
|
+
ModelList,
|
|
47
|
+
PromptSegment,
|
|
48
|
+
QuotaReport,
|
|
49
|
+
SystemStatus,
|
|
50
|
+
TimePoint,
|
|
51
|
+
Video,
|
|
52
|
+
VideoStatus,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
__version__ = "0.1.0rc1"
|
|
56
|
+
|
|
57
|
+
__all__ = [
|
|
58
|
+
"Galileo",
|
|
59
|
+
"DEFAULT_BASE_URL",
|
|
60
|
+
"__version__",
|
|
61
|
+
# errors
|
|
62
|
+
"GalileoError",
|
|
63
|
+
"APIError",
|
|
64
|
+
"InvalidRequestError",
|
|
65
|
+
"AuthenticationError",
|
|
66
|
+
"NotFoundError",
|
|
67
|
+
"InsufficientCreditsError",
|
|
68
|
+
"RateLimitError",
|
|
69
|
+
"ServerError",
|
|
70
|
+
"ConnectionError",
|
|
71
|
+
"PollTimeoutError",
|
|
72
|
+
# models
|
|
73
|
+
"Account",
|
|
74
|
+
"BoundingBox",
|
|
75
|
+
"BoxKeyframe",
|
|
76
|
+
"Credits",
|
|
77
|
+
"Evaluation",
|
|
78
|
+
"EvaluationList",
|
|
79
|
+
"EvaluationResult",
|
|
80
|
+
"EvaluationSummary",
|
|
81
|
+
"Glitch",
|
|
82
|
+
"GlitchRegion",
|
|
83
|
+
"GlitchType",
|
|
84
|
+
"Model",
|
|
85
|
+
"ModelList",
|
|
86
|
+
"PromptSegment",
|
|
87
|
+
"QuotaReport",
|
|
88
|
+
"SystemStatus",
|
|
89
|
+
"TimePoint",
|
|
90
|
+
"Video",
|
|
91
|
+
"VideoStatus",
|
|
92
|
+
]
|
physionlabs/_client.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""The client. One object, three resources, no configuration beyond a key."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from types import TracebackType
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from ._transport import Transport
|
|
11
|
+
from .resources import Account, Evaluations, Videos
|
|
12
|
+
|
|
13
|
+
DEFAULT_BASE_URL = "https://api.physionlabs.ai"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Galileo:
|
|
17
|
+
"""Client for the Galileo video evaluation API.
|
|
18
|
+
|
|
19
|
+
``api_key`` defaults to ``GALILEO_API_KEY`` from the environment, rather than
|
|
20
|
+
being required as an argument, because the alternative is a key written into a
|
|
21
|
+
source file -- and a key in a source file is a key in somebody's git history.
|
|
22
|
+
|
|
23
|
+
Usable as a context manager, which closes the underlying HTTP connections::
|
|
24
|
+
|
|
25
|
+
with Galileo() as galileo:
|
|
26
|
+
...
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
*,
|
|
32
|
+
api_key: str | None = None,
|
|
33
|
+
base_url: str | None = None,
|
|
34
|
+
upload_base_url: str | None = None,
|
|
35
|
+
timeout: float = 60.0,
|
|
36
|
+
max_retries: int = 2,
|
|
37
|
+
rate_limit_budget: float = 60.0,
|
|
38
|
+
max_rate_limit_retries: int = 20,
|
|
39
|
+
max_concurrency: int = 4,
|
|
40
|
+
http_client: httpx.Client | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
key = api_key or os.environ.get("GALILEO_API_KEY")
|
|
43
|
+
if not key:
|
|
44
|
+
raise ValueError(
|
|
45
|
+
"No API key. Pass api_key=, or set GALILEO_API_KEY in the environment."
|
|
46
|
+
)
|
|
47
|
+
resolved_base = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
48
|
+
|
|
49
|
+
self._transport = Transport(
|
|
50
|
+
api_key=key,
|
|
51
|
+
base_url=resolved_base,
|
|
52
|
+
timeout=timeout,
|
|
53
|
+
max_retries=max_retries,
|
|
54
|
+
rate_limit_budget=rate_limit_budget,
|
|
55
|
+
max_rate_limit_retries=max_rate_limit_retries,
|
|
56
|
+
max_concurrency=max_concurrency,
|
|
57
|
+
client=http_client,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
self.evaluations = Evaluations(self._transport)
|
|
61
|
+
# `upload_base_url` is separate from `base_url` because the two genuinely
|
|
62
|
+
# differ: uploads go to storage infrastructure, and pinning them together
|
|
63
|
+
# would send the bytes to whichever host happens to serve the API.
|
|
64
|
+
self.videos = Videos(self._transport, upload_base_url or resolved_base)
|
|
65
|
+
self.account = Account(self._transport)
|
|
66
|
+
|
|
67
|
+
def close(self) -> None:
|
|
68
|
+
self._transport.close()
|
|
69
|
+
|
|
70
|
+
def __enter__(self) -> Galileo:
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
def __exit__(
|
|
74
|
+
self,
|
|
75
|
+
exc_type: type[BaseException] | None,
|
|
76
|
+
exc: BaseException | None,
|
|
77
|
+
tb: TracebackType | None,
|
|
78
|
+
) -> None:
|
|
79
|
+
self.close()
|
physionlabs/_poll.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Wait for something asynchronous to settle.
|
|
2
|
+
|
|
3
|
+
Backs off rather than polling at a fixed rate: a job that finishes in two seconds
|
|
4
|
+
should be noticed quickly, and one that takes three minutes should not be asked
|
|
5
|
+
about ninety times.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
from typing import Callable, TypeVar
|
|
12
|
+
|
|
13
|
+
from .errors import PollTimeoutError
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def poll_until(
|
|
19
|
+
fetch_once: Callable[[], T],
|
|
20
|
+
settled: Callable[[T], bool],
|
|
21
|
+
*,
|
|
22
|
+
describe: str,
|
|
23
|
+
status_of: Callable[[T], str] | None = None,
|
|
24
|
+
timeout: float = 600.0,
|
|
25
|
+
initial_interval: float = 1.0,
|
|
26
|
+
max_interval: float = 8.0,
|
|
27
|
+
) -> T:
|
|
28
|
+
interval = initial_interval
|
|
29
|
+
deadline = time.monotonic() + timeout
|
|
30
|
+
|
|
31
|
+
while True:
|
|
32
|
+
value = fetch_once()
|
|
33
|
+
if settled(value):
|
|
34
|
+
return value
|
|
35
|
+
if time.monotonic() + interval > deadline:
|
|
36
|
+
status = f" (last status: {status_of(value)})" if status_of else ""
|
|
37
|
+
raise PollTimeoutError(
|
|
38
|
+
f"{describe} did not settle within {timeout:.0f}s{status}. "
|
|
39
|
+
"It is still running; retrieve it again later."
|
|
40
|
+
)
|
|
41
|
+
time.sleep(interval)
|
|
42
|
+
interval = min(interval * 1.5, max_interval)
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""HTTP: auth, timeouts, retries, rate-limit backoff, bounded concurrency.
|
|
2
|
+
|
|
3
|
+
A script calling this API once needs none of this. A job pushing a few hundred
|
|
4
|
+
clips through it needs all of it, and needs it to behave the same on every call
|
|
5
|
+
rather than be remembered at each call site.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import random
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, BinaryIO, Iterator, Mapping
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from .errors import ConnectionError as GalileoConnectionError
|
|
18
|
+
from .errors import error_from_response, retry_after_seconds
|
|
19
|
+
|
|
20
|
+
# Codes that are terminal despite a retryable status.
|
|
21
|
+
#
|
|
22
|
+
# `model_output_invalid` is a 502: the model answered, and answered unusably.
|
|
23
|
+
# The same input produces the same unusable answer, so a retry cannot change the
|
|
24
|
+
# outcome -- and the run is metered, so it would spend the caller's credits again
|
|
25
|
+
# on a failure that is already decided.
|
|
26
|
+
#
|
|
27
|
+
# `model_timeout` (504) is deliberately absent. There the model was still working
|
|
28
|
+
# when the gateway gave up, and a second attempt may well land.
|
|
29
|
+
TERMINAL_CODES = frozenset({"model_output_invalid", "unsupported_codec", "file_too_large"})
|
|
30
|
+
|
|
31
|
+
RETRYABLE_STATUS = frozenset({408, 409, 500, 502, 503, 504})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Transport:
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
*,
|
|
38
|
+
api_key: str,
|
|
39
|
+
base_url: str,
|
|
40
|
+
timeout: float = 60.0,
|
|
41
|
+
max_retries: int = 2,
|
|
42
|
+
rate_limit_budget: float = 60.0,
|
|
43
|
+
max_rate_limit_retries: int = 20,
|
|
44
|
+
max_concurrency: int = 4,
|
|
45
|
+
client: httpx.Client | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
self._api_key = api_key
|
|
48
|
+
self._base_url = base_url.rstrip("/")
|
|
49
|
+
self._timeout = timeout
|
|
50
|
+
self._max_retries = max_retries
|
|
51
|
+
# A budget of its own, separate from `max_retries`, because a rate-limit
|
|
52
|
+
# reply is flow control rather than failure. Charged to the retry count, a
|
|
53
|
+
# batch larger than that count fails on its own tail: submit ten things
|
|
54
|
+
# against a limit that admits two a minute and the last must wait minutes,
|
|
55
|
+
# which no sane retry count covers.
|
|
56
|
+
self._rate_limit_budget = rate_limit_budget
|
|
57
|
+
# A budget measured in SLEEP bounds nothing when the sleeps are zero.
|
|
58
|
+
# `Retry-After: 0` is a legal answer -- and a proxy or a misconfigured
|
|
59
|
+
# limiter can give it indefinitely -- so a loop guarded only by the budget
|
|
60
|
+
# spins as fast as the network allows, forever, even at budget 0. Two
|
|
61
|
+
# further bounds close that: this count, and a wall-clock deadline taken
|
|
62
|
+
# before the first attempt.
|
|
63
|
+
self._max_rate_limit_retries = max_rate_limit_retries
|
|
64
|
+
# Python has no ambient limit either. A ThreadPoolExecutor over two
|
|
65
|
+
# hundred clips otherwise opens two hundred requests, most of which come
|
|
66
|
+
# straight back 429 and spend the budget above on requests that were never
|
|
67
|
+
# going to be admitted.
|
|
68
|
+
self._gate = threading.Semaphore(max_concurrency)
|
|
69
|
+
self._client = client or httpx.Client(timeout=timeout, follow_redirects=True)
|
|
70
|
+
self._owns_client = client is None
|
|
71
|
+
|
|
72
|
+
def close(self) -> None:
|
|
73
|
+
if self._owns_client:
|
|
74
|
+
self._client.close()
|
|
75
|
+
|
|
76
|
+
def json(self, **spec: Any) -> Any:
|
|
77
|
+
response = self.send(**spec)
|
|
78
|
+
if response.status_code == 204 or not response.content:
|
|
79
|
+
return None
|
|
80
|
+
return response.json()
|
|
81
|
+
|
|
82
|
+
def send(
|
|
83
|
+
self,
|
|
84
|
+
*,
|
|
85
|
+
method: str,
|
|
86
|
+
path: str | None = None,
|
|
87
|
+
absolute_url: str | None = None,
|
|
88
|
+
params: Mapping[str, Any] | None = None,
|
|
89
|
+
body: Any = None,
|
|
90
|
+
content: bytes | BinaryIO | Iterator[bytes] | None = None,
|
|
91
|
+
content_type: str | None = None,
|
|
92
|
+
content_length: int | None = None,
|
|
93
|
+
anonymous: bool = False,
|
|
94
|
+
max_retries: int | None = None,
|
|
95
|
+
) -> httpx.Response:
|
|
96
|
+
if absolute_url is None and path is None:
|
|
97
|
+
raise ValueError("a request needs either `path` or `absolute_url`")
|
|
98
|
+
url = absolute_url or f"{self._base_url}{path}"
|
|
99
|
+
retries = self._max_retries if max_retries is None else max_retries
|
|
100
|
+
|
|
101
|
+
headers: dict[str, str] = {"accept": "application/json"}
|
|
102
|
+
if not anonymous:
|
|
103
|
+
headers["authorization"] = f"Bearer {self._api_key}"
|
|
104
|
+
if content is not None:
|
|
105
|
+
headers["content-type"] = content_type or "application/octet-stream"
|
|
106
|
+
if content_length is None:
|
|
107
|
+
raise ValueError("a streamed body must declare content_length")
|
|
108
|
+
# Declared explicitly: a receiver that has to refuse an oversized body
|
|
109
|
+
# before storing it cannot do so without knowing the size up front.
|
|
110
|
+
headers["content-length"] = str(content_length)
|
|
111
|
+
|
|
112
|
+
query = {k: v for k, v in (params or {}).items() if v is not None}
|
|
113
|
+
|
|
114
|
+
with self._gate:
|
|
115
|
+
return self._attempt(
|
|
116
|
+
method=method,
|
|
117
|
+
url=url,
|
|
118
|
+
headers=headers,
|
|
119
|
+
query=query,
|
|
120
|
+
body=body,
|
|
121
|
+
content=content,
|
|
122
|
+
retries=retries,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def _attempt(
|
|
126
|
+
self,
|
|
127
|
+
*,
|
|
128
|
+
method: str,
|
|
129
|
+
url: str,
|
|
130
|
+
headers: dict[str, str],
|
|
131
|
+
query: dict[str, Any],
|
|
132
|
+
body: Any,
|
|
133
|
+
content: Any,
|
|
134
|
+
retries: int,
|
|
135
|
+
) -> httpx.Response:
|
|
136
|
+
rate_limit_spent = 0.0
|
|
137
|
+
rate_limited = 0
|
|
138
|
+
attempt = 0
|
|
139
|
+
rate_limit_deadline = time.monotonic() + self._rate_limit_budget
|
|
140
|
+
|
|
141
|
+
while True:
|
|
142
|
+
try:
|
|
143
|
+
response = self._client.request(
|
|
144
|
+
method,
|
|
145
|
+
url,
|
|
146
|
+
headers=headers,
|
|
147
|
+
params=query or None,
|
|
148
|
+
json=body if content is None else None,
|
|
149
|
+
content=content,
|
|
150
|
+
timeout=self._timeout,
|
|
151
|
+
)
|
|
152
|
+
except httpx.HTTPError as exc:
|
|
153
|
+
# A streamed body cannot be replayed -- the file position has
|
|
154
|
+
# moved -- so a retry would send a truncated request. Uploads pass
|
|
155
|
+
# retries=0 anyway; this is the guard for anyone who does not.
|
|
156
|
+
if attempt < retries and content is None:
|
|
157
|
+
attempt += 1
|
|
158
|
+
time.sleep(_backoff(attempt))
|
|
159
|
+
continue
|
|
160
|
+
raise GalileoConnectionError(f"Could not reach Galileo at {url}: {exc}") from exc
|
|
161
|
+
|
|
162
|
+
if response.is_success:
|
|
163
|
+
return response
|
|
164
|
+
|
|
165
|
+
if response.status_code == 429:
|
|
166
|
+
wait = retry_after_seconds(response.headers)
|
|
167
|
+
if wait is None:
|
|
168
|
+
wait = _backoff(attempt + 1)
|
|
169
|
+
# Three bounds, each closing a hole the others leave open:
|
|
170
|
+
# * the count stops a `Retry-After: 0` loop, where no time goes;
|
|
171
|
+
# * the deadline stops many small waits adding up past the
|
|
172
|
+
# budget in wall-clock terms;
|
|
173
|
+
# * the budget stops one enormous `Retry-After` being honoured.
|
|
174
|
+
within_count = rate_limited < self._max_rate_limit_retries
|
|
175
|
+
within_deadline = time.monotonic() + wait <= rate_limit_deadline
|
|
176
|
+
within_budget = rate_limit_spent + wait <= self._rate_limit_budget
|
|
177
|
+
if within_count and within_deadline and within_budget:
|
|
178
|
+
rate_limited += 1
|
|
179
|
+
rate_limit_spent += wait
|
|
180
|
+
if wait > 0:
|
|
181
|
+
time.sleep(wait)
|
|
182
|
+
continue
|
|
183
|
+
raise error_from_response(response)
|
|
184
|
+
|
|
185
|
+
error = error_from_response(response)
|
|
186
|
+
if (
|
|
187
|
+
attempt < retries
|
|
188
|
+
and content is None
|
|
189
|
+
and response.status_code in RETRYABLE_STATUS
|
|
190
|
+
and error.code not in TERMINAL_CODES
|
|
191
|
+
):
|
|
192
|
+
attempt += 1
|
|
193
|
+
time.sleep(_backoff(attempt))
|
|
194
|
+
continue
|
|
195
|
+
raise error
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _backoff(attempt: int) -> float:
|
|
199
|
+
"""Exponential, with jitter so a batch that fails together does not retry together."""
|
|
200
|
+
base = min(0.5 * 2.0 ** (attempt - 1), 8.0)
|
|
201
|
+
return base + random.random() * base * 0.25
|
physionlabs/errors.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""One exception per thing a caller might actually do about it.
|
|
2
|
+
|
|
3
|
+
The split is by REACTION, not by status code. ``RateLimitError`` and
|
|
4
|
+
``InsufficientCreditsError`` are both a refusal, but one clears on its own and
|
|
5
|
+
the other needs somebody to buy credits -- which is the difference between a
|
|
6
|
+
batch that pauses and a batch that stops.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"GalileoError",
|
|
17
|
+
"APIError",
|
|
18
|
+
"InvalidRequestError",
|
|
19
|
+
"AuthenticationError",
|
|
20
|
+
"NotFoundError",
|
|
21
|
+
"InsufficientCreditsError",
|
|
22
|
+
"RateLimitError",
|
|
23
|
+
"ServerError",
|
|
24
|
+
"ConnectionError",
|
|
25
|
+
"PollTimeoutError",
|
|
26
|
+
"error_from_response",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class GalileoError(Exception):
|
|
31
|
+
"""Base class. Catch this to catch anything this client raises."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class APIError(GalileoError):
|
|
35
|
+
"""The API answered, and the answer was a refusal."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
status: int,
|
|
41
|
+
type: str,
|
|
42
|
+
code: str,
|
|
43
|
+
message: str,
|
|
44
|
+
request_id: str | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
self.status = status
|
|
48
|
+
self.type = type
|
|
49
|
+
self.code = code
|
|
50
|
+
self.message = message
|
|
51
|
+
#: Quote this when asking us about a specific failure.
|
|
52
|
+
self.request_id = request_id
|
|
53
|
+
|
|
54
|
+
def __str__(self) -> str:
|
|
55
|
+
suffix = f" (request_id={self.request_id})" if self.request_id else ""
|
|
56
|
+
return f"[{self.status} {self.code}] {self.message}{suffix}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class InvalidRequestError(APIError):
|
|
60
|
+
"""The request was wrong: bad body, unsupported codec, video too large."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class AuthenticationError(APIError):
|
|
64
|
+
"""The key is missing, malformed, or revoked."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class NotFoundError(APIError):
|
|
68
|
+
"""No such evaluation or video, or not yours."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class InsufficientCreditsError(APIError):
|
|
72
|
+
"""Out of credits. Retrying cannot help; the balance has to change."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class RateLimitError(APIError):
|
|
76
|
+
"""Too many requests.
|
|
77
|
+
|
|
78
|
+
Unlike the others this clears by waiting, and ``retry_after`` is how long the
|
|
79
|
+
server asked for. The client already waits and retries inside its rate-limit
|
|
80
|
+
budget, so seeing this means the budget ran out -- not that nothing was tried.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, *, retry_after: float | None = None, **kw: Any) -> None:
|
|
84
|
+
super().__init__(**kw)
|
|
85
|
+
self.retry_after = retry_after
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ServerError(APIError):
|
|
89
|
+
"""Our fault: a 5xx, or a model that answered unusably."""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class ConnectionError(GalileoError):
|
|
93
|
+
"""The request never got an answer: DNS, TCP, TLS, a timeout.
|
|
94
|
+
|
|
95
|
+
Separate from ``ServerError`` because the two differ in what is safe to
|
|
96
|
+
assume. A 500 means the server received the request and may have acted on
|
|
97
|
+
it; this means we do not know whether it arrived at all.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class PollTimeoutError(GalileoError):
|
|
102
|
+
"""A wait that ran out of patience before the job settled.
|
|
103
|
+
|
|
104
|
+
The job is still running. Retrieve it again later rather than resubmitting --
|
|
105
|
+
a second submission is a second charge.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
_BY_STATUS: dict[int, type[APIError]] = {
|
|
110
|
+
400: InvalidRequestError,
|
|
111
|
+
401: AuthenticationError,
|
|
112
|
+
402: InsufficientCreditsError,
|
|
113
|
+
403: AuthenticationError,
|
|
114
|
+
404: NotFoundError,
|
|
115
|
+
413: InvalidRequestError,
|
|
116
|
+
422: InvalidRequestError,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def retry_after_seconds(headers: httpx.Headers) -> float | None:
|
|
121
|
+
"""``Retry-After`` in seconds, or None when the server did not say.
|
|
122
|
+
|
|
123
|
+
The header is defined as either a number of seconds or an HTTP date, and both
|
|
124
|
+
appear in the wild. A date in the past yields 0 rather than a negative wait.
|
|
125
|
+
"""
|
|
126
|
+
raw = headers.get("retry-after")
|
|
127
|
+
if not raw:
|
|
128
|
+
return None
|
|
129
|
+
try:
|
|
130
|
+
return max(0.0, float(raw))
|
|
131
|
+
except ValueError:
|
|
132
|
+
pass
|
|
133
|
+
from email.utils import parsedate_to_datetime
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
when = parsedate_to_datetime(raw)
|
|
137
|
+
except (TypeError, ValueError):
|
|
138
|
+
return None
|
|
139
|
+
import datetime as _dt
|
|
140
|
+
|
|
141
|
+
now = _dt.datetime.now(tz=when.tzinfo or _dt.timezone.utc)
|
|
142
|
+
return max(0.0, (when - now).total_seconds())
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def error_from_response(response: httpx.Response) -> APIError:
|
|
146
|
+
"""Build the right exception from a response the server refused with.
|
|
147
|
+
|
|
148
|
+
The body is not trusted to be well-formed. An error can come from a proxy, a
|
|
149
|
+
load balancer, or a crash that never reached the application, and those answer
|
|
150
|
+
with HTML or with nothing. Status is always there; everything else is a best
|
|
151
|
+
effort.
|
|
152
|
+
"""
|
|
153
|
+
parsed: dict[str, Any] = {}
|
|
154
|
+
try:
|
|
155
|
+
body = response.json()
|
|
156
|
+
if isinstance(body, dict) and isinstance(body.get("error"), dict):
|
|
157
|
+
parsed = body["error"]
|
|
158
|
+
except Exception:
|
|
159
|
+
pass
|
|
160
|
+
|
|
161
|
+
status = response.status_code
|
|
162
|
+
kw: dict[str, Any] = {
|
|
163
|
+
"status": status,
|
|
164
|
+
"type": parsed.get("type") or ("api_error" if status >= 500 else "invalid_request_error"),
|
|
165
|
+
"code": parsed.get("code") or f"http_{status}",
|
|
166
|
+
"message": parsed.get("message") or f"Galileo returned {status}.",
|
|
167
|
+
"request_id": parsed.get("request_id") or response.headers.get("x-request-id"),
|
|
168
|
+
}
|
|
169
|
+
if status == 429:
|
|
170
|
+
return RateLimitError(retry_after=retry_after_seconds(response.headers), **kw)
|
|
171
|
+
return _BY_STATUS.get(status, ServerError)(**kw)
|