inference-tracker 0.9.4__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.
@@ -0,0 +1,306 @@
1
+ """Sees the answers an HTTP client gets, without changing them: for apps that call a provider over plain HTTP.
2
+
3
+ _http.watch(session, watcher) # an httpx.Client, httpx.AsyncClient or requests.Session
4
+
5
+ The watcher's hooks are added to the session itself (httpx's event_hooks, requests' hooks), so the app keeps
6
+ its own session object, of its own type, and every request made with it is seen: including those made by
7
+ code the app doesn't own that uses the same session. A request to a host the watcher doesn't accept is left
8
+ alone: nothing is read, timed or kept.
9
+
10
+ The body of an answer is read only when the watcher asks for it (wants_body), the way httpx and requests let
11
+ a hook read it: what the app reads afterwards is the same bytes. An error while reading is the call's own
12
+ (the connection broke) and reaches the app as it would have; an error in the watcher is logged, never raised.
13
+
14
+ A request that gets no answer at all (a timeout, a refused connection, the app cancelling it) raises in the
15
+ session's send(), which no hook sees: send() is wrapped on the session object itself, so the watcher's
16
+ failed() hears of it, and the error is raised as it was.
17
+
18
+ Without an active client (init() not called, or without a key) the hooks return at once: nothing is read.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import contextvars
24
+ import inspect
25
+ import json
26
+ import logging
27
+ import threading
28
+ import time
29
+ import weakref
30
+ from collections.abc import Mapping
31
+ from typing import Any, Protocol
32
+ from urllib.parse import parse_qs, urlsplit
33
+
34
+ from . import _bypass, _client
35
+ from ._record import error_name
36
+
37
+ logger = logging.getLogger("inference_tracker")
38
+
39
+
40
+ class Exchange:
41
+ """One request and the answer to it, as a hook sees them. For a request that got no answer (see failed()),
42
+ `response` is None: status 0, no headers, and `error` the exception."""
43
+
44
+ def __init__(
45
+ self,
46
+ request: Any,
47
+ response: Any,
48
+ url: str,
49
+ started: tuple[float, float],
50
+ elapsed: float,
51
+ error: BaseException | None = None,
52
+ ):
53
+ parts = urlsplit(url)
54
+ self.method = str(request.method).upper()
55
+ self.host = (parts.hostname or "").lower()
56
+ self.path = parts.path
57
+ self.query = parse_qs(parts.query)
58
+ self.request_headers: Mapping[str, str] = request.headers # case-insensitive in httpx and requests
59
+ self.status: int = response.status_code if response is not None else 0
60
+ self.headers: Mapping[str, str] = response.headers if response is not None else {}
61
+ self.started_at, self.clock = started # unix seconds and time.monotonic() when the request was sent
62
+ self.duration_s = round(elapsed, 3) # until the answer's headers came (or the error)
63
+ self.body: Any = None # the answer's JSON, when the watcher asked for it
64
+ self.error = error # why there is no answer
65
+ self._request = request
66
+
67
+ @property
68
+ def ok(self) -> bool:
69
+ return 200 <= self.status < 300
70
+
71
+ def request_json(self) -> Any:
72
+ """The request's JSON body, None when it has none (or isn't at hand, like a streamed upload)."""
73
+ try:
74
+ content = getattr(self._request, "content", None) # httpx
75
+ if content is None:
76
+ content = getattr(self._request, "body", None) # requests
77
+ return json.loads(content) if isinstance(content, (bytes, str)) and content else None
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ class Watcher(Protocol):
83
+ name: str # one watcher of each name per session: watching twice adds nothing
84
+
85
+ def accepts(self, host: str) -> bool: ...
86
+
87
+ def wants_body(self, exchange: Exchange) -> bool: ...
88
+
89
+ def seen(self, exchange: Exchange) -> None: ...
90
+
91
+ def failed(self, exchange: Exchange) -> None: ... # the request raised: exchange.error, no answer
92
+
93
+
94
+ def watch(session: Any, watcher: Watcher) -> bool:
95
+ """Adds the watcher's hooks to the session. False when it isn't a session this knows how to watch."""
96
+ try:
97
+ if isinstance(getattr(session, "event_hooks", None), Mapping):
98
+ watched = _watch_httpx(session, watcher)
99
+ elif isinstance(getattr(session, "hooks", None), dict) and hasattr(session, "mount"):
100
+ watched = _watch_requests(session, watcher)
101
+ else:
102
+ return False
103
+ _watch_failures(session, watcher)
104
+ return watched
105
+ except Exception:
106
+ logger.exception("inference_tracker: could not watch an HTTP client")
107
+ return False
108
+
109
+
110
+ _FAILURE_WATCHERS = "_inference_tracker_failure_watchers"
111
+ # Inside a watched send(): requests sends each redirect with send() again, and only the outer one reports.
112
+ _sending: contextvars.ContextVar[bool] = contextvars.ContextVar("inference_tracker_sending", default=False)
113
+
114
+
115
+ def _watch_failures(session: Any, watcher: Watcher) -> None:
116
+ """Wraps the session's send() (once, for every watcher of the session) to see requests that raise."""
117
+ watchers: list[Watcher] | None = getattr(session, _FAILURE_WATCHERS, None)
118
+ if watchers is not None:
119
+ if all(w.name != watcher.name for w in watchers):
120
+ watchers.append(watcher)
121
+ return
122
+ watchers = [watcher]
123
+ send = session.send
124
+ is_async = inspect.iscoroutinefunction(send)
125
+
126
+ def failed(request: Any, started: tuple[float, float], error: BaseException) -> None:
127
+ try:
128
+ if not _client.active() or _bypass.on():
129
+ return
130
+ url = str(request.url)
131
+ host = (urlsplit(url).hostname or "").lower()
132
+ for w in list(watchers):
133
+ if w.accepts(host):
134
+ ex = Exchange(request, None, url, started, time.monotonic() - started[1], error)
135
+ try:
136
+ w.failed(ex)
137
+ except Exception:
138
+ logger.exception("inference_tracker: tracking a failed HTTP call failed")
139
+ except Exception:
140
+ logger.exception("inference_tracker: could not read a failed HTTP request")
141
+
142
+ if is_async:
143
+
144
+ async def send_async(request: Any, *args: Any, **kwargs: Any) -> Any:
145
+ started = (time.time(), time.monotonic())
146
+ token = _sending.set(True)
147
+ try:
148
+ return await send(request, *args, **kwargs)
149
+ except BaseException as e:
150
+ if token.old_value is not True:
151
+ failed(request, started, e)
152
+ raise
153
+ finally:
154
+ _sending.reset(token)
155
+
156
+ session.send = send_async
157
+ else:
158
+
159
+ def send_sync(request: Any, *args: Any, **kwargs: Any) -> Any:
160
+ started = (time.time(), time.monotonic())
161
+ token = _sending.set(True)
162
+ try:
163
+ return send(request, *args, **kwargs)
164
+ except BaseException as e:
165
+ if token.old_value is not True:
166
+ failed(request, started, e)
167
+ raise
168
+ finally:
169
+ _sending.reset(token)
170
+
171
+ session.send = send_sync
172
+ setattr(session, _FAILURE_WATCHERS, watchers)
173
+
174
+
175
+ def error_type(ex: Exchange) -> str | None:
176
+ """A failed request's error type: the exception's class name. None for an answered one."""
177
+ return error_name(ex.error) if ex.error is not None else None
178
+
179
+
180
+ # Which watched session reports a request, per watcher: the first one it goes through. A session can send through
181
+ # a transport with a session of its own inside (fal_client's retries on a backup domain that way), and the
182
+ # request then passes both; the inner one stays quiet, or a call would be recorded twice.
183
+ _owners: weakref.WeakKeyDictionary[Any, dict[str, int]] = weakref.WeakKeyDictionary()
184
+ _owners_lock = threading.Lock()
185
+
186
+
187
+ def _claim(request: Any, name: str, owner: int) -> bool:
188
+ """Whether this session (owner) reports the request for the watcher of that name: True for the first."""
189
+ with _owners_lock:
190
+ owners = _owners.setdefault(request, {})
191
+ return owners.setdefault(name, owner) == owner
192
+
193
+
194
+ def _watch_httpx(session: Any, watcher: Watcher) -> bool:
195
+ hooks = session.event_hooks
196
+ if any(getattr(h, "_inference_tracker", None) == watcher.name for h in hooks.get("response", [])):
197
+ return True
198
+ is_async = hasattr(session, "aclose") # httpx.AsyncClient
199
+ sent: weakref.WeakKeyDictionary[Any, tuple[float, float]] = weakref.WeakKeyDictionary()
200
+ lock = threading.Lock()
201
+
202
+ def on_request(request: Any) -> None:
203
+ try:
204
+ if _client.active() and not _bypass.on() and watcher.accepts((request.url.host or "").lower()):
205
+ if not _claim(request, watcher.name, id(sent)):
206
+ return
207
+ with lock:
208
+ sent[request] = (time.time(), time.monotonic())
209
+ except Exception:
210
+ logger.exception("inference_tracker: could not time an HTTP request")
211
+
212
+ def exchange(response: Any) -> tuple[Exchange | None, bool]:
213
+ """The exchange, and whether the watcher wants the answer's body."""
214
+ try:
215
+ request = response.request
216
+ if not _client.active() or _bypass.on() or not watcher.accepts((request.url.host or "").lower()):
217
+ return None, False
218
+ with lock:
219
+ started = sent.pop(request, None)
220
+ if started is None and not _claim(request, watcher.name, id(sent)):
221
+ return None, False # reported by the session this one sent it through
222
+ now = time.monotonic()
223
+ started = started or (time.time(), now)
224
+ ex = Exchange(request, response, str(request.url), started, now - started[1])
225
+ return ex, watcher.wants_body(ex)
226
+ except Exception:
227
+ logger.exception("inference_tracker: could not read an HTTP answer")
228
+ return None, False
229
+
230
+ def on_response(response: Any) -> None:
231
+ ex, wanted = exchange(response)
232
+ if ex is not None:
233
+ if wanted:
234
+ response.read()
235
+ ex.body = _json(response.content)
236
+ _seen(watcher, ex)
237
+
238
+ async def on_request_async(request: Any) -> None:
239
+ on_request(request)
240
+
241
+ async def on_response_async(response: Any) -> None:
242
+ ex, wanted = exchange(response)
243
+ if ex is not None:
244
+ if wanted:
245
+ await response.aread()
246
+ ex.body = _json(response.content)
247
+ _seen(watcher, ex)
248
+
249
+ request_hook, response_hook = (on_request_async, on_response_async) if is_async else (on_request, on_response)
250
+ response_hook._inference_tracker = watcher.name # type: ignore[attr-defined]
251
+ session.event_hooks = {
252
+ **hooks,
253
+ "request": [*hooks.get("request", []), request_hook],
254
+ "response": [*hooks.get("response", []), response_hook],
255
+ }
256
+ return True
257
+
258
+
259
+ def _watch_requests(session: Any, watcher: Watcher) -> bool:
260
+ hooks = session.hooks.setdefault("response", [])
261
+ if not isinstance(hooks, list): # requests allows a single callable here
262
+ hooks = session.hooks["response"] = [hooks]
263
+ if any(getattr(h, "_inference_tracker", None) == watcher.name for h in hooks):
264
+ return True
265
+
266
+ def on_response(response: Any, *args: Any, **kwargs: Any) -> None:
267
+ try:
268
+ request = response.request
269
+ if not _client.active() or _bypass.on() or not watcher.accepts((urlsplit(request.url).hostname or "").lower()):
270
+ return None
271
+ elapsed = response.elapsed.total_seconds() # requests times until the headers came
272
+ ex = Exchange(request, response, request.url, (time.time() - elapsed, time.monotonic() - elapsed), elapsed)
273
+ wanted = watcher.wants_body(ex)
274
+ except Exception:
275
+ logger.exception("inference_tracker: could not read an HTTP answer")
276
+ return None
277
+ if wanted:
278
+ ex.body = _json(response.content)
279
+ _seen(watcher, ex)
280
+ return None # a hook that returns something replaces the response
281
+
282
+ on_response._inference_tracker = watcher.name # type: ignore[attr-defined]
283
+ hooks.append(on_response)
284
+ return True
285
+
286
+
287
+ def _seen(watcher: Watcher, ex: Exchange) -> None:
288
+ try:
289
+ watcher.seen(ex)
290
+ except Exception:
291
+ logger.exception("inference_tracker: tracking an HTTP call failed")
292
+
293
+
294
+ def _json(content: Any) -> Any:
295
+ try:
296
+ return json.loads(content) if content else None
297
+ except Exception:
298
+ return None
299
+
300
+
301
+ def header_number(headers: Mapping[str, str], name: str) -> float | None:
302
+ try:
303
+ value = headers.get(name)
304
+ return float(value) if value is not None else None
305
+ except (TypeError, ValueError):
306
+ return None
@@ -0,0 +1,71 @@
1
+ """A stand-in for an SDK client that intercepts only the methods that make inference calls.
2
+
3
+ client.chat.completions.create(...) path ("chat", "completions", "create")
4
+
5
+ Every other attribute is the client's own, unchanged. The wrappers (openai.py, google.py) say which paths
6
+ to intercept and what to do around them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import inspect
12
+ from collections.abc import Callable
13
+ from typing import Any
14
+
15
+ from ._bypass import bypass
16
+
17
+ Path = tuple[str, ...]
18
+ # Given the path, the original method and whether it is async, returns the method to use instead.
19
+ Wrap = Callable[[Path, Callable[..., Any], bool], Callable[..., Any]]
20
+
21
+
22
+ class Proxy:
23
+ def __init__(self, target: Any, paths: frozenset[Path], wrap: Wrap, path: Path = ()):
24
+ object.__setattr__(self, "_target", target)
25
+ object.__setattr__(self, "_paths", paths)
26
+ object.__setattr__(self, "_wrap", wrap)
27
+ object.__setattr__(self, "_path", path)
28
+
29
+ def __getattr__(self, name: str) -> Any:
30
+ with bypass(): # the client's own attribute, not the one attached at init(): recorded once, here
31
+ value = getattr(self._target, name)
32
+ path = self._path + (name,)
33
+ if path in self._paths and callable(value):
34
+ return self._wrap(path, value, _is_async(value))
35
+ if any(p[: len(path)] == path for p in self._paths):
36
+ return Proxy(value, self._paths, self._wrap, path)
37
+ return value
38
+
39
+ def __setattr__(self, name: str, value: Any) -> None:
40
+ setattr(self._target, name, value)
41
+
42
+ def __repr__(self) -> str:
43
+ return f"<tracked {self._target!r}>"
44
+
45
+
46
+ def _is_async(method: Any) -> bool:
47
+ """Whether calling the method gives a coroutine. A decorator can hide it (openai's AsyncCompletions.create
48
+ is wrapped in a plain function that checks its arguments), so the function it wraps is looked at too."""
49
+ try:
50
+ return inspect.iscoroutinefunction(method) or inspect.iscoroutinefunction(inspect.unwrap(method))
51
+ except Exception:
52
+ return False
53
+
54
+
55
+ def get(obj: Any, *names: str) -> Any:
56
+ """obj.a.b or obj["a"]["b"], None when any step is missing. SDK objects and plain dicts alike."""
57
+ for name in names:
58
+ if obj is None:
59
+ return None
60
+ obj = obj.get(name) if isinstance(obj, dict) else getattr(obj, name, None)
61
+ return obj
62
+
63
+
64
+ def number(value: Any) -> float | None:
65
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None
66
+
67
+
68
+ def put(units: dict[str, float], name: str, value: Any) -> None:
69
+ n = number(value)
70
+ if n is not None:
71
+ units[name] = n
@@ -0,0 +1,158 @@
1
+ """One record per inference call: who it was for, what was called, and what it used.
2
+
3
+ Never holds prompts, images, URLs or outputs. Cost is not here either: it comes from
4
+ the provider's bill, matched by request_id or split by the usage in `units`.
5
+
6
+ A call can be recorded in two parts when its result arrives somewhere else (fal's
7
+ queue with a webhook, RunPod /run, Veo's long-running operations): a "start" record
8
+ when it is sent and a "finish" record when the result comes back. The server joins
9
+ them on provider + request_id. A call seen from start to end in one place is one
10
+ "call" record.
11
+
12
+ A call made by another call (a step of a fal workflow, a model called by one of our fal
13
+ apps) names that call as its parent the same way: parent_provider + parent_request_id.
14
+
15
+ On the wire, fields that OpenTelemetry's GenAI conventions name use those names.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import json
22
+ import math
23
+ import re
24
+ import time
25
+ import uuid
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Literal
28
+
29
+ from . import _code
30
+ from ._context import current as _current_context
31
+
32
+ Phase = Literal["call", "start", "finish"]
33
+ # "cancelled": the app stopped waiting (cancelled, or timed out waiting) before the answer came, on a call
34
+ # recorded as one "call" record. The provider may still have run it, and billed it.
35
+ Status = Literal["ok", "error", "cancelled"]
36
+
37
+ # What an error type or a provider's code looks like. Anything else (a sentence, a message that could quote
38
+ # the input) is not copied onto a record.
39
+ _CODE = re.compile(r"^[A-Za-z0-9_.:-]{1,64}$")
40
+
41
+
42
+ @dataclass
43
+ class Record:
44
+ provider: str # "fal", "gcp.vertex_ai", "openai", "azure.ai.openai", "aws.bedrock"
45
+ model: str | None # model or endpoint, e.g. "fal-ai/kling-video/v2.6/pro/motion-control"; None only on a
46
+ # "finish" record made where the model isn't known (a webhook): the start record has it
47
+ phase: Phase = "call"
48
+ request_id: str | None = None # the provider's id for this call: how the bill is matched
49
+ status: Status | None = None # None on a "start" record
50
+ error_type: str | None = None # the exception's class name or the provider's error code, never a message
51
+ started_at: float | None = None # unix seconds
52
+ duration_s: float | None = None
53
+ # Usage as the provider reports it: input_tokens, output_tokens, cached_input_tokens, cache_write_input_tokens,
54
+ # images, video_seconds, audio_seconds... Numbers only.
55
+ units: dict[str, float] = field(default_factory=dict)
56
+ # Settings that change the price (resolution, requested duration, audio on/off), copied
57
+ # by name by the wrappers. Never the call's whole input: that is how prompts stay out.
58
+ settings: dict[str, Any] = field(default_factory=dict)
59
+ # Retries the app marks itself: the same call_id on every attempt, attempt 1, 2, 3...; None when not marked.
60
+ call_id: str | None = None
61
+ attempt: int | None = None
62
+ # Filled from the current context when the record is made.
63
+ user_id: str | None = None
64
+ task_id: str | None = None
65
+ # The call that made this one, as its provider knows it (e.g. "fal" and fal's request id).
66
+ parent_provider: str | None = None
67
+ parent_request_id: str | None = None
68
+ # Which call in the app's code made it ("prompt-suggestions"), from the current context.
69
+ call_name: str | None = None
70
+ # Which of the app's functions made the call, nearest first (see _code). Not on a "finish" record: its
71
+ # "start" has it. How the product tells calls apart; their names are given there.
72
+ code: list[str] | None = None
73
+ id: str = field(default_factory=lambda: uuid.uuid4().hex) # lets the server drop duplicates
74
+ recorded_at: float = field(default_factory=time.time)
75
+
76
+ @classmethod
77
+ def new(cls, provider: str, model: str, **fields) -> Record:
78
+ ctx = _current_context()
79
+ fields.setdefault("user_id", ctx.user_id)
80
+ fields.setdefault("task_id", ctx.task_id)
81
+ fields.setdefault("parent_provider", ctx.parent_provider)
82
+ fields.setdefault("parent_request_id", ctx.parent_request_id)
83
+ fields.setdefault("call_name", ctx.call_name)
84
+ if "code" not in fields and fields.get("phase", "call") != "finish":
85
+ fields["code"] = _code.functions() or None
86
+ return cls(provider=provider, model=model, **fields)
87
+
88
+ def to_wire(self) -> dict:
89
+ wire = {
90
+ "id": self.id,
91
+ "phase": self.phase,
92
+ "recorded_at": self.recorded_at,
93
+ "gen_ai.provider.name": self.provider,
94
+ "gen_ai.request.model": self.model,
95
+ "gen_ai.response.id": self.request_id,
96
+ "status": self.status,
97
+ "error.type": _error_type(self.error_type),
98
+ "started_at": self.started_at,
99
+ "duration_s": self.duration_s,
100
+ "units": _numbers(self.units),
101
+ "settings": _settings(self.settings),
102
+ "call_id": self.call_id,
103
+ "attempt": self.attempt,
104
+ "user_id": self.user_id,
105
+ "task_id": self.task_id,
106
+ "parent_provider": self.parent_provider,
107
+ "parent_request_id": self.parent_request_id,
108
+ "call_name": self.call_name,
109
+ "code.functions": [str(f)[:300] for f in self.code[: _code.DEPTH]] if self.code else None,
110
+ }
111
+ return {k: v for k, v in wire.items() if v is not None and v != {}}
112
+
113
+
114
+ def _numbers(units: dict) -> dict[str, float]:
115
+ return {
116
+ str(k): v
117
+ for k, v in units.items()
118
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
119
+ }
120
+
121
+
122
+ def _settings(settings: dict) -> dict[str, Any]:
123
+ """Kept as given. Only a value that can't be sent as JSON is left out."""
124
+ out: dict[str, Any] = {}
125
+ for k, v in settings.items():
126
+ try:
127
+ json.dumps(v, allow_nan=False)
128
+ except (TypeError, ValueError):
129
+ continue
130
+ out[str(k)] = v
131
+ return out
132
+
133
+
134
+ def _error_type(value: str | None) -> str | None:
135
+ """A last check that error_type is a code, whatever a wrapper put there."""
136
+ if value is None:
137
+ return None
138
+ return code(value) or "error"
139
+
140
+
141
+ def error_name(error: BaseException) -> str:
142
+ """What goes in error_type for an exception: its class name. The message can quote the input."""
143
+ return type(error).__name__
144
+
145
+
146
+ def code(value: object) -> str | None:
147
+ """`value` when it looks like a code ("content_policy_violation", "INVALID_ARGUMENT", "429"), else None:
148
+ a provider's free text (a reason, a message) can quote the input, so it never goes on a record."""
149
+ if isinstance(value, int) and not isinstance(value, bool):
150
+ value = str(value)
151
+ return value if isinstance(value, str) and _CODE.match(value) else None
152
+
153
+
154
+ def cancelled(error: BaseException | None) -> bool:
155
+ """Whether an error only says the app stopped waiting: the task was cancelled, or a timeout around the wait
156
+ ran out (asyncio's, or a client's that is a TimeoutError, like fal_client's). The provider may still be
157
+ running the call, and billing it, so this isn't the call failing."""
158
+ return isinstance(error, (asyncio.CancelledError, TimeoutError, asyncio.TimeoutError))
@@ -0,0 +1,51 @@
1
+ """One HTTP POST of a batch to the ingest endpoint, and what to do about the answer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import json
7
+ import urllib.error
8
+ import urllib.request
9
+ from dataclasses import dataclass
10
+ from typing import Literal
11
+
12
+ Outcome = Literal["sent", "retry", "rejected"]
13
+
14
+
15
+ @dataclass
16
+ class Result:
17
+ outcome: Outcome
18
+ status: int | None = None # HTTP status, None when the request never got an answer
19
+ retry_after: float | None = None # seconds, from a 429's Retry-After header
20
+
21
+
22
+ def post(url: str, key: str, body: dict, timeout: float) -> Result:
23
+ data = gzip.compress(json.dumps(body, allow_nan=False, separators=(",", ":")).encode())
24
+ request = urllib.request.Request(
25
+ url,
26
+ data=data,
27
+ method="POST",
28
+ headers={
29
+ "Authorization": f"Bearer {key}",
30
+ "Content-Type": "application/json",
31
+ "Content-Encoding": "gzip",
32
+ },
33
+ )
34
+ try:
35
+ with urllib.request.urlopen(request, timeout=timeout) as response:
36
+ return Result("sent", response.status)
37
+ except urllib.error.HTTPError as e:
38
+ # 429 and 5xx: the server is busy or broken, the same batch may go through later.
39
+ if e.code == 429 or e.code >= 500:
40
+ return Result("retry", e.code, _seconds(e.headers.get("Retry-After")))
41
+ # Any other 4xx (bad key, rejected body): sending it again won't change the answer.
42
+ return Result("rejected", e.code)
43
+ except (urllib.error.URLError, OSError, TimeoutError):
44
+ return Result("retry")
45
+
46
+
47
+ def _seconds(value: str | None) -> float | None:
48
+ try:
49
+ return max(0.0, float(value)) if value is not None else None
50
+ except ValueError:
51
+ return None
@@ -0,0 +1 @@
1
+ __version__ = "0.9.4"