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.
- inference_tracker/__init__.py +28 -0
- inference_tracker/_attach.py +321 -0
- inference_tracker/_bypass.py +53 -0
- inference_tracker/_client.py +371 -0
- inference_tracker/_code.py +64 -0
- inference_tracker/_context.py +98 -0
- inference_tracker/_http.py +306 -0
- inference_tracker/_proxy.py +71 -0
- inference_tracker/_record.py +158 -0
- inference_tracker/_transport.py +51 -0
- inference_tracker/_version.py +1 -0
- inference_tracker/eachlabs.py +262 -0
- inference_tracker/fal.py +842 -0
- inference_tracker/google.py +388 -0
- inference_tracker/litellm.py +471 -0
- inference_tracker/modal.py +380 -0
- inference_tracker/openai.py +761 -0
- inference_tracker/pruna.py +258 -0
- inference_tracker-0.9.4.dist-info/METADATA +327 -0
- inference_tracker-0.9.4.dist-info/RECORD +22 -0
- inference_tracker-0.9.4.dist-info/WHEEL +4 -0
- inference_tracker-0.9.4.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Tracks calls to Pruna's API (https://api.pruna.ai), made over plain HTTP or with Pruna's Python client
|
|
2
|
+
(the pruna_client package).
|
|
3
|
+
|
|
4
|
+
import inference_tracker
|
|
5
|
+
|
|
6
|
+
http = inference_tracker.pruna.track_http(httpx.AsyncClient()) # or httpx.Client, requests.Session
|
|
7
|
+
pruna = inference_tracker.pruna.track_http(PrunaClient()) # pruna_client: both of its sessions
|
|
8
|
+
|
|
9
|
+
How Pruna's API works: a prediction is sent with POST /v1/predictions, the model in the Model header and the
|
|
10
|
+
input in {"input": {...}}. Pruna answers with the prediction's id and a status URL (get_url,
|
|
11
|
+
/v1/predictions/status/<id>), which the app polls until it says succeeded (with a generation_url to download
|
|
12
|
+
the result from), failed or canceled. With the Try-Sync header, Pruna may instead wait (up to a minute) and
|
|
13
|
+
answer with the finished result, which carries no id. Pruna has no webhooks.
|
|
14
|
+
|
|
15
|
+
What is recorded:
|
|
16
|
+
- a submit answered with an id: a "start" record with the id as request id, and the status answer that says
|
|
17
|
+
the prediction ended: the "finish", ok, or "failed" / "cancelled" (status "error"). The status may be polled
|
|
18
|
+
with another watched session than the one that submitted.
|
|
19
|
+
- a submit answered with the finished result (Try-Sync): one "call" record, without a request id: Pruna gives
|
|
20
|
+
none.
|
|
21
|
+
- a submit Pruna refused (an error answer): one "call" record with Pruna's code (VALIDATION_ERROR,
|
|
22
|
+
RATE_LIMIT_EXCEEDED...) or "http_<status>", and the request id the error carries (req_...).
|
|
23
|
+
- a submit that got no answer (a timeout, a broken connection): one "call" record with the exception's class
|
|
24
|
+
name, no request id ("cancelled" when the app cancelled it). A poll without an answer, or with an error
|
|
25
|
+
answer, changes nothing: the prediction may still be running.
|
|
26
|
+
Downloads (/v1/predictions/delivery/...), uploads (/v1/files) and other hosts pass through unseen. The call
|
|
27
|
+
itself is never changed, and tracking never raises: a problem in it is logged and the call goes on.
|
|
28
|
+
|
|
29
|
+
Usage: Pruna's answers report none (no seconds of video, no cost, no credits), and its API has no usage or
|
|
30
|
+
billing endpoint. What the price depends on is in the request: settings copied from the input by name (duration,
|
|
31
|
+
resolution, mode, draft...), and the number of reference images, videos and audio files sent (input_images,
|
|
32
|
+
input_videos, input_audios: counts, never the URLs). Never the prompt, nor any media URL. Pruna bills some models
|
|
33
|
+
by the finished video's length, which only its bill (its dashboard) shows.
|
|
34
|
+
|
|
35
|
+
The model is Pruna's name for it, from the Model header ("p-video-2-pro-reference"). The parent is taken from the
|
|
36
|
+
context, as for every record.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import logging
|
|
42
|
+
import re
|
|
43
|
+
import threading
|
|
44
|
+
import time
|
|
45
|
+
from collections import OrderedDict
|
|
46
|
+
from collections.abc import Iterable, Mapping
|
|
47
|
+
from typing import Any
|
|
48
|
+
|
|
49
|
+
from . import _attach, _client, _http
|
|
50
|
+
from ._proxy import get
|
|
51
|
+
from ._record import Record, cancelled, code
|
|
52
|
+
|
|
53
|
+
logger = logging.getLogger("inference_tracker")
|
|
54
|
+
|
|
55
|
+
PROVIDER = "pruna"
|
|
56
|
+
HOSTS = frozenset({"api.pruna.ai"})
|
|
57
|
+
MODEL_HEADER = "Model"
|
|
58
|
+
# Input fields copied onto the record because they change the price (or say how long the video is).
|
|
59
|
+
SETTINGS = (
|
|
60
|
+
"duration",
|
|
61
|
+
"resolution",
|
|
62
|
+
"mode",
|
|
63
|
+
"draft",
|
|
64
|
+
"fps",
|
|
65
|
+
"aspect_ratio",
|
|
66
|
+
"num_frames",
|
|
67
|
+
"num_outputs",
|
|
68
|
+
"width",
|
|
69
|
+
"height",
|
|
70
|
+
"size",
|
|
71
|
+
"image_size",
|
|
72
|
+
"go_fast",
|
|
73
|
+
"turbo",
|
|
74
|
+
)
|
|
75
|
+
# Input fields holding media URLs, counted (never copied): reference images, videos and audio change the price.
|
|
76
|
+
MEDIA = {
|
|
77
|
+
"input_images": ("image", "images", "first_frame_image", "last_frame_image"),
|
|
78
|
+
"input_videos": ("video",),
|
|
79
|
+
"input_audios": ("audio",),
|
|
80
|
+
}
|
|
81
|
+
# Predictions submitted and not seen ended yet, by id, shared by every watched session. Beyond this many, the
|
|
82
|
+
# oldest is forgotten.
|
|
83
|
+
MAX_OPEN = 1000
|
|
84
|
+
_ENDED = {"succeeded": None, "failed": "failed", "canceled": "cancelled"}
|
|
85
|
+
|
|
86
|
+
_SUBMIT = re.compile(r"^/v\d+/predictions/?$")
|
|
87
|
+
_STATUS = re.compile(r"^/v\d+/predictions/status/(?P<id>[^/]+)/?$")
|
|
88
|
+
|
|
89
|
+
_open: OrderedDict[str, _Call] = OrderedDict()
|
|
90
|
+
_open_lock = threading.Lock()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def track_http(client: Any, *, settings: Iterable[str] = SETTINGS) -> Any:
|
|
94
|
+
"""Watches an httpx.Client, httpx.AsyncClient or requests.Session for calls to Pruna's API, and returns the
|
|
95
|
+
same client. A pruna_client.PrunaClient can be passed as it is: both of its httpx sessions (sync and async)
|
|
96
|
+
are watched. See the module docstring."""
|
|
97
|
+
watcher = _HttpWatcher(settings)
|
|
98
|
+
_attach.learn(watcher)
|
|
99
|
+
try:
|
|
100
|
+
if _http.watch(client, watcher):
|
|
101
|
+
return client
|
|
102
|
+
sessions = [getattr(client, name, None) for name in ("client", "_async_client")] # pruna_client's
|
|
103
|
+
watched = [s for s in sessions if s is not None and _http.watch(s, watcher)]
|
|
104
|
+
if not watched:
|
|
105
|
+
logger.warning("inference_tracker: can't watch a %s for Pruna calls", type(client).__name__)
|
|
106
|
+
except Exception:
|
|
107
|
+
logger.exception("inference_tracker: could not watch a client for Pruna calls")
|
|
108
|
+
return client
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# --- one call ----------------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class _Call:
|
|
115
|
+
"""The record of one prediction while this process follows it."""
|
|
116
|
+
|
|
117
|
+
def __init__(self, model: str | None, settings: dict[str, Any], units: dict[str, float], started: tuple):
|
|
118
|
+
started_at, self._clock = started
|
|
119
|
+
self.record = Record.new(PROVIDER, model, phase="start", started_at=started_at, settings=settings)
|
|
120
|
+
self.units = units
|
|
121
|
+
self.done = False
|
|
122
|
+
|
|
123
|
+
def submitted(self, request_id: str) -> None:
|
|
124
|
+
self.record.request_id = request_id
|
|
125
|
+
_client.record(self.record)
|
|
126
|
+
with _open_lock:
|
|
127
|
+
_open[request_id] = self
|
|
128
|
+
while len(_open) > MAX_OPEN:
|
|
129
|
+
_open.popitem(last=False)
|
|
130
|
+
|
|
131
|
+
def finish(self, error_type: str | None) -> None:
|
|
132
|
+
if self.done:
|
|
133
|
+
return
|
|
134
|
+
self.done = True
|
|
135
|
+
start = self.record
|
|
136
|
+
with _open_lock:
|
|
137
|
+
_open.pop(start.request_id, None)
|
|
138
|
+
_client.record(
|
|
139
|
+
Record.new(
|
|
140
|
+
PROVIDER,
|
|
141
|
+
start.model,
|
|
142
|
+
phase="finish",
|
|
143
|
+
request_id=start.request_id,
|
|
144
|
+
status="error" if error_type else "ok",
|
|
145
|
+
error_type=error_type,
|
|
146
|
+
duration_s=self._elapsed(),
|
|
147
|
+
units=dict(self.units),
|
|
148
|
+
user_id=start.user_id,
|
|
149
|
+
task_id=start.task_id,
|
|
150
|
+
parent_provider=start.parent_provider,
|
|
151
|
+
parent_request_id=start.parent_request_id,
|
|
152
|
+
call_name=start.call_name,
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def completed(self, request_id: str | None, error_type: str | None, stopped: bool = False) -> None:
|
|
157
|
+
"""The whole call seen here (a Try-Sync answer, a refused or unanswered submit): one "call" record."""
|
|
158
|
+
if self.done:
|
|
159
|
+
return
|
|
160
|
+
self.done = True
|
|
161
|
+
r = self.record
|
|
162
|
+
r.phase, r.request_id = "call", request_id
|
|
163
|
+
r.status, r.error_type = ("cancelled" if stopped else "error" if error_type else "ok"), error_type
|
|
164
|
+
r.duration_s, r.units = self._elapsed(), dict(self.units)
|
|
165
|
+
_client.record(r)
|
|
166
|
+
|
|
167
|
+
def _elapsed(self) -> float:
|
|
168
|
+
return round(time.monotonic() - self._clock, 3)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# --- over HTTP ---------------------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class _HttpWatcher:
|
|
175
|
+
name = "pruna"
|
|
176
|
+
|
|
177
|
+
def __init__(self, settings: Iterable[str]):
|
|
178
|
+
self.settings = tuple(settings)
|
|
179
|
+
|
|
180
|
+
def accepts(self, host: str) -> bool:
|
|
181
|
+
return host in HOSTS
|
|
182
|
+
|
|
183
|
+
def wants_body(self, ex: _http.Exchange) -> bool:
|
|
184
|
+
kind, request_id = _route(ex)
|
|
185
|
+
if kind == "submit":
|
|
186
|
+
return True # the id is in it, or the finished result, or Pruna's error code
|
|
187
|
+
return kind == "status" and ex.ok and _peek(request_id) is not None
|
|
188
|
+
|
|
189
|
+
def seen(self, ex: _http.Exchange) -> None:
|
|
190
|
+
kind, request_id = _route(ex)
|
|
191
|
+
if kind == "submit":
|
|
192
|
+
self._submitted(ex)
|
|
193
|
+
elif kind == "status" and ex.ok and isinstance(ex.body, Mapping):
|
|
194
|
+
call = _peek(request_id)
|
|
195
|
+
status = ex.body.get("status")
|
|
196
|
+
if call is not None and status in _ENDED:
|
|
197
|
+
call.finish(_ENDED[status])
|
|
198
|
+
|
|
199
|
+
def failed(self, ex: _http.Exchange) -> None:
|
|
200
|
+
kind, _ = _route(ex)
|
|
201
|
+
if kind == "submit" and (call := self._start(ex)) is not None:
|
|
202
|
+
call.completed(None, _http.error_type(ex), cancelled(ex.error))
|
|
203
|
+
|
|
204
|
+
def _start(self, ex: _http.Exchange) -> _Call | None:
|
|
205
|
+
try:
|
|
206
|
+
model = ex.request_headers.get(MODEL_HEADER)
|
|
207
|
+
body = ex.request_json()
|
|
208
|
+
data = body.get("input") if isinstance(body, Mapping) else None
|
|
209
|
+
data = data if isinstance(data, Mapping) else {}
|
|
210
|
+
settings = {k: data[k] for k in self.settings if data.get(k) is not None}
|
|
211
|
+
units = {name: n for name, keys in MEDIA.items() if (n := sum(_count(data.get(k)) for k in keys))}
|
|
212
|
+
model = model if isinstance(model, str) and model else None
|
|
213
|
+
return _Call(model, settings, units, (ex.started_at, ex.clock))
|
|
214
|
+
except Exception:
|
|
215
|
+
logger.exception("inference_tracker: could not start tracking a Pruna call")
|
|
216
|
+
return None
|
|
217
|
+
|
|
218
|
+
def _submitted(self, ex: _http.Exchange) -> None:
|
|
219
|
+
call = self._start(ex)
|
|
220
|
+
if call is None:
|
|
221
|
+
return
|
|
222
|
+
body = ex.body if isinstance(ex.body, Mapping) else {}
|
|
223
|
+
if not ex.ok:
|
|
224
|
+
request_id = body.get("request_id")
|
|
225
|
+
error_type = code(get(body, "error", "code")) or f"http_{ex.status}"
|
|
226
|
+
call.completed(request_id if isinstance(request_id, str) and request_id else None, error_type)
|
|
227
|
+
return
|
|
228
|
+
request_id = body.get("id")
|
|
229
|
+
request_id = request_id if isinstance(request_id, str) and request_id else None
|
|
230
|
+
status = body.get("status")
|
|
231
|
+
if status in _ENDED: # Try-Sync: the finished result (no id in it, as Pruna documents it)
|
|
232
|
+
call.completed(request_id, _ENDED[status])
|
|
233
|
+
elif request_id is not None:
|
|
234
|
+
call.submitted(request_id)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _route(ex: _http.Exchange) -> tuple[str | None, str | None]:
|
|
238
|
+
"""What a request to Pruna was: ("submit" | "status" | None, the prediction id in the URL)."""
|
|
239
|
+
if ex.method == "POST" and _SUBMIT.match(ex.path):
|
|
240
|
+
return "submit", None
|
|
241
|
+
match = _STATUS.match(ex.path)
|
|
242
|
+
if ex.method == "GET" and match is not None:
|
|
243
|
+
return "status", match["id"]
|
|
244
|
+
return None, None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _peek(request_id: Any) -> _Call | None:
|
|
248
|
+
with _open_lock:
|
|
249
|
+
return _open.get(request_id)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _count(value: Any) -> int:
|
|
253
|
+
"""How many media a field holds: one URL, or a list of them."""
|
|
254
|
+
if isinstance(value, str):
|
|
255
|
+
return 1 if value else 0
|
|
256
|
+
if isinstance(value, (list, tuple)):
|
|
257
|
+
return sum(1 for v in value if v)
|
|
258
|
+
return 0
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: inference-tracker
|
|
3
|
+
Version: 0.9.4
|
|
4
|
+
Summary: Per-user inference cost for AI apps
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# inference-tracker
|
|
11
|
+
|
|
12
|
+
Per-user inference cost for AI apps.
|
|
13
|
+
|
|
14
|
+
A small Python library that records each inference call (each call to an AI model) where the app
|
|
15
|
+
makes it: who it was for, which provider and model, the provider's request id, and how long it
|
|
16
|
+
took. The provider's bill says how much was spent; the record says who it was for. Prompts, images
|
|
17
|
+
and other user content are never recorded.
|
|
18
|
+
|
|
19
|
+
Early work in progress. Python 3.10 or newer, no other packages needed.
|
|
20
|
+
|
|
21
|
+
## Setup
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
pip install "inference-tracker>=0.9.4,<1"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Then one line at startup, with the string you get when you make a key (the address, with the key in it):
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import inference_tracker
|
|
31
|
+
|
|
32
|
+
inference_tracker.init("https://<key>@<host>", environment="prod")
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
That's all: `init()` attaches to the SDKs the app uses (openai, google-genai, LiteLLM, fal_client, and
|
|
36
|
+
plain `httpx` and `requests` sessions to fal, eachlabs, Pruna, Modal and OpenAI), so every client is tracked,
|
|
37
|
+
wherever and whenever it's made. Nothing to wrap.
|
|
38
|
+
|
|
39
|
+
The key can only send records, so it may be written in the code of a private repo. Set
|
|
40
|
+
`INFERENCE_TRACKER_DSN` to replace the whole string without changing the code (a public repo sets it
|
|
41
|
+
there and calls `init()` with nothing). No other variable changes where records go. Without a string,
|
|
42
|
+
nothing is sent and every call below does nothing: no answer is read, no body parsed.
|
|
43
|
+
`INFERENCE_TRACKER_ENVIRONMENT` fills in the environment when it isn't passed. Pass `attach=False` to
|
|
44
|
+
wrap clients yourself instead (below).
|
|
45
|
+
|
|
46
|
+
The older form, `init(url=..., key=..., app=...)`, still works, with `INFERENCE_TRACKER_URL`,
|
|
47
|
+
`INFERENCE_TRACKER_KEY` and `INFERENCE_TRACKER_APP` winning over it as before.
|
|
48
|
+
|
|
49
|
+
`init()` can be called at startup or at the start of every request, from any number of threads at
|
|
50
|
+
once: called again with the same values, it returns the client already running and does nothing else.
|
|
51
|
+
So there is no need for a "started" flag of your own (a flag set before `init()` returns lets a
|
|
52
|
+
request that comes meanwhile run without a client).
|
|
53
|
+
|
|
54
|
+
Records are sent in the background every few seconds. Some hosts freeze the process as soon as the
|
|
55
|
+
response is sent (Cloud Functions, Lambda, Cloud Run by default). There, use
|
|
56
|
+
`init(..., background=False)` and `context(..., flush=True)`, which sends the records when the
|
|
57
|
+
block ends.
|
|
58
|
+
|
|
59
|
+
That flush runs in your request, so it is kept short:
|
|
60
|
+
|
|
61
|
+
- Only the outermost `context(flush=True)` block flushes; blocks inside it don't.
|
|
62
|
+
- It gives up after `flush_timeout` seconds (1 by default), and never waits on a busy ingest server
|
|
63
|
+
(a 429, a Retry-After, a retry): records that didn't go stay queued and go with the next flush.
|
|
64
|
+
- After a flush that didn't get everything through, flushes are skipped for `flush_pause` seconds
|
|
65
|
+
(60 by default), so a slow or down server costs one request a second, not every request.
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
inference_tracker.init(..., background=False, flush_timeout=1.0, flush_pause=60)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The background thread, and `inference_tracker.shutdown()` (run when the process exits), still retry
|
|
72
|
+
with growing waits.
|
|
73
|
+
|
|
74
|
+
Say who the work is for where it starts. Every tracked call inside the block gets that user and task:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
with inference_tracker.context(user_id=uid, task_id=task.id):
|
|
78
|
+
...
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
A call made by another call names that call as its parent, by provider and the provider's request
|
|
82
|
+
id, the way the bill knows it. The server finds the user and task by walking up the parents, so
|
|
83
|
+
code that only knows its parent doesn't need them:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
with inference_tracker.context(parent_provider="fal", parent_request_id=rid):
|
|
87
|
+
...
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Calls aren't named in the code. Each record carries the app's functions that made it, nearest first
|
|
91
|
+
(`code.functions`), which tells apart two places that use the same model; names are given in the
|
|
92
|
+
product. A name already set with `context(call_name="prompt-suggestions")` keeps working.
|
|
93
|
+
|
|
94
|
+
A result read later, somewhere else, keeps the name its call was made with.
|
|
95
|
+
|
|
96
|
+
## Wrapping clients yourself
|
|
97
|
+
|
|
98
|
+
`init()` already tracks the clients below. The `track()` wrappers in each section stay for code written
|
|
99
|
+
before 0.9.0 and for `init(..., attach=False)`; a wrapped client is still recorded once.
|
|
100
|
+
|
|
101
|
+
## fal
|
|
102
|
+
|
|
103
|
+
Without `init()`'s tracking, wrap the client once, then call it as before.
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
import fal_client
|
|
107
|
+
import inference_tracker
|
|
108
|
+
|
|
109
|
+
client = inference_tracker.fal.track(fal_client.AsyncClient(key=FAL_KEY))
|
|
110
|
+
|
|
111
|
+
handle = await client.submit("fal-ai/kling-video/v2.6/pro/motion-control", arguments=args)
|
|
112
|
+
result = await handle.get()
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Recorded: `submit`, `subscribe`, `run`, and getting or cancelling a result (`handle.get()`,
|
|
116
|
+
`handle.cancel()`, `client.result(...)`, `client.cancel(...)`). Everything else (`upload`,
|
|
117
|
+
`status`, `stream`...) passes through untouched. Tracking never raises an error and never changes
|
|
118
|
+
the call.
|
|
119
|
+
|
|
120
|
+
When fal sends the result to a webhook, record the finish in the webhook handler:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
inference_tracker.fal.webhook(request_json) # the body fal posts: request_id, status, payload
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Workflows
|
|
127
|
+
|
|
128
|
+
Submit a fal workflow with the envelope header, and its result comes back as `{output, nodes}`,
|
|
129
|
+
with the request id of each step. Each step is then recorded too, with the run as its parent:
|
|
130
|
+
from the webhook body, or from the result when it is fetched here (`get()`, `result()`,
|
|
131
|
+
`subscribe()`). The app reads its output from `output`.
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
handle = await client.submit(
|
|
135
|
+
"workflows/ACME-COMPUTE/prod-myapp-video",
|
|
136
|
+
arguments=args,
|
|
137
|
+
webhook_url=hook_url,
|
|
138
|
+
headers={inference_tracker.fal.WORKFLOW_ENVELOPE_HEADER: "true"},
|
|
139
|
+
)
|
|
140
|
+
...
|
|
141
|
+
inference_tracker.fal.webhook(request_json) # the run's finish, and one record per step
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
When a run fails, the step that failed is recorded with fal's error code. A step that fell back to
|
|
145
|
+
another model also gets a record for the model that failed.
|
|
146
|
+
|
|
147
|
+
### Our own fal apps
|
|
148
|
+
|
|
149
|
+
Our own fal apps make calls of their own. In the endpoint, `inside(self)` makes the request the app
|
|
150
|
+
is serving the parent of every tracked call in the block:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
@fal.endpoint("/")
|
|
154
|
+
async def generate(self, input: Input) -> Output:
|
|
155
|
+
with inference_tracker.fal.inside(self):
|
|
156
|
+
return await self._inference(input)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The request id comes from fal's `self.current_request`. Without one (the app runs outside fal), the
|
|
160
|
+
block does nothing.
|
|
161
|
+
|
|
162
|
+
### fal over HTTP
|
|
163
|
+
|
|
164
|
+
For calls made with plain HTTP instead of `fal_client` (or from a subclass of its clients):
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
http = inference_tracker.fal.track_http(httpx.Client()) # or httpx.AsyncClient, requests.Session,
|
|
168
|
+
# a fal_client.SyncClient (subclasses too)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
A submit to `queue.fal.run` is a "start", fetching the result a "finish", a call to `fal.run` one
|
|
172
|
+
record. A submit or `fal.run` call that gets no answer at all (a timeout, a refused connection) is
|
|
173
|
+
one record with the exception's class name and no request id: fal may have run it. Other addresses
|
|
174
|
+
pass through untouched. Use `track()` or `track_http()` on a client, not both.
|
|
175
|
+
|
|
176
|
+
## OpenAI and Azure (the `openai` package)
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
from openai import OpenAI
|
|
180
|
+
import inference_tracker
|
|
181
|
+
|
|
182
|
+
client = inference_tracker.openai.track(OpenAI(api_key=...))
|
|
183
|
+
response = client.responses.parse(model="gpt-5.4-mini", input=..., text_format=...)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Works the same for `AsyncOpenAI`, `AzureOpenAI`, and an `OpenAI` client pointed at Azure AI Foundry
|
|
187
|
+
(`base_url="https://<resource>.services.ai.azure.com/openai/v1/"`). Tracked: `responses.create` /
|
|
188
|
+
`parse`, `chat.completions.create` / `parse`, `images.generate` / `edit`. Each is one record with the
|
|
189
|
+
response id, the model the response names, and the tokens by kind (input, cached input, output,
|
|
190
|
+
reasoning) or images. Azure calls also note their resource name, which is how Azure's bill is split.
|
|
191
|
+
|
|
192
|
+
Also tracked: `embeddings.create`, `moderations.create`, streams (`stream=True`, recorded when the
|
|
193
|
+
stream ends, with the last chunk's usage; for chat completions pass
|
|
194
|
+
`stream_options={"include_usage": True}`, or `ModelSettings(include_usage=True)` in the Agents SDK,
|
|
195
|
+
else there is no usage), and copies made with `with_options`. An OpenAI client pointed at Vertex AI
|
|
196
|
+
(`base_url="https://aiplatform.googleapis.com/v1beta1/projects/<p>/locations/<l>/endpoints/openapi"`)
|
|
197
|
+
is recorded as Vertex, with its project and location. Works with the OpenAI Agents SDK: pass the
|
|
198
|
+
tracked `AsyncOpenAI` to `set_default_openai_client` or to a model.
|
|
199
|
+
|
|
200
|
+
Calls to OpenAI's API made without the `openai` package (`httpx.post("https://api.openai.com/v1/decisions",
|
|
201
|
+
...)`, or with `requests`) are recorded too, once `init()` has attached: one record per POST to an inference
|
|
202
|
+
endpoint, with the model, the usage the answer reports and the `x-request-id`. A streamed one is recorded
|
|
203
|
+
without usage, since its answer isn't read. With `attach=False`, watch the session yourself:
|
|
204
|
+
`inference_tracker.openai.track_http(httpx.Client())`.
|
|
205
|
+
|
|
206
|
+
## Google (the `google-genai` package)
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
from google import genai
|
|
210
|
+
import inference_tracker
|
|
211
|
+
|
|
212
|
+
client = inference_tracker.google.track(genai.Client(vertexai=True, project=..., location=...))
|
|
213
|
+
response = client.models.generate_content(model="gemini-3.1-flash-image", contents=..., config=...)
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Tracked, sync and `client.aio`: `models.generate_content`, `generate_images`, `edit_image` (one record
|
|
217
|
+
each, with tokens by kind: text and image, in and out, thinking, cached), and Veo's
|
|
218
|
+
`models.generate_videos`: a "start" when it is sent and a "finish" when `operations.get()` returns the
|
|
219
|
+
operation done, with the seconds of video made. Settings that change the price (resolution, length,
|
|
220
|
+
audio, image size, aspect ratio, thinking) and the Google Cloud project are noted.
|
|
221
|
+
|
|
222
|
+
Also `models.embed_content` (tokens in), and the `vertexai` package's embeddings:
|
|
223
|
+
`model = inference_tracker.google.track(TextEmbeddingModel.from_pretrained("text-embedding-005"))`.
|
|
224
|
+
|
|
225
|
+
## LiteLLM (AWS Bedrock, and every other provider it routes to)
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
inference_tracker.litellm.track() # once at startup, after any `litellm.callbacks = [...]`
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Every `litellm.completion` / `acompletion`, embedding, image and responses call is recorded, streamed or
|
|
232
|
+
not, including calls the OpenAI Agents SDK's `LitellmModel` makes (`Runner.run`, `Runner.run_sync`). An
|
|
233
|
+
async call is recorded before it returns; for a sync call, LiteLLM records it on its own thread a moment
|
|
234
|
+
later, and `flush()` waits for it, so it is in the flush of the block that made it. Bedrock records carry the model or
|
|
235
|
+
inference-profile id, the `x-amzn-requestid`, the region, and input, output, cache-read and cache-write
|
|
236
|
+
tokens. Don't also pass a client wrapped by `inference_tracker.openai.track` to LiteLLM (`client=`), or
|
|
237
|
+
the call is recorded twice.
|
|
238
|
+
|
|
239
|
+
## Modal
|
|
240
|
+
|
|
241
|
+
```python
|
|
242
|
+
generate = inference_tracker.modal.function("video-app", "generate")
|
|
243
|
+
generate.remote(args) # one record, timing only (Modal gives no call id here)
|
|
244
|
+
call = generate.spawn(args); call.get() # a "start" and a "finish", with the fc- call id
|
|
245
|
+
http = inference_tracker.modal.track_http(httpx.Client(), apps=["video-app"]) # web endpoints
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Inside a Modal function, `with inference_tracker.modal.inside():` makes the call the function is serving
|
|
249
|
+
the parent of every tracked call in the block, like `fal.inside(self)`.
|
|
250
|
+
|
|
251
|
+
## Pruna
|
|
252
|
+
|
|
253
|
+
For calls to Pruna's API (`api.pruna.ai`) over plain HTTP, or with Pruna's `pruna_client`:
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
http = inference_tracker.pruna.track_http(httpx.AsyncClient()) # or httpx.Client, requests.Session,
|
|
257
|
+
# a pruna_client.PrunaClient
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
A prediction sent to `POST /v1/predictions` is a "start" with Pruna's prediction id, and the status
|
|
261
|
+
answer that says it ended (`succeeded`, `failed`, `canceled`) is the "finish". With `Try-Sync`, a
|
|
262
|
+
prediction answered at once is one record, without an id (Pruna gives none). A refused one is one
|
|
263
|
+
record with Pruna's code (`VALIDATION_ERROR`...). The model is the `Model` header (`p-video`,
|
|
264
|
+
`p-video-2-pro-reference`...). Pruna reports no usage, so the record keeps what the price depends
|
|
265
|
+
on: the settings sent (duration, resolution, mode, draft, fps...) and how many reference images,
|
|
266
|
+
videos and audio files went with it (counts, never the URLs). Downloads and uploads aren't recorded.
|
|
267
|
+
|
|
268
|
+
## eachlabs
|
|
269
|
+
|
|
270
|
+
For calls to eachlabs' API (`api.eachlabs.ai`) over plain HTTP:
|
|
271
|
+
|
|
272
|
+
```python
|
|
273
|
+
http = inference_tracker.eachlabs.track_http(httpx.AsyncClient()) # or httpx.Client, requests.Session
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
A prediction created with `POST /v1/prediction` is a "start" with eachlabs' prediction id, and the poll
|
|
277
|
+
answer that says it ended (`success`, `error`, `cancelled`) is the "finish". A refused create is one
|
|
278
|
+
record with `http_<status>`. The model is the body's `model` (`p-video-upscale`...), with its `version`
|
|
279
|
+
in the settings. The finish keeps the prediction's cost as eachlabs reports it (`metrics.cost`, list
|
|
280
|
+
price with any rebate off) as `cost_usd`, and on metered models `billed_seconds` and `output_gb`; plus
|
|
281
|
+
the settings sent (duration, resolution...) and counts of reference media, never the URLs. Predictions
|
|
282
|
+
answered to a webhook aren't seen finishing.
|
|
283
|
+
|
|
284
|
+
## What a record holds
|
|
285
|
+
|
|
286
|
+
One record per call. A call whose result arrives somewhere else (a queued call, a webhook) gets two:
|
|
287
|
+
a "start" when it is sent and a "finish" when the result comes back, both with the provider's
|
|
288
|
+
request id.
|
|
289
|
+
|
|
290
|
+
Each record has: provider, model, the provider's request id, status and error type (the error's
|
|
291
|
+
class name or the provider's code, never its message: a provider's text that doesn't look like a
|
|
292
|
+
code is left out), start time and duration, usage as the provider reports it, and the settings that
|
|
293
|
+
change the price (copied by name, never the whole input), with where the call was billed: a Google
|
|
294
|
+
project, an Azure resource, or for a provider that bills by key (OpenAI), the key's hint, its first 8
|
|
295
|
+
and last 4 characters, as the provider's own key list shows them; never the key. From the context: user, task, and the call
|
|
296
|
+
that made this one (`parent_provider` and `parent_request_id`, the provider's request id).
|
|
297
|
+
|
|
298
|
+
## When the app stops waiting
|
|
299
|
+
|
|
300
|
+
When the app cancels a call or a timeout around it runs out (`asyncio.CancelledError`,
|
|
301
|
+
`asyncio.TimeoutError`, fal_client's timeout while polling), the provider may still be running the
|
|
302
|
+
call, and billing it. So that isn't recorded as a failure:
|
|
303
|
+
|
|
304
|
+
- A call recorded in one record (OpenAI, Google, LiteLLM, `fal.run`, Modal's `remote()`) gets status
|
|
305
|
+
`cancelled`, with the error's class name as error type.
|
|
306
|
+
- A call with a "start" and a "finish" (fal's queue, Veo, Modal's `spawn()`, Pruna) gets no finish: the
|
|
307
|
+
start stays open, and a later result fetch or webhook finishes it.
|
|
308
|
+
|
|
309
|
+
## If sending fails
|
|
310
|
+
|
|
311
|
+
A busy or unreachable server is retried with growing waits. Records that still can't be sent, or
|
|
312
|
+
that the server refuses, are written to the `inference_tracker` log as one JSON line each. Every batch
|
|
313
|
+
also tells the server how many records were lost since the last one that got through.
|
|
314
|
+
|
|
315
|
+
## Adding it to an app
|
|
316
|
+
|
|
317
|
+
Step-by-step guides, for people and for coding agents:
|
|
318
|
+
|
|
319
|
+
- [skills/find-ai-calls/SKILL.md](skills/find-ai-calls/SKILL.md) lists every AI call in a repo or a
|
|
320
|
+
whole folder of repos, and changes nothing.
|
|
321
|
+
- [skills/add-tracking/SKILL.md](skills/add-tracking/SKILL.md) starts from that list and adds
|
|
322
|
+
tracking to one app, through a pull request: say who each call is for, wrap the clients, test,
|
|
323
|
+
connect the bill, and check the numbers.
|
|
324
|
+
- [skills/track-app/SKILL.md](skills/track-app/SKILL.md) (`/track-app`) does a whole app in one go:
|
|
325
|
+
runs the two guides above, opens one short pull request per repo, and ends with one table of every
|
|
326
|
+
call and where it stands. It stops only for what a person has to decide: keys, who a call is for,
|
|
327
|
+
code that looks dead, library changes.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
inference_tracker/__init__.py,sha256=E0ymOKO8fA5HcajoXrh90VgAmS1HHovUXl0YiqPsXQM,599
|
|
2
|
+
inference_tracker/_attach.py,sha256=sLjs3EisbeTX03eprG7cGm9XiOE1llLnsTAEMKflcWY,11378
|
|
3
|
+
inference_tracker/_bypass.py,sha256=WGq9Qo8DMmwi-Mzmpxd_DC0g26hS3PnzqWVFqzuiqUk,1498
|
|
4
|
+
inference_tracker/_client.py,sha256=hNQzqXMeu6bwiBCtHQhwyuBx6gY7K2Vw4JaBW5Lfmk8,17024
|
|
5
|
+
inference_tracker/_code.py,sha256=gtFoRYIL8VGKeEFG9wxVoV_ZCE5bXhHLtAb-atukR70,2416
|
|
6
|
+
inference_tracker/_context.py,sha256=Y4lxqUW-g7cA-1CPg3kjd2_EI-OVOEG3ffZyd-PR-SQ,3668
|
|
7
|
+
inference_tracker/_http.py,sha256=sHXC2bSyTKCo5oytVm2wQtULNk1xnHYs8eMWbx6pdOs,12678
|
|
8
|
+
inference_tracker/_proxy.py,sha256=d_8KrSK8IZhc3a8LJC3aeGYdeo8r6WzUWaUpjz0TGH0,2634
|
|
9
|
+
inference_tracker/_record.py,sha256=Gy-jFALZDxoha8q2o1Q8gt_EYrZbTVO3uA9sTsEd_Cc,7205
|
|
10
|
+
inference_tracker/_transport.py,sha256=cOEgf5SrrIOMzWubbFVB8Gq4RmhtxFX_MZrT2NbfNOo,1728
|
|
11
|
+
inference_tracker/_version.py,sha256=e56AvHfJCtG2ZwwINqsxINVbehWdKxMYgIDbjd7P-II,22
|
|
12
|
+
inference_tracker/eachlabs.py,sha256=ddLGoy9JEwnPMmMuyqSqp5JjIE6j2aJWHr3LzLPvWkA,10632
|
|
13
|
+
inference_tracker/fal.py,sha256=w3ZJUOjuRt9zA6IhkkdEYmdn9AlJb-GMS031pw2Rrvw,37225
|
|
14
|
+
inference_tracker/google.py,sha256=TLectEwz8MLIJkuCiCyvFrBwPUrFbDQFK5Y8X4CJgjc,17252
|
|
15
|
+
inference_tracker/litellm.py,sha256=YMV8vJViai8Z179P3I7kVAysJynaO3p76IaLbZS0lWY,22398
|
|
16
|
+
inference_tracker/modal.py,sha256=KxcdHeNKm8xPtqxXVCIU4gQmLHJerOQfWdXpOcKRxUI,16196
|
|
17
|
+
inference_tracker/openai.py,sha256=YcaN20K9MttoOxxlJ8_B3hNRWkulmfikv2Y0RcBkqCk,33790
|
|
18
|
+
inference_tracker/pruna.py,sha256=UaG4OPxvBxoHHsOmAfa2ycf24mYyqDlkNx10-jI0gpQ,10906
|
|
19
|
+
inference_tracker-0.9.4.dist-info/METADATA,sha256=QjE0ILRVfcvuWGsoplDusJDLfwbFk-Odd7hlZT4XXhQ,15969
|
|
20
|
+
inference_tracker-0.9.4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
21
|
+
inference_tracker-0.9.4.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
|
|
22
|
+
inference_tracker-0.9.4.dist-info/RECORD,,
|