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,388 @@
1
+ """Tracks calls made with Google's google-genai package (genai.Client), on Vertex AI or the Gemini API,
2
+ sync or async (client.aio), and embeddings made with the older vertexai package's TextEmbeddingModel.
3
+
4
+ from google import genai
5
+ import inference_tracker
6
+
7
+ client = inference_tracker.google.track(genai.Client(vertexai=True, project=..., location=...))
8
+ response = client.models.generate_content(model="gemini-3.1-flash-image", contents=..., config=...)
9
+
10
+ from vertexai.language_models import TextEmbeddingModel
11
+
12
+ model = inference_tracker.google.track(TextEmbeddingModel.from_pretrained("text-embedding-005"))
13
+ embeddings = model.get_embeddings(["..."])
14
+
15
+ Tracked:
16
+ - models.generate_content, generate_images, edit_image: one "call" record each, with the response id
17
+ and the usage the response reports: tokens in and out, by kind (text, image...), thinking and cached
18
+ tokens, images made.
19
+ - models.embed_content: one "call" record, with the tokens in as the response reports them (Vertex does;
20
+ see _embed_units for the Gemini API, which doesn't), and the number of inputs. Embeddings have no
21
+ response id.
22
+ - TextEmbeddingModel.get_embeddings / get_embeddings_async (the vertexai package): one "call" record,
23
+ with the tokens in (each embedding's statistics.token_count, added up), the number of inputs, and the
24
+ billable characters Vertex reports.
25
+ - models.generate_videos (Veo) runs as a long-running operation: a "start" record when it is sent (its
26
+ request id is the operation's name), and a "finish" record when operations.get() returns it done, with
27
+ the seconds of video made (the requested length times the videos returned).
28
+ When the app stops waiting (its task is cancelled, or a timeout around the call runs out), a "call" record gets
29
+ status "cancelled", not "error": Google may still have run the call. A Veo operation the app stopped polling is
30
+ left open (no finish): a later operations.get() that returns it done finishes it.
31
+ Everything else, streamed calls included, passes through unchanged. The call itself is never changed, and
32
+ tracking never raises: a problem in it is logged and the call goes on.
33
+
34
+ Settings copied onto the record are those that change the price (resolution, length, audio, number of
35
+ videos, image size, aspect ratio, thinking budget or level), plus the Google Cloud project the call went to,
36
+ which is how Vertex's bill is split. Never prompts, images or outputs.
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 Callable
47
+ from typing import Any
48
+
49
+ from . import _client
50
+ from ._proxy import Path, Proxy, get, number, put
51
+ from ._record import Record, cancelled, code, error_name
52
+
53
+ logger = logging.getLogger("inference_tracker")
54
+
55
+ VERTEX = "gcp.vertex_ai"
56
+ GEMINI = "gcp.gemini"
57
+
58
+ _CALLS = {"generate_content", "generate_images", "edit_image", "embed_content"}
59
+ PATHS = frozenset(
60
+ {("models", m) for m in _CALLS | {"generate_videos"}}
61
+ | {("aio", "models", m) for m in _CALLS | {"generate_videos"}}
62
+ | {("operations", "get"), ("aio", "operations", "get")}
63
+ )
64
+ # Config fields copied onto the record because they change the price.
65
+ SETTINGS = (
66
+ "duration_seconds",
67
+ "resolution",
68
+ "generate_audio",
69
+ "number_of_videos",
70
+ "number_of_images",
71
+ "aspect_ratio",
72
+ "image_size",
73
+ )
74
+ # Video operations sent and not seen done yet, by operation name. Beyond this many, the oldest is forgotten.
75
+ MAX_OPEN = 1000
76
+
77
+
78
+ def track(client: Any) -> Any:
79
+ """Wraps a google.genai.Client, or a vertexai TextEmbeddingModel. See the module docstring."""
80
+ if callable(getattr(client, "get_embeddings", None)) and not hasattr(client, "models"):
81
+ return _track_embedding_model(client)
82
+ api = getattr(client, "_api_client", None)
83
+ provider = VERTEX if getattr(api, "vertexai", False) else GEMINI
84
+ project = getattr(api, "project", None) if provider == VERTEX else None
85
+ open_ops: OrderedDict[str, tuple[Record, float]] = OrderedDict()
86
+ lock = threading.Lock()
87
+
88
+ def before(path: Path, kwargs: dict[str, Any]) -> tuple[Record, float] | None:
89
+ if path[-1] == "get" or not _client.active():
90
+ return None
91
+ try:
92
+ config = kwargs.get("config")
93
+ settings = {k: v for k in SETTINGS if (v := get(config, k)) is not None}
94
+ for k in ("aspect_ratio", "image_size"):
95
+ v = get(config, "image_config", k)
96
+ if v is not None:
97
+ settings[k] = v
98
+ for k in ("thinking_budget", "thinking_level"):
99
+ v = get(config, "thinking_config", k)
100
+ if v is not None:
101
+ settings[k] = getattr(v, "value", v)
102
+ if project:
103
+ settings["gcp_project"] = project
104
+ phase = "start" if path[-1] == "generate_videos" else "call"
105
+ record = Record.new(provider, kwargs.get("model"), phase=phase, started_at=time.time(), settings=settings)
106
+ return record, time.monotonic()
107
+ except Exception:
108
+ logger.exception("inference_tracker: could not start tracking a google-genai call")
109
+ return None
110
+
111
+ def after(
112
+ path: Path,
113
+ call: tuple[Record, float] | None,
114
+ args: tuple,
115
+ kwargs: dict,
116
+ result: Any,
117
+ error: BaseException | None,
118
+ ) -> None:
119
+ try:
120
+ if not _client.active():
121
+ return
122
+ if path[-1] == "get":
123
+ _polled(args, kwargs, result, error)
124
+ elif path[-1] == "generate_videos":
125
+ _sent(call, result, error)
126
+ else:
127
+ _called(call, result, error, kwargs.get("contents") if path[-1] == "embed_content" else None)
128
+ except Exception:
129
+ logger.exception("inference_tracker: could not record a google-genai call")
130
+
131
+ def _called(
132
+ call: tuple[Record, float] | None, response: Any, error: BaseException | None, embedded: Any = None
133
+ ) -> None:
134
+ if call is None:
135
+ return
136
+ record, clock = call
137
+ record.duration_s = round(time.monotonic() - clock, 3)
138
+ _outcome(record, error)
139
+ if error is None:
140
+ record.request_id = get(response, "response_id")
141
+ record.units = _units(response) if embedded is None else _embed_units(response, embedded)
142
+ _client.record(record)
143
+
144
+ def _sent(call: tuple[Record, float] | None, operation: Any, error: BaseException | None) -> None:
145
+ if call is None:
146
+ return
147
+ record, clock = call
148
+ name = get(operation, "name") if error is None else None
149
+ if error is not None or not name:
150
+ # Never got an operation: the whole call ends here.
151
+ record.phase = "call"
152
+ record.duration_s = round(time.monotonic() - clock, 3)
153
+ _outcome(record, error)
154
+ _client.record(record)
155
+ return
156
+ record.request_id = name
157
+ _client.record(record)
158
+ with lock:
159
+ open_ops[name] = call
160
+ while len(open_ops) > MAX_OPEN:
161
+ open_ops.popitem(last=False)
162
+ if get(operation, "done"):
163
+ _finish(name, operation, None)
164
+
165
+ def _polled(args: tuple, kwargs: dict, operation: Any, error: BaseException | None) -> None:
166
+ asked = kwargs.get("operation", args[0] if args else None)
167
+ name = get(asked, "name") if not isinstance(asked, str) else asked
168
+ if not name:
169
+ return
170
+ if error is not None:
171
+ return # a failed poll isn't the end of the operation; the app may poll again
172
+ if get(operation, "done"):
173
+ _finish(name, operation, None)
174
+
175
+ def _finish(name: str, operation: Any, error: BaseException | None) -> None:
176
+ with lock:
177
+ call = open_ops.pop(name, None)
178
+ if call is None:
179
+ return
180
+ start, clock = call
181
+ failure = get(operation, "error")
182
+ videos = get(operation, "response", "generated_videos")
183
+ if videos is None:
184
+ videos = get(operation, "result", "generated_videos")
185
+ units: dict[str, float] = {}
186
+ if isinstance(videos, list):
187
+ units["videos"] = len(videos)
188
+ seconds = number(start.settings.get("duration_seconds"))
189
+ if seconds is not None:
190
+ units["video_seconds"] = seconds * len(videos)
191
+ error_type = None
192
+ if failure:
193
+ error_type = code(get(failure, "code")) or "operation_error"
194
+ elif isinstance(videos, list) and not videos:
195
+ filtered = get(operation, "response", "rai_media_filtered_count")
196
+ error_type = "filtered" if filtered else "no_video"
197
+ _client.record(
198
+ Record.new(
199
+ start.provider,
200
+ start.model,
201
+ phase="finish",
202
+ request_id=name,
203
+ status="error" if error_type else "ok",
204
+ error_type=error_type,
205
+ duration_s=round(time.monotonic() - clock, 3),
206
+ units=units,
207
+ user_id=start.user_id,
208
+ task_id=start.task_id,
209
+ parent_provider=start.parent_provider,
210
+ parent_request_id=start.parent_request_id,
211
+ call_name=start.call_name,
212
+ )
213
+ )
214
+
215
+ def wrap(path: Path, method: Callable[..., Any], is_async: bool) -> Callable[..., Any]:
216
+ if is_async:
217
+
218
+ async def tracked_async(*args: Any, **kwargs: Any) -> Any:
219
+ call = before(path, kwargs)
220
+ try:
221
+ result = await method(*args, **kwargs)
222
+ except BaseException as e:
223
+ after(path, call, args, kwargs, None, e)
224
+ raise
225
+ after(path, call, args, kwargs, result, None)
226
+ return result
227
+
228
+ return tracked_async
229
+
230
+ def tracked(*args: Any, **kwargs: Any) -> Any:
231
+ call = before(path, kwargs)
232
+ try:
233
+ result = method(*args, **kwargs)
234
+ except BaseException as e:
235
+ after(path, call, args, kwargs, None, e)
236
+ raise
237
+ after(path, call, args, kwargs, result, None)
238
+ return result
239
+
240
+ return tracked
241
+
242
+ return Proxy(client, PATHS, wrap)
243
+
244
+
245
+ def _outcome(record: Record, error: BaseException | None) -> None:
246
+ if error is None:
247
+ record.status = "ok"
248
+ return
249
+ record.status = "cancelled" if cancelled(error) else "error"
250
+ record.error_type = code(getattr(error, "status", None)) or error_name(error)
251
+
252
+
253
+ def _units(response: Any) -> dict[str, float]:
254
+ usage = get(response, "usage_metadata")
255
+ units: dict[str, float] = {}
256
+ put(units, "input_tokens", get(usage, "prompt_token_count"))
257
+ put(units, "output_tokens", get(usage, "candidates_token_count"))
258
+ put(units, "thinking_tokens", get(usage, "thoughts_token_count"))
259
+ put(units, "cached_input_tokens", get(usage, "cached_content_token_count"))
260
+ for side, field in (("input", "prompt_tokens_details"), ("output", "candidates_tokens_details")):
261
+ for detail in get(usage, field) or []:
262
+ modality = get(detail, "modality")
263
+ modality = getattr(modality, "value", modality)
264
+ count = number(get(detail, "token_count"))
265
+ if isinstance(modality, str) and count is not None:
266
+ key = f"{side}_{modality.lower()}_tokens"
267
+ units[key] = units.get(key, 0) + count
268
+ images = get(response, "generated_images")
269
+ if isinstance(images, list):
270
+ units["images"] = len(images)
271
+ return units
272
+
273
+
274
+ def _embed_units(response: Any, contents: Any) -> dict[str, float]:
275
+ """An embed_content answer's usage: the tokens in (each embedding's statistics.token_count, added up; by
276
+ modality when Vertex says), the billable characters when Vertex reports them, and the number of inputs.
277
+
278
+ The Gemini API answers with the embeddings alone, no token count. Then the characters of text sent are
279
+ counted here instead (input_characters: a count, never the text), so the call can still be split.
280
+ """
281
+ units: dict[str, float] = {}
282
+ embeddings = get(response, "embeddings")
283
+ embeddings = embeddings if isinstance(embeddings, list) else []
284
+ units["inputs"] = len(embeddings)
285
+ counts = [number(get(e, "statistics", "token_count")) for e in embeddings]
286
+ if embeddings and all(c is not None for c in counts):
287
+ units["input_tokens"] = sum(counts)
288
+ for e in embeddings:
289
+ for detail in get(e, "statistics", "tokens_details") or []:
290
+ modality = get(detail, "modality")
291
+ modality = getattr(modality, "value", modality)
292
+ count = number(get(detail, "token_count"))
293
+ if isinstance(modality, str) and count is not None:
294
+ key = f"input_{modality.lower()}_tokens"
295
+ units[key] = units.get(key, 0) + count
296
+ characters, all_text = _text_size(contents)
297
+ if "input_tokens" in units and all_text and not any(k.startswith("input_") and k != "input_tokens" for k in units):
298
+ units["input_text_tokens"] = units["input_tokens"] # only text went in
299
+ put(units, "billable_characters", get(response, "metadata", "billable_character_count"))
300
+ if "input_tokens" not in units and "billable_characters" not in units:
301
+ units["input_characters"] = characters
302
+ return units
303
+
304
+
305
+ def _text_size(contents: Any, depth: int = 0) -> tuple[int, bool]:
306
+ """The characters of text in an embed_content call's contents (strings, Parts, Contents, or lists of
307
+ them), and whether there was nothing but text. Nothing is kept but the count."""
308
+ if isinstance(contents, str):
309
+ return len(contents), True
310
+ if depth > 4 or contents is None:
311
+ return 0, contents is None
312
+ if isinstance(contents, (list, tuple)):
313
+ sizes = [_text_size(c, depth + 1) for c in contents]
314
+ return sum(n for n, _ in sizes), all(t for _, t in sizes)
315
+ text = get(contents, "text")
316
+ if isinstance(text, str):
317
+ return len(text), True
318
+ parts = get(contents, "parts")
319
+ if isinstance(parts, list):
320
+ return _text_size(parts, depth + 1)
321
+ return 0, False # an image, a file...
322
+
323
+
324
+ def _track_embedding_model(model: Any) -> Any:
325
+ """Wraps a vertexai.language_models.TextEmbeddingModel (from_pretrained), whose get_embeddings and
326
+ get_embeddings_async call Vertex's predict. The project and location come from the endpoint the model
327
+ calls ("projects/<p>/locations/<l>/publishers/google/models/<model>")."""
328
+ endpoint = str(getattr(model, "_endpoint_name", "") or "")
329
+ found = re.search(r"projects/([^/]+)/locations/([^/]+)", endpoint)
330
+ place = {"gcp_project": found[1], "gcp_location": found[2]} if found else {}
331
+ name = getattr(model, "_model_id", None) or endpoint.rsplit("/", 1)[-1] or None
332
+
333
+ def start() -> tuple[Record, float] | None:
334
+ if not _client.active():
335
+ return None
336
+ try:
337
+ return Record.new(VERTEX, name, started_at=time.time(), settings=dict(place)), time.monotonic()
338
+ except Exception:
339
+ logger.exception("inference_tracker: could not start tracking a vertexai embeddings call")
340
+ return None
341
+
342
+ def end(call: tuple[Record, float] | None, embeddings: Any, error: BaseException | None) -> None:
343
+ if call is None:
344
+ return
345
+ record, clock = call
346
+ try:
347
+ record.duration_s = round(time.monotonic() - clock, 3)
348
+ _outcome(record, error)
349
+ if error is None and isinstance(embeddings, list):
350
+ record.units["inputs"] = len(embeddings)
351
+ counts = [number(get(e, "statistics", "token_count")) for e in embeddings]
352
+ if embeddings and all(c is not None for c in counts):
353
+ record.units["input_tokens"] = record.units["input_text_tokens"] = sum(counts)
354
+ if embeddings:
355
+ metadata = get(embeddings[0], "_prediction_response", "metadata")
356
+ put(record.units, "billable_characters", get(metadata, "billableCharacterCount"))
357
+ _client.record(record)
358
+ except Exception:
359
+ logger.exception("inference_tracker: could not record a vertexai embeddings call")
360
+
361
+ def wrap(path: Path, method: Callable[..., Any], is_async: bool) -> Callable[..., Any]:
362
+ if is_async:
363
+
364
+ async def tracked_async(*args: Any, **kwargs: Any) -> Any:
365
+ call = start()
366
+ try:
367
+ result = await method(*args, **kwargs)
368
+ except BaseException as e:
369
+ end(call, None, e)
370
+ raise
371
+ end(call, result, None)
372
+ return result
373
+
374
+ return tracked_async
375
+
376
+ def tracked(*args: Any, **kwargs: Any) -> Any:
377
+ call = start()
378
+ try:
379
+ result = method(*args, **kwargs)
380
+ except BaseException as e:
381
+ end(call, None, e)
382
+ raise
383
+ end(call, result, None)
384
+ return result
385
+
386
+ return tracked
387
+
388
+ return Proxy(model, frozenset({("get_embeddings",), ("get_embeddings_async",)}), wrap)