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,28 @@
1
+ """inference_tracker: records each inference call with who it was for."""
2
+
3
+ from . import eachlabs, fal, google, litellm, modal, openai, pruna
4
+ from ._client import Client, flush, init, record, shutdown
5
+ from ._context import Context, context, current
6
+ from ._record import Record, error_name
7
+ from ._version import __version__
8
+
9
+ __all__ = [
10
+ "Client",
11
+ "Context",
12
+ "Record",
13
+ "context",
14
+ "current",
15
+ "eachlabs",
16
+ "error_name",
17
+ "fal",
18
+ "google",
19
+ "litellm",
20
+ "modal",
21
+ "openai",
22
+ "pruna",
23
+ "flush",
24
+ "init",
25
+ "record",
26
+ "shutdown",
27
+ "__version__",
28
+ ]
@@ -0,0 +1,321 @@
1
+ """Attaches to the provider SDKs once, at init(), so every client the app makes is tracked, wherever and whenever
2
+ it's made: nothing to wrap, and a call added later is recorded without anyone remembering to.
3
+
4
+ - openai (OpenAI, AsyncOpenAI and the Azure ones) and google-genai (genai.Client): the client's attributes that
5
+ lead to inference calls (client.chat, client.models...) are looked up through the same wrappers track() uses.
6
+ Clients made by LiteLLM are left alone: LiteLLM's own callback records those calls.
7
+ - Plain HTTP (httpx.Client, httpx.AsyncClient, requests.Session): each session is watched on its first request
8
+ for the providers tracked over HTTP: fal (fal_client's own session included), eachlabs, Pruna, Modal web
9
+ endpoints, and OpenAI's API called without the openai package. Other hosts pass through unseen.
10
+ - LiteLLM: its callback is added (litellm.track()).
11
+
12
+ A package imported after init() is attached to when it's imported. Only the class is changed, in memory: the app's
13
+ objects and calls stay its own, a call is never changed, and tracking never raises. If a package changed what we
14
+ attach to, that package isn't attached (one warning in the log) and the app runs on.
15
+
16
+ track() still works: a client wrapped with it is recorded by its wrapper only, never twice.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import importlib.abc
22
+ import inspect
23
+ import logging
24
+ import sys
25
+ import threading
26
+ from collections.abc import Callable
27
+ from typing import Any
28
+
29
+ from . import _bypass, _client, _http
30
+
31
+ logger = logging.getLogger("inference_tracker")
32
+
33
+ _VIEW = "_inference_tracker_view" # an attached client's tracked stand-in, kept on the client
34
+ _SKIP = "_inference_tracker_skip" # a client LiteLLM made: its calls are LiteLLM's to record
35
+ _WATCHED = "_inference_tracker_watched" # an HTTP session already given the watchers
36
+
37
+ _done: set[str] = set()
38
+ _lock = threading.Lock()
39
+ _on = False # set by attach(); the class changes do nothing until then (and after off())
40
+
41
+
42
+ # --- what is attached ------------------------------------------------------------------------------
43
+
44
+
45
+ def _openai() -> None:
46
+ import openai
47
+
48
+ from . import openai as tracked
49
+
50
+ names = sorted({p[0] for p in tracked.PATHS} - {"post", "with_options", "copy"})
51
+ for cls in (openai.OpenAI, openai.AsyncOpenAI):
52
+ _skip_litellm_made(cls)
53
+ _lookups(cls, names, lambda client: tracked.track(client))
54
+
55
+
56
+ def _google() -> None:
57
+ from google import genai
58
+
59
+ from . import google as tracked
60
+
61
+ names = sorted({p[0] for p in tracked.PATHS})
62
+ _lookups(genai.Client, names, lambda client: tracked.track(client))
63
+
64
+
65
+ def _httpx() -> None:
66
+ # The classes where httpx defines them: httpx.Client may have been replaced (a test's stand-in, say).
67
+ from httpx import _client as httpx_client
68
+
69
+ _sessions(httpx_client.Client, "send", is_async=False)
70
+ _sessions(httpx_client.AsyncClient, "send", is_async=True)
71
+
72
+
73
+ def _requests() -> None:
74
+ from requests import sessions
75
+
76
+ _sessions(sessions.Session, "request", is_async=False) # before the request is prepared: its hooks come from here
77
+ _sessions(sessions.Session, "send", is_async=False)
78
+
79
+
80
+ def _litellm() -> None:
81
+ from . import litellm
82
+
83
+ litellm.track()
84
+
85
+
86
+ # Module that triggers it → what to attach.
87
+ TARGETS: dict[str, Callable[[], None]] = {
88
+ "openai": _openai,
89
+ "google.genai": _google,
90
+ "httpx": _httpx,
91
+ "requests": _requests,
92
+ "litellm": _litellm,
93
+ }
94
+
95
+
96
+ def attach() -> None:
97
+ """Attaches to every target already imported, and to the others when they are. Safe to call again."""
98
+ global _on
99
+ _on = True
100
+ for module in TARGETS:
101
+ if module in sys.modules:
102
+ _run(module)
103
+ _install_import_hook()
104
+
105
+
106
+ def off() -> None:
107
+ """Stops the attached tracking (the classes stay changed, but stand aside). For tests."""
108
+ global _on
109
+ _on = False
110
+
111
+
112
+ def _run(module: str) -> None:
113
+ with _lock:
114
+ if module in _done:
115
+ return
116
+ _done.add(module)
117
+ try:
118
+ TARGETS[module]()
119
+ except Exception:
120
+ logger.warning("inference_tracker: couldn't attach to %s; its calls won't be recorded", module, exc_info=True)
121
+
122
+
123
+ # --- attribute lookups ---------------------------------------------------------------------------
124
+
125
+
126
+ class _Lookup:
127
+ """Replaces one attribute on an SDK client class (client.chat, client.models...). Looked up on a client, it
128
+ gives the attribute as the client's tracked stand-in has it."""
129
+
130
+ def __init__(self, name: str, original: Any, make: Callable[[Any], Any]):
131
+ self.name, self.original, self.make = name, original, make
132
+
133
+ def _own(self, obj: Any, cls: Any) -> Any:
134
+ get = getattr(self.original, "__get__", None)
135
+ return get(obj, cls) if get is not None else self.original
136
+
137
+ def __get__(self, obj: Any, cls: Any = None) -> Any:
138
+ if obj is None or not _on or _bypass.on() or not _client.active() or getattr(obj, _SKIP, False):
139
+ return self._own(obj, cls)
140
+ try:
141
+ view = obj.__dict__.get(_VIEW)
142
+ if view is None:
143
+ view = self.make(obj)
144
+ obj.__dict__[_VIEW] = view
145
+ return getattr(view, self.name)
146
+ except Exception:
147
+ logger.exception("inference_tracker: could not track %s.%s", type(obj).__name__, self.name)
148
+ return self._own(obj, cls)
149
+
150
+ def __set__(self, obj: Any, value: Any) -> None:
151
+ setter = getattr(self.original, "__set__", None)
152
+ if setter is not None:
153
+ setter(obj, value)
154
+ else:
155
+ obj.__dict__[self.name] = value
156
+
157
+ def __delete__(self, obj: Any) -> None:
158
+ deleter = getattr(self.original, "__delete__", None)
159
+ if deleter is not None:
160
+ deleter(obj)
161
+ else:
162
+ obj.__dict__.pop(self.name, None)
163
+
164
+
165
+ def _lookups(cls: type, names: list[str], make: Callable[[Any], Any]) -> None:
166
+ for name in names:
167
+ original = inspect.getattr_static(cls, name) # raises if the SDK no longer has it: the target isn't attached
168
+ if isinstance(original, _Lookup):
169
+ continue
170
+ setattr(cls, name, _Lookup(name, original, make))
171
+
172
+
173
+ def _skip_litellm_made(cls: type) -> None:
174
+ """Marks the clients LiteLLM makes, so their calls are recorded once, by LiteLLM's callback."""
175
+ init = cls.__init__
176
+ if getattr(init, "_inference_tracker", False):
177
+ return
178
+
179
+ def __init__(self: Any, *args: Any, **kwargs: Any) -> None:
180
+ init(self, *args, **kwargs)
181
+ try:
182
+ f = sys._getframe(1)
183
+ while f is not None:
184
+ if str(f.f_globals.get("__name__", "")).startswith("litellm"):
185
+ self.__dict__[_SKIP] = True
186
+ break
187
+ f = f.f_back
188
+ except Exception:
189
+ pass
190
+
191
+ __init__._inference_tracker = True # type: ignore[attr-defined]
192
+ __init__.__wrapped__ = init # type: ignore[attr-defined]
193
+ cls.__init__ = __init__ # type: ignore[misc]
194
+
195
+
196
+ # --- HTTP sessions --------------------------------------------------------------------------------
197
+
198
+
199
+ def watchers() -> list[_http.Watcher]:
200
+ """The watchers every session gets, one per provider tracked over HTTP."""
201
+ from . import eachlabs, fal, modal, openai, pruna
202
+
203
+ with _lock:
204
+ global _watchers
205
+ if _watchers is None:
206
+ _watchers = [
207
+ fal._HttpWatcher(fal.SETTINGS),
208
+ eachlabs._HttpWatcher(eachlabs.SETTINGS),
209
+ pruna._HttpWatcher(pruna.SETTINGS),
210
+ modal._HttpWatcher(()),
211
+ openai._HttpWatcher(),
212
+ ]
213
+ return _watchers
214
+
215
+
216
+ _watchers: list[_http.Watcher] | None = None
217
+
218
+
219
+ def learn(watcher: Any) -> None:
220
+ """A track_http() call's own settings (or Modal app names) are added to the attached watcher of that
221
+ provider, so sessions the app didn't wrap get them too."""
222
+ try:
223
+ for w in watchers():
224
+ if w.name != watcher.name:
225
+ continue
226
+ for attr in ("settings", "apps"):
227
+ mine, theirs = getattr(w, attr, None), getattr(watcher, attr, None)
228
+ if isinstance(mine, (tuple, list)) and isinstance(theirs, (tuple, list)):
229
+ merged = list(dict.fromkeys([*mine, *theirs]))
230
+ if attr == "apps":
231
+ merged.sort(key=len, reverse=True) # longest first, as modal's watcher keeps them
232
+ setattr(w, attr, tuple(merged) if isinstance(mine, tuple) else merged)
233
+ except Exception:
234
+ logger.exception("inference_tracker: could not add a client's settings to the attached tracking")
235
+
236
+
237
+ def _watch(session: Any) -> None:
238
+ try:
239
+ session.__dict__[_WATCHED] = True
240
+ for w in watchers():
241
+ _http.watch(session, w)
242
+ except Exception:
243
+ logger.exception("inference_tracker: could not watch an HTTP session")
244
+
245
+
246
+ def _sessions(cls: type, method: str, *, is_async: bool) -> None:
247
+ original = cls.__dict__.get(method) or getattr(cls, method)
248
+ if getattr(original, "_inference_tracker", False):
249
+ return
250
+
251
+ def needs(session: Any) -> bool:
252
+ try:
253
+ return _on and _client.active() and not session.__dict__.get(_WATCHED, False)
254
+ except Exception:
255
+ return False
256
+
257
+ if is_async:
258
+
259
+ async def attached_async(self: Any, *args: Any, **kwargs: Any) -> Any:
260
+ if needs(self):
261
+ _watch(self)
262
+ return await getattr(self, method)(*args, **kwargs) # the watched session's own method
263
+ return await original(self, *args, **kwargs)
264
+
265
+ attached: Any = attached_async
266
+ else:
267
+
268
+ def attached_sync(self: Any, *args: Any, **kwargs: Any) -> Any:
269
+ if needs(self):
270
+ _watch(self)
271
+ return getattr(self, method)(*args, **kwargs)
272
+ return original(self, *args, **kwargs)
273
+
274
+ attached = attached_sync
275
+ attached._inference_tracker = True
276
+ attached.__wrapped__ = original
277
+ attached.__name__ = getattr(original, "__name__", method)
278
+ setattr(cls, method, attached)
279
+
280
+
281
+ # --- packages imported later ---------------------------------------------------------------------
282
+
283
+
284
+ class _Finder(importlib.abc.MetaPathFinder):
285
+ """Runs the attach for a target module right after it is first imported."""
286
+
287
+ def find_spec(self, name: str, path: Any = None, target: Any = None) -> Any:
288
+ if name not in TARGETS or name in _done:
289
+ return None
290
+ spec = None
291
+ for finder in sys.meta_path:
292
+ if finder is self or not hasattr(finder, "find_spec"):
293
+ continue
294
+ try:
295
+ spec = finder.find_spec(name, path, target)
296
+ except Exception:
297
+ continue
298
+ if spec is not None:
299
+ break
300
+ loader = getattr(spec, "loader", None)
301
+ if spec is None or loader is None or not hasattr(loader, "exec_module"):
302
+ return None
303
+ exec_module = loader.exec_module
304
+
305
+ def exec_and_attach(module: Any) -> None:
306
+ exec_module(module)
307
+ _run(name)
308
+
309
+ try:
310
+ loader.exec_module = exec_and_attach
311
+ except Exception:
312
+ return None
313
+ return spec
314
+
315
+
316
+ _finder = _Finder()
317
+
318
+
319
+ def _install_import_hook() -> None:
320
+ if _finder not in sys.meta_path:
321
+ sys.meta_path.insert(0, _finder)
@@ -0,0 +1,53 @@
1
+ """Set while a track() wrapper looks up its client's own attribute or runs a call it records itself, so the
2
+ tracking attached at init() (_attach) stands aside: one record per call."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import contextvars
7
+ import functools
8
+ import inspect
9
+ from collections.abc import Callable
10
+ from typing import Any
11
+
12
+ _on: contextvars.ContextVar[bool] = contextvars.ContextVar("inference_tracker_bypass", default=False)
13
+
14
+
15
+ def on() -> bool:
16
+ return _on.get()
17
+
18
+
19
+ class bypass:
20
+ """with bypass(): ... (the attached tracking doesn't see what runs inside)."""
21
+
22
+ def __enter__(self) -> None:
23
+ self._token = _on.set(True)
24
+
25
+ def __exit__(self, *exc: Any) -> None:
26
+ _on.reset(self._token)
27
+
28
+
29
+ def methods(cls: type) -> type:
30
+ """Runs each public method the class defines in bypass(): for wrappers that record the calls they make."""
31
+ for name, fn in list(vars(cls).items()):
32
+ if name.startswith("_") or not inspect.isfunction(fn):
33
+ continue
34
+ setattr(cls, name, _wrapped(fn))
35
+ return cls
36
+
37
+
38
+ def _wrapped(fn: Callable[..., Any]) -> Callable[..., Any]:
39
+ if inspect.iscoroutinefunction(fn):
40
+
41
+ @functools.wraps(fn)
42
+ async def run_async(*args: Any, **kwargs: Any) -> Any:
43
+ with bypass():
44
+ return await fn(*args, **kwargs)
45
+
46
+ return run_async
47
+
48
+ @functools.wraps(fn)
49
+ def run(*args: Any, **kwargs: Any) -> Any:
50
+ with bypass():
51
+ return fn(*args, **kwargs)
52
+
53
+ return run