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,471 @@
1
+ """Tracks calls made through LiteLLM, for every provider it routes to: AWS Bedrock, OpenAI, Azure, Vertex AI and the
2
+ rest. Also calls made by libraries built on LiteLLM, like the OpenAI Agents SDK's LitellmModel.
3
+
4
+ import inference_tracker
5
+
6
+ inference_tracker.litellm.track() # once, at startup; calling it again does nothing
7
+
8
+ with inference_tracker.context(user_id=uid, task_id=task.id):
9
+ response = await litellm.acompletion(model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0", ...)
10
+
11
+ track() adds a callback to litellm.callbacks, LiteLLM's own way to see each call, so nothing is wrapped and the call
12
+ itself is never changed. Tracking never raises: a problem in it is logged and the call goes on. An app that sets
13
+ litellm.callbacks itself (litellm.callbacks = [...]) replaces the list: call track() after that.
14
+
15
+ Tracked, one "call" record each, sync or async, streamed or not: completion, text_completion, embedding,
16
+ image_generation, image_edit and responses. A streamed call is recorded when its stream ends (that is when LiteLLM
17
+ has its usage); a stream the app stops reading early isn't recorded. Answers from LiteLLM's cache aren't recorded:
18
+ no provider was called. Every other LiteLLM call passes through unrecorded.
19
+
20
+ Who a call is for: LiteLLM runs its callbacks on its own thread, or after the call has returned. So the context
21
+ (user, task, parent) is taken when LiteLLM sends the request (its pre-call hook, which runs where the app made the
22
+ call) and kept by LiteLLM's id for the call until the call is recorded.
23
+
24
+ When a call is recorded: an async call (acompletion..., and so the OpenAI Agents SDK's Runner.run and run_sync) is
25
+ recorded before it returns to the app, from the hook LiteLLM runs on the answer
26
+ (async_post_call_success_deployment_hook): LiteLLM's own success callbacks run later on its logging worker, which may
27
+ be after the app's flushing block ended, or never, if the process is frozen first. A sync call (completion...) is
28
+ recorded by LiteLLM's logging thread a moment after it returns; inference_tracker.flush() (and so
29
+ context(flush=True)) first waits for those of the calls that have been answered, so they are in that flush. Streams
30
+ are recorded when they end, as LiteLLM reports them.
31
+
32
+ When the app stops waiting for an async call (its task is cancelled, or a timeout around it runs out) before the
33
+ provider answered, LiteLLM records nothing. The call is then recorded with status "cancelled" (error_type
34
+ "CancelledError") when the task that made it is done: the provider may still have run it, and billed it.
35
+
36
+ On the record:
37
+ - provider: Bedrock is "aws.bedrock". OpenAI, Azure (azure, azure_ai), Vertex AI and Gemini get the names the openai
38
+ and google wrappers use, so the same bills split them; any other provider keeps LiteLLM's name for it.
39
+ - model: the one the provider billed. For Bedrock, the model or inference profile id in the request's URL (no
40
+ "bedrock/" or route prefix; an application inference profile's ARN as it is). For others, the model the response
41
+ names, with the requested one in settings when it differs (an Azure deployment, say).
42
+ - request_id: for Bedrock, the x-amzn-requestid header of its answer (LiteLLM keeps the answer's headers). For
43
+ others, the response id, or the request id header when there isn't one (embeddings, images, errors).
44
+ - units: input_tokens (all of the input, cached or not, as LiteLLM counts it), and the parts of it read from or
45
+ written to the prompt cache (cached_input_tokens, cache_write_input_tokens); output_tokens and reasoning_tokens
46
+ (part of the output); images.
47
+ - settings: those that change the price (service tier, Bedrock's latency-optimized mode, reasoning effort, thinking
48
+ budget, image size, quality, count) and where the call went: the AWS region, the Azure resource, the Google Cloud
49
+ project. Never prompts, inputs or outputs.
50
+ - status and error_type: Bedrock's error code (x-amzn-errortype), or the exception's class name.
51
+
52
+ Each call is recorded once. A call LiteLLM makes with its own client isn't seen by the other wrappers, so tracking
53
+ both LiteLLM and an openai client (inference_tracker.openai.track) is fine. Only don't pass a tracked client to
54
+ LiteLLM (litellm.completion(..., client=tracked)): that call would be recorded by both.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ import asyncio
60
+ import datetime
61
+ import logging
62
+ import re
63
+ import threading
64
+ import time
65
+ from collections import OrderedDict
66
+ from dataclasses import dataclass
67
+ from typing import Any
68
+ from urllib.parse import unquote, urlparse
69
+
70
+ from . import _client, _code
71
+ from ._context import Context
72
+ from ._context import current as _current_context
73
+ from ._proxy import get, number, put
74
+ from ._record import Record, cancelled, code, error_name
75
+ from .google import GEMINI, VERTEX
76
+ from .openai import AZURE, OPENAI
77
+
78
+ logger = logging.getLogger("inference_tracker")
79
+
80
+ BEDROCK = "aws.bedrock"
81
+
82
+ # LiteLLM's provider names, as the bills know them. A provider not here keeps LiteLLM's name.
83
+ PROVIDERS = {
84
+ "bedrock": BEDROCK,
85
+ "openai": OPENAI,
86
+ "text-completion-openai": OPENAI,
87
+ "azure": AZURE,
88
+ "azure_text": AZURE,
89
+ "azure_ai": AZURE,
90
+ "vertex_ai": VERTEX,
91
+ "vertex_ai_beta": VERTEX,
92
+ "gemini": GEMINI,
93
+ }
94
+ # LiteLLM's call types that are recorded (sync and async).
95
+ CALL_TYPES = frozenset(
96
+ {
97
+ t
98
+ for c in ("completion", "text_completion", "embedding", "image_generation", "image_edit", "responses")
99
+ for t in (c, "a" + c)
100
+ }
101
+ )
102
+ # Request arguments copied onto the record because they change the price.
103
+ SETTINGS = ("service_tier", "reasoning_effort", "size", "quality", "n")
104
+ # Calls sent and not recorded yet, by LiteLLM's call id. Beyond this many, the oldest is forgotten.
105
+ MAX_OPEN = 1000
106
+ # How long flush() waits, at most, for a sync call that was answered this long ago to be recorded. One that isn't
107
+ # by then (LiteLLM dropped its logging task, say) isn't waited for again.
108
+ LATE_FOR = 5.0
109
+
110
+ # An id LiteLLM makes up when the provider gives none (Bedrock's answers, for one): not the provider's.
111
+ _MADE_UP_ID = re.compile(r"^chatcmpl-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
112
+ _BEDROCK_HOST = re.compile(r"^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com$")
113
+ _REQUEST_ID_HEADERS = ("x-request-id", "request-id", "apim-request-id", "x-amzn-requestid")
114
+
115
+
116
+ @dataclass
117
+ class _Open:
118
+ """A call LiteLLM has sent and this module hasn't recorded yet."""
119
+
120
+ context: Context
121
+ api_base: str | None
122
+ sync: bool # completion, not acompletion: recorded on LiteLLM's logging thread
123
+ stream: bool
124
+ kwargs: Any = None # LiteLLM's own dict for the call, kept only for an async call, to record it if cancelled
125
+ answered: float | None = None # time.monotonic() when the provider's answer came (LiteLLM's post-call hook)
126
+ code: list[str] | None = None # the app's functions that made the call, taken where it was made
127
+
128
+
129
+ _open: OrderedDict[str, _Open] = OrderedDict()
130
+ # Calls recorded when they returned (_returned): LiteLLM's success callback for them comes later, and is skipped.
131
+ _recorded: OrderedDict[str, None] = OrderedDict()
132
+ _open_lock = threading.Lock()
133
+ _changed = threading.Condition(_open_lock) # a call was recorded: for flush(), waiting for late records
134
+ _recording = 0 # sync calls taken out of _open whose record isn't queued yet
135
+ _logger: Any = None
136
+ _track_lock = threading.Lock()
137
+
138
+
139
+ def track() -> Any:
140
+ """Adds the tracking callback to litellm.callbacks, once. Returns it (None when LiteLLM can't be loaded)."""
141
+ global _logger
142
+ try:
143
+ import litellm
144
+
145
+ with _track_lock:
146
+ if _logger is None:
147
+ _logger = _make_logger()
148
+ if _logger not in litellm.callbacks:
149
+ litellm.callbacks.append(_logger)
150
+ if _wait_for_records not in _client._before_flush:
151
+ _client._before_flush.append(_wait_for_records)
152
+ return _logger
153
+ except Exception:
154
+ logger.exception("inference_tracker: could not add the litellm callback")
155
+ return None
156
+
157
+
158
+ def _make_logger() -> Any:
159
+ from litellm.integrations.custom_logger import CustomLogger
160
+
161
+ class Tracker(CustomLogger):
162
+ """LiteLLM calls these itself; the argument names are LiteLLM's (it passes them by name)."""
163
+
164
+ def log_pre_api_call(self, model: Any, messages: Any, kwargs: Any) -> None:
165
+ _before(kwargs)
166
+
167
+ def log_post_api_call(self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any) -> None:
168
+ _answered(kwargs)
169
+
170
+ async def async_post_call_success_deployment_hook(
171
+ self, request_data: Any, response: Any, call_type: Any
172
+ ) -> Any:
173
+ _returned(request_data, response)
174
+ return None # the response as it is
175
+
176
+ def log_success_event(self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any) -> None:
177
+ _after(kwargs, response_obj, start_time, end_time)
178
+
179
+ def log_failure_event(self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any) -> None:
180
+ _after(kwargs, response_obj, start_time, end_time, failed=True)
181
+
182
+ async def async_log_success_event(self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any) -> None:
183
+ _after(kwargs, response_obj, start_time, end_time)
184
+
185
+ async def async_log_failure_event(self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any) -> None:
186
+ _after(kwargs, response_obj, start_time, end_time, failed=True)
187
+
188
+ return Tracker()
189
+
190
+
191
+ def _before(kwargs: Any) -> None:
192
+ """Runs where the app made the call, just before the request goes out: keeps who it is for, and the URL. An async
193
+ call is watched until the task that made it is done, in case the app stops waiting for it (see _task_done)."""
194
+ try:
195
+ if not _client.active():
196
+ return
197
+ call_id = get(kwargs, "litellm_call_id")
198
+ if not call_id:
199
+ return
200
+ api_base = get(kwargs, "additional_args", "api_base")
201
+ call_type = get(kwargs, "call_type")
202
+ call = _Open(
203
+ _current_context(),
204
+ api_base if isinstance(api_base, str) else None,
205
+ sync=isinstance(call_type, str) and not call_type.startswith("a"),
206
+ stream=get(kwargs, "stream") is True,
207
+ code=_code.functions() or None,
208
+ )
209
+ task = None
210
+ if call_type in CALL_TYPES and not call.sync and not call.stream:
211
+ try:
212
+ asyncio.get_running_loop()
213
+ task = asyncio.current_task()
214
+ except RuntimeError:
215
+ task = None # not on an event loop: LiteLLM sends it from a thread
216
+ call.kwargs = kwargs if task is not None else None
217
+ with _open_lock:
218
+ _open[call_id] = call
219
+ _open.move_to_end(call_id)
220
+ while len(_open) > MAX_OPEN:
221
+ _open.popitem(last=False)
222
+ if task is not None:
223
+ task.add_done_callback(lambda done: _task_done(call_id, done))
224
+ except Exception:
225
+ logger.exception("inference_tracker: could not start tracking a litellm call")
226
+
227
+
228
+ def _answered(kwargs: Any) -> None:
229
+ """LiteLLM's post-call hook: the provider's answer has come, so a record is due (see _wait_for_records)."""
230
+ try:
231
+ with _open_lock:
232
+ call = _open.get(get(kwargs, "litellm_call_id"))
233
+ if call is not None and call.answered is None:
234
+ call.answered = time.monotonic()
235
+ except Exception:
236
+ logger.exception("inference_tracker: could not track a litellm answer")
237
+
238
+
239
+ def _returned(request_data: Any, response: Any) -> None:
240
+ """An async call's answer, before it returns to the app: recorded now. A stream is recorded when it ends."""
241
+ try:
242
+ if not _client.active() or response is None or hasattr(response, "__anext__") or hasattr(response, "__next__"):
243
+ return
244
+ logging_obj = get(request_data, "litellm_logging_obj")
245
+ kwargs = getattr(logging_obj, "model_call_details", None)
246
+ if not isinstance(kwargs, dict):
247
+ return
248
+ _after(kwargs, response, getattr(logging_obj, "start_time", None), datetime.datetime.now(), inline=True)
249
+ except Exception:
250
+ logger.exception("inference_tracker: could not record a litellm call")
251
+
252
+
253
+ def _task_done(call_id: str, task: Any) -> None:
254
+ """The task that made an async call is done. When the call is still open without an answer, the app stopped
255
+ waiting for it (cancelled, or a timeout around it): recorded as "cancelled"."""
256
+ try:
257
+ with _open_lock:
258
+ call = _open.get(call_id)
259
+ if call is None or call.answered is not None or call.kwargs is None:
260
+ return
261
+ _after(call.kwargs, None, get(call.kwargs, "start_time"), datetime.datetime.now(), stopped=True)
262
+ except Exception:
263
+ logger.exception("inference_tracker: could not record a cancelled litellm call")
264
+
265
+
266
+ def _wait_for_records(deadline: float) -> None:
267
+ """Before a flush: waits, until the deadline, for the sync calls the provider has answered to be recorded by
268
+ LiteLLM's logging thread (it runs the callbacks a moment after the call returns)."""
269
+ with _changed:
270
+ while True:
271
+ now = time.monotonic()
272
+ late = [c for c in _open.values() if c.sync and not c.stream and c.answered and now - c.answered < LATE_FOR]
273
+ if (not late and not _recording) or now >= deadline:
274
+ return
275
+ _changed.wait(min(deadline - now, 0.05))
276
+
277
+
278
+ def _after(
279
+ kwargs: Any,
280
+ response: Any,
281
+ start_time: Any,
282
+ end_time: Any,
283
+ failed: bool = False,
284
+ stopped: bool = False,
285
+ inline: bool = False,
286
+ ) -> None:
287
+ """Records a call. `stopped`: the app stopped waiting before any answer (see _task_done). `inline`: recorded
288
+ as it returns (_returned), so LiteLLM's success callback for it, which comes later, is skipped."""
289
+ global _recording
290
+ counted = False
291
+ try:
292
+ call_id = get(kwargs, "litellm_call_id")
293
+ with _open_lock:
294
+ if call_id is not None and not failed and not stopped and call_id in _recorded:
295
+ if not inline:
296
+ _recorded.pop(call_id, None)
297
+ return # recorded when it returned
298
+ call = _open.pop(call_id, None)
299
+ if call is not None and call.sync:
300
+ _recording += 1 # flush() waits for it until it is queued (see _wait_for_records)
301
+ counted = True
302
+ if inline and call_id is not None:
303
+ _recorded[call_id] = None
304
+ while len(_recorded) > MAX_OPEN:
305
+ _recorded.popitem(last=False)
306
+ ctx, api_base = (call.context, call.api_base) if call is not None else (None, None)
307
+ if not _client.active():
308
+ return
309
+ if get(kwargs, "call_type") not in CALL_TYPES or get(kwargs, "cache_hit") is True:
310
+ return
311
+ error = get(kwargs, "exception") if failed else None
312
+ if failed or stopped:
313
+ response = None
314
+ llm_provider = get(kwargs, "custom_llm_provider") or get(kwargs, "litellm_params", "custom_llm_provider")
315
+ provider = PROVIDERS.get(llm_provider, llm_provider) if isinstance(llm_provider, str) else None
316
+ api_base = (
317
+ api_base
318
+ or _text(get(kwargs, "litellm_params", "api_base"))
319
+ or _text(get(response, "_hidden_params", "api_base"))
320
+ )
321
+ url = urlparse(api_base or "")
322
+ host = url.hostname or ""
323
+ headers = _headers(kwargs, response, error)
324
+ requested = _text(get(kwargs, "model"))
325
+ settings = _settings(get(kwargs, "optional_params"), response)
326
+
327
+ if provider == BEDROCK:
328
+ model = _bedrock_model(url.path) or _text(get(response, "model")) or requested
329
+ region = _BEDROCK_HOST.match(host)
330
+ region = (region.group(1) if region else None) or _text(get(response, "_hidden_params", "region_name"))
331
+ if region:
332
+ settings["aws_region"] = region
333
+ request_id = headers.get("x-amzn-requestid")
334
+ else:
335
+ model = _text(get(response, "model")) or requested
336
+ if requested and model != requested:
337
+ settings["requested_model"] = requested
338
+ if host.endswith(".azure.com"):
339
+ settings["azure_resource"] = host.split(".")[0]
340
+ project = re.search(r"/projects/([^/]+)/", url.path)
341
+ if project and provider == VERTEX:
342
+ settings["gcp_project"] = project.group(1)
343
+ request_id = _response_id(response) or next(
344
+ (headers[h] for h in _REQUEST_ID_HEADERS if headers.get(h)), None
345
+ )
346
+
347
+ fields: dict[str, Any] = {}
348
+ if ctx is not None: # who the call was for when it was made, not whatever is current here
349
+ fields = {
350
+ "user_id": ctx.user_id,
351
+ "task_id": ctx.task_id,
352
+ "parent_provider": ctx.parent_provider,
353
+ "parent_request_id": ctx.parent_request_id,
354
+ "call_name": ctx.call_name,
355
+ "code": call.code if call is not None else None,
356
+ }
357
+ started, ended = _seconds(start_time), _seconds(end_time)
358
+ record = Record.new(
359
+ provider or "litellm",
360
+ model,
361
+ request_id=request_id or None,
362
+ status="cancelled" if stopped or cancelled(error) else "error" if failed else "ok",
363
+ started_at=started,
364
+ duration_s=round(ended - started, 3) if started is not None and ended is not None else None,
365
+ units=_units(get(kwargs, "call_type"), response),
366
+ settings=settings,
367
+ **fields,
368
+ )
369
+ if stopped:
370
+ record.error_type = "CancelledError"
371
+ elif failed:
372
+ found = code((headers.get("x-amzn-errortype") or "").split(":")[0])
373
+ record.error_type = found or (error_name(error) if isinstance(error, BaseException) else "error")
374
+ _client.record(record)
375
+ except Exception:
376
+ logger.exception("inference_tracker: could not record a litellm call")
377
+ finally:
378
+ if counted:
379
+ with _changed:
380
+ _recording -= 1
381
+ _changed.notify_all()
382
+
383
+
384
+ def _bedrock_model(path: str) -> str | None:
385
+ """The model id in a Bedrock runtime URL: /model/<id>/converse (or converse-stream, invoke...)."""
386
+ found = re.search(r"/model/([^/]+)/", path)
387
+ return unquote(found.group(1)) if found else None
388
+
389
+
390
+ def _response_id(response: Any) -> str | None:
391
+ rid = get(response, "id")
392
+ return rid if isinstance(rid, str) and rid and not _MADE_UP_ID.match(rid) else None
393
+
394
+
395
+ def _headers(kwargs: Any, response: Any, error: Any) -> dict[str, str]:
396
+ """The provider's answer headers, lower-case, from wherever LiteLLM keeps them (on the response, on the error)."""
397
+ sources = (
398
+ lambda: get(kwargs, "response_headers"),
399
+ lambda: get(response, "_hidden_params", "additional_headers"),
400
+ lambda: get(response, "_hidden_params", "headers"),
401
+ lambda: getattr(error, "litellm_response_headers", None),
402
+ lambda: get(error, "response", "headers"),
403
+ lambda: get(kwargs, "standard_logging_object", "hidden_params", "additional_headers"),
404
+ )
405
+ found: dict[str, str] = {}
406
+ for source in sources:
407
+ try:
408
+ items = dict(source() or {}).items()
409
+ except Exception:
410
+ continue
411
+ for k, v in items:
412
+ name = str(k).lower()
413
+ if name.startswith("llm_provider-"):
414
+ name = name[len("llm_provider-") :]
415
+ if isinstance(v, str):
416
+ found.setdefault(name, v)
417
+ return found
418
+
419
+
420
+ def _settings(params: Any, response: Any) -> dict[str, Any]:
421
+ params = params if isinstance(params, dict) else {}
422
+ settings = {k: params[k] for k in SETTINGS if params.get(k) is not None}
423
+ tier = get(params, "serviceTier", "type") # Bedrock's own form of service_tier
424
+ if tier is not None:
425
+ settings.setdefault("service_tier", tier)
426
+ tier = code(get(response, "service_tier")) # the tier that served the call, when the answer says
427
+ if tier is not None:
428
+ settings["service_tier"] = tier
429
+ latency = get(params, "performanceConfig", "latency") # Bedrock's latency-optimized mode
430
+ if latency is not None:
431
+ settings["latency"] = latency
432
+ budget = get(params, "thinking", "budget_tokens")
433
+ if budget is not None:
434
+ settings["thinking_budget"] = budget
435
+ return settings
436
+
437
+
438
+ def _units(call_type: Any, response: Any) -> dict[str, float]:
439
+ usage = get(response, "usage")
440
+ units: dict[str, float] = {}
441
+ if isinstance(call_type, str) and call_type.lstrip("a").startswith("image"):
442
+ data = get(response, "data")
443
+ if isinstance(data, list):
444
+ units["images"] = len(data)
445
+ if number(get(usage, "prompt_tokens")) is not None: # chat completions, embeddings
446
+ put(units, "input_tokens", get(usage, "prompt_tokens"))
447
+ put(units, "output_tokens", get(usage, "completion_tokens"))
448
+ details, out_details = get(usage, "prompt_tokens_details"), get(usage, "completion_tokens_details")
449
+ else: # responses, images
450
+ put(units, "input_tokens", get(usage, "input_tokens"))
451
+ put(units, "output_tokens", get(usage, "output_tokens"))
452
+ details, out_details = get(usage, "input_tokens_details"), get(usage, "output_tokens_details")
453
+ cached = number(get(details, "cached_tokens"))
454
+ put(units, "cached_input_tokens", cached if cached is not None else get(usage, "cache_read_input_tokens"))
455
+ written = number(get(usage, "cache_creation_input_tokens"))
456
+ written = written if written is not None else number(get(details, "cache_creation_tokens"))
457
+ written = written if written is not None else number(get(details, "cache_write_tokens"))
458
+ if written: # only providers that bill writing the cache (Anthropic models, GPT-5.6 and later) report it
459
+ units["cache_write_input_tokens"] = written
460
+ put(units, "reasoning_tokens", get(out_details, "reasoning_tokens"))
461
+ return units
462
+
463
+
464
+ def _text(value: Any) -> str | None:
465
+ return value if isinstance(value, str) and value else None
466
+
467
+
468
+ def _seconds(t: Any) -> float | None:
469
+ if isinstance(t, datetime.datetime):
470
+ return t.timestamp()
471
+ return number(t)