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,761 @@
1
+ """Tracks calls made with the openai package, sync or async: OpenAI's own API, Azure (AzureOpenAI, or
2
+ OpenAI with an Azure base_url, as Azure AI Foundry suggests), and Vertex AI's OpenAI-compatible endpoint
3
+ (an OpenAI client whose base_url is https://aiplatform.googleapis.com/v1beta1/projects/<p>/locations/<l>/
4
+ endpoints/openapi, or the same on a regional <region>-aiplatform.googleapis.com host).
5
+
6
+ from openai import OpenAI
7
+ import inference_tracker
8
+
9
+ client = inference_tracker.openai.track(OpenAI(base_url=..., api_key=...))
10
+ response = client.responses.parse(model="gpt-5.4-mini", input=..., text_format=...)
11
+
12
+ Tracked, one "call" record each (the whole call is seen here): responses.create / parse,
13
+ chat.completions.create / parse (and beta.chat.completions.parse), embeddings.create, moderations.create,
14
+ images.generate / edit, and a raw client.post() to an images route ("/images/generations",
15
+ "/images/edits"), which is how Azure AI Foundry's other image models (FLUX, for example) are called. The
16
+ with_raw_response and with_streaming_response versions of responses, chat.completions, embeddings and
17
+ moderations .create are tracked too, when the app parses the answer (response.parse()), which is how the
18
+ OpenAI Agents SDK streams. A copy of the client (with_options, copy) is tracked like the client.
19
+ Calls made over plain HTTP, without the openai package, are recorded too (see the end of this
20
+ file). Everything else passes through unchanged. The call itself is never changed, and tracking never raises: a
21
+ problem in it is logged and the call goes on.
22
+
23
+ When the app stops waiting (its task is cancelled, or a timeout around the call runs out), the call is recorded
24
+ with status "cancelled" (error_type the exception's class name): the provider may still have answered, and billed.
25
+
26
+ Streamed calls (stream=True) are recorded when the stream ends, with the usage its last chunk or event
27
+ reports. A Responses stream always reports it. A chat completions stream reports it only when the app
28
+ asked for stream_options={"include_usage": True}; it isn't added here, because it adds a chunk the app
29
+ would then receive, and some OpenAI-compatible servers refuse it. Without it the call is recorded without
30
+ usage.
31
+
32
+ A parse call whose answer doesn't fit the format the app asked for raises after the provider has answered
33
+ and billed. So parse calls go through the SDK's own with_raw_response, and the answer is parsed here, the
34
+ same way the SDK does it: when parsing fails, the record still gets the usage the answer reports, and the
35
+ app gets the same error as before.
36
+
37
+ On the record: the model the response names (the one billed; the requested name, an Azure deployment for
38
+ example, goes in settings when it differs), the response id (the x-request-id header when the answer has
39
+ no id, as with embeddings), the usage the response reports (tokens by kind, images), and settings that
40
+ change the price (reasoning effort, service tier, image size, quality, count). Never prompts, images or
41
+ outputs. For Azure, settings also hold the resource the call went to (the first part of its host name),
42
+ which is how its bill is split. For Vertex, they hold the project and location, the model is named as
43
+ Vertex names it (without the "google/" prefix), and the tokens are named as the google wrapper names them
44
+ (input_text_tokens, output_text_tokens, thinking_tokens...), so Vertex's bill is split the same way. For
45
+ OpenAI's own API, they hold key_hint: the first 8 and last 4 characters of the API key, which OpenAI's own
46
+ key list shows too. OpenAI bills by key, and a call names no key, so this is how a call is matched to the
47
+ key that paid for it. Never the key itself.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import inspect
53
+ import logging
54
+ import re
55
+ import time
56
+ from collections.abc import Callable
57
+ from dataclasses import dataclass, field
58
+ from typing import Any
59
+ from urllib.parse import urlparse
60
+
61
+ from . import _client
62
+ from ._proxy import Path, Proxy, get, number, put
63
+ from ._record import Record, cancelled, code, error_name
64
+
65
+ logger = logging.getLogger("inference_tracker")
66
+
67
+ OPENAI = "openai"
68
+ AZURE = "azure.ai.openai"
69
+ VERTEX = "gcp.vertex_ai" # the same name google.py uses: one bill, one provider
70
+
71
+ # Calls that also have with_raw_response / with_streaming_response versions tracked here.
72
+ _CREATES = (
73
+ ("responses", "create"),
74
+ ("chat", "completions", "create"),
75
+ ("embeddings", "create"),
76
+ ("moderations", "create"),
77
+ )
78
+ RAW = ("with_raw_response", "with_streaming_response")
79
+ PATHS = frozenset(
80
+ {
81
+ *_CREATES,
82
+ ("responses", "parse"),
83
+ ("chat", "completions", "parse"),
84
+ ("beta", "chat", "completions", "parse"),
85
+ ("images", "generate"),
86
+ ("images", "edit"),
87
+ ("post",), # only a raw call to an images route, see _images_post
88
+ ("with_options",), # a copy of the client, tracked too
89
+ ("copy",),
90
+ }
91
+ | {c[:-1] + (raw, c[-1]) for c in _CREATES for raw in RAW}
92
+ )
93
+ # Request arguments copied onto the record because they change the price.
94
+ SETTINGS = ("service_tier", "size", "quality", "n", "background", "output_format", "input_fidelity")
95
+ # Content parts that aren't text. A Vertex call without any has only text tokens in; see _as_vertex.
96
+ _MEDIA = {"image_url", "input_image", "input_audio", "input_file", "file", "image", "audio", "video_url"}
97
+
98
+
99
+ @dataclass
100
+ class _Where:
101
+ provider: str
102
+ place: dict[str, str] = field(default_factory=dict) # azure_resource; gcp_project and gcp_location; or key_hint
103
+
104
+
105
+ @dataclass
106
+ class _Call:
107
+ record: Record
108
+ clock: float
109
+ text_in: bool = True # no image, audio or file in the request (only looked at for Vertex)
110
+ text_out: bool = True # no output modality other than text was asked for (only looked at for Vertex)
111
+
112
+
113
+ def track(client: Any) -> Any:
114
+ """Wraps an openai.OpenAI, AsyncOpenAI, AzureOpenAI or AsyncAzureOpenAI. See the module docstring."""
115
+ where = _where(client)
116
+
117
+ def wrap(path: Path, method: Callable[..., Any], is_async: bool) -> Callable[..., Any]:
118
+ if path == ("post",):
119
+ return _images_post(method, is_async, where)
120
+ if path in (("with_options",), ("copy",)):
121
+ return lambda *args, **kwargs: track(method(*args, **kwargs))
122
+ if len(path) > 2 and path[-2] in RAW:
123
+ return _raw_variant(path, method, is_async, where)
124
+ raw = _raw_parse(path, method)
125
+ if is_async:
126
+
127
+ async def tracked_async(*args: Any, **kwargs: Any) -> Any:
128
+ call = _start(where, kwargs)
129
+ try:
130
+ if kwargs.get("stream"):
131
+ return _watch(call, path, await method(*args, **kwargs))
132
+ answer = await (raw or method)(*args, **kwargs)
133
+ except BaseException as e:
134
+ _end(call, path, None, e)
135
+ raise
136
+ if raw is None:
137
+ response = answer
138
+ else:
139
+ try:
140
+ response = answer.parse()
141
+ if inspect.isawaitable(response):
142
+ response = await response
143
+ except BaseException as e:
144
+ _end(call, path, _body(answer), e)
145
+ raise
146
+ _end(call, path, response, None)
147
+ return response
148
+
149
+ return tracked_async
150
+
151
+ def tracked(*args: Any, **kwargs: Any) -> Any:
152
+ call = _start(where, kwargs)
153
+ try:
154
+ if kwargs.get("stream"):
155
+ return _watch(call, path, method(*args, **kwargs))
156
+ answer = (raw or method)(*args, **kwargs)
157
+ except BaseException as e:
158
+ _end(call, path, None, e)
159
+ raise
160
+ if raw is None:
161
+ response = answer
162
+ else:
163
+ try:
164
+ response = answer.parse()
165
+ except BaseException as e:
166
+ _end(call, path, _body(answer), e)
167
+ raise
168
+ _end(call, path, response, None)
169
+ return response
170
+
171
+ return tracked
172
+
173
+ return Proxy(client, PATHS, wrap)
174
+
175
+
176
+ def _raw_parse(path: Path, method: Callable[..., Any]) -> Callable[..., Any] | None:
177
+ """The SDK's with_raw_response version of a parse method: it sends the same request and returns the
178
+ answer unparsed (its parse() then does what the plain method would have). None when there isn't one."""
179
+ if path[-1] != "parse":
180
+ return None
181
+ try:
182
+ raw = getattr(getattr(method, "__self__", None), "with_raw_response", None)
183
+ found = getattr(raw, "parse", None)
184
+ return found if callable(found) else None
185
+ except Exception:
186
+ return None
187
+
188
+
189
+ def _body(answer: Any) -> Any:
190
+ """The answer's JSON body, for its id, model and usage. None when it can't be read."""
191
+ try:
192
+ return answer.http_response.json()
193
+ except Exception:
194
+ logger.debug("inference_tracker: could not read the body of an answer that failed to parse", exc_info=True)
195
+ return None
196
+
197
+
198
+ def _raw_variant(path: Path, method: Callable[..., Any], is_async: bool, where: _Where) -> Callable[..., Any]:
199
+ """x.with_raw_response.create(...) returns the HTTP answer; x.with_streaming_response.create(...) returns a
200
+ context manager that sends the request when entered and gives the HTTP answer. Either way the call is
201
+ seen when the app parses the answer (answer.parse()): its result is recorded, or, for a stream, watched
202
+ as the app reads it. The answer object is the SDK's own, with only its parse() looked through. An answer
203
+ the app never parses (it reads the bytes itself) isn't recorded."""
204
+ plain = path[:-2] + path[-1:] # ("responses", "create")
205
+
206
+ def look_through(call: _Call | None, answer: Any, stream: bool) -> Any:
207
+ if call is None:
208
+ return answer
209
+ try:
210
+ original = answer.parse
211
+ except Exception:
212
+ return answer
213
+ seen: list[bool] = []
214
+
215
+ def done(result: Any) -> Any:
216
+ if seen:
217
+ return result # parse() again: the SDK returns its cached result, already recorded
218
+ seen.append(True)
219
+ if stream:
220
+ return _watch(call, plain, result)
221
+ _end(call, plain, result, None)
222
+ return result
223
+
224
+ def failed(e: BaseException) -> None:
225
+ if not seen:
226
+ seen.append(True)
227
+ _end(call, plain, None if stream else _body(answer), e)
228
+
229
+ async def finish_async(pending: Any) -> Any:
230
+ try:
231
+ result = await pending
232
+ except BaseException as e:
233
+ failed(e)
234
+ raise
235
+ return done(result)
236
+
237
+ def parse(*args: Any, **kwargs: Any) -> Any:
238
+ try:
239
+ result = original(*args, **kwargs)
240
+ except BaseException as e:
241
+ failed(e)
242
+ raise
243
+ return finish_async(result) if inspect.isawaitable(result) else done(result)
244
+
245
+ try:
246
+ answer.parse = parse
247
+ except Exception:
248
+ logger.debug("inference_tracker: could not look through an openai raw answer", exc_info=True)
249
+ return answer
250
+
251
+ if path[-2] == "with_streaming_response":
252
+
253
+ def streaming(*args: Any, **kwargs: Any) -> Any:
254
+ manager = method(*args, **kwargs) # nothing is sent until the app enters it
255
+ try:
256
+ if hasattr(manager, "_api_request"): # AsyncResponseContextManager: an awaitable request
257
+ call = _start(where, kwargs)
258
+ pending = manager._api_request
259
+
260
+ async def request() -> Any:
261
+ try:
262
+ answer = await pending
263
+ except BaseException as e:
264
+ _end(call, plain, None, e)
265
+ raise
266
+ return look_through(call, answer, bool(kwargs.get("stream")))
267
+
268
+ manager._api_request = request()
269
+ elif hasattr(manager, "_request_func"): # ResponseContextManager: a request function
270
+ call = _start(where, kwargs)
271
+ send = manager._request_func
272
+
273
+ def request_now() -> Any:
274
+ try:
275
+ answer = send()
276
+ except BaseException as e:
277
+ _end(call, plain, None, e)
278
+ raise
279
+ return look_through(call, answer, bool(kwargs.get("stream")))
280
+
281
+ manager._request_func = request_now
282
+ except Exception:
283
+ logger.exception("inference_tracker: could not track an openai with_streaming_response call")
284
+ return manager
285
+
286
+ return streaming
287
+
288
+ if is_async:
289
+
290
+ async def raw_async(*args: Any, **kwargs: Any) -> Any:
291
+ call = _start(where, kwargs)
292
+ try:
293
+ answer = await method(*args, **kwargs)
294
+ except BaseException as e:
295
+ _end(call, plain, None, e)
296
+ raise
297
+ return look_through(call, answer, bool(kwargs.get("stream")))
298
+
299
+ return raw_async
300
+
301
+ def raw(*args: Any, **kwargs: Any) -> Any:
302
+ call = _start(where, kwargs)
303
+ try:
304
+ answer = method(*args, **kwargs)
305
+ except BaseException as e:
306
+ _end(call, plain, None, e)
307
+ raise
308
+ return look_through(call, answer, bool(kwargs.get("stream")))
309
+
310
+ return raw
311
+
312
+
313
+ def _watch(call: _Call | None, path: Path, stream: Any) -> Any:
314
+ """Returns the same stream, read through a generator that looks at each chunk or event on its way to the
315
+ app, and records the call when the usage arrives (the last chunk, or the Responses API's
316
+ response.completed event) or the stream ends, fails or is closed early. A stream that can't be read
317
+ this way (not the SDK's Stream) is recorded now, without usage."""
318
+ if call is None:
319
+ return stream
320
+ watcher = _Stream(call, path, stream)
321
+ try:
322
+ source = stream._iterator
323
+ stream._iterator = watcher.read_async(source) if hasattr(source, "__anext__") else watcher.read(source)
324
+ except Exception:
325
+ logger.debug("inference_tracker: could not watch an openai stream; recorded without usage", exc_info=True)
326
+ watcher.finish(None)
327
+ return stream
328
+
329
+
330
+ class _Stream:
331
+ """What a stream has said so far: the answer's id, model and usage, as an answer would hold them."""
332
+
333
+ def __init__(self, call: _Call, path: Path, stream: Any):
334
+ self.call = call
335
+ self.path = path
336
+ self.stream = stream
337
+ self.answer: dict[str, Any] = {}
338
+ self.images = 0
339
+ self.error_type: str | None = None
340
+ self.done = False
341
+
342
+ def see(self, item: Any) -> None:
343
+ try:
344
+ kind = get(item, "type")
345
+ response = get(item, "response") # a Responses event that carries the whole response
346
+ for source in (item, response):
347
+ for name in ("id", "model", "usage"):
348
+ value = get(source, name)
349
+ if value is not None and (name != "id" or isinstance(value, str)):
350
+ self.answer[name] = value
351
+ if not isinstance(kind, str):
352
+ # A chat completions chunk. The usage-only chunk (no choices) is the last one; some
353
+ # OpenAI-compatible servers put the running usage on every chunk, so the latest one is kept.
354
+ if get(item, "usage") is not None and not get(item, "choices"):
355
+ self.finish(None)
356
+ return
357
+ if kind.startswith("image_") and kind.endswith(".completed"):
358
+ self.images += 1
359
+ elif kind == "response.failed":
360
+ self.error_type = code(get(response, "error", "code")) or "failed"
361
+ elif kind == "error":
362
+ self.error_type = code(get(item, "code")) or "error"
363
+ if kind in ("response.completed", "response.incomplete", "response.failed", "error"):
364
+ self.finish(None)
365
+ except Exception:
366
+ logger.debug("inference_tracker: could not read an openai stream chunk", exc_info=True)
367
+
368
+ def finish(self, error: BaseException | None) -> None:
369
+ if self.done:
370
+ return
371
+ self.done = True
372
+ try:
373
+ if not isinstance(self.answer.get("id"), str):
374
+ self.answer["id"] = get(self.stream, "response", "headers").get("x-request-id")
375
+ except Exception:
376
+ pass
377
+ if self.path[0] == "images":
378
+ self.answer["data"] = [None] * self.images
379
+ _end(self.call, self.path, self.answer, error, self.error_type)
380
+
381
+ def read(self, source: Any) -> Any:
382
+ try:
383
+ for item in source:
384
+ self.see(item)
385
+ yield item
386
+ except GeneratorExit:
387
+ raise # closed early: recorded below with what was seen
388
+ except BaseException as e:
389
+ self.finish(e)
390
+ raise
391
+ finally:
392
+ self.finish(None)
393
+
394
+ async def read_async(self, source: Any) -> Any:
395
+ try:
396
+ async for item in source:
397
+ self.see(item)
398
+ yield item
399
+ except GeneratorExit:
400
+ raise
401
+ except BaseException as e:
402
+ self.finish(e)
403
+ raise
404
+ finally:
405
+ self.finish(None)
406
+
407
+
408
+ def _images_post(method: Callable[..., Any], is_async: bool, where: _Where) -> Callable[..., Any]:
409
+ """client.post(path, body=..., cast_to=...): tracked like images.generate when path is an images route,
410
+ passed through otherwise."""
411
+
412
+ def images_body(args: tuple, kwargs: dict) -> dict | None:
413
+ route = kwargs.get("path", args[0] if args else None)
414
+ body = kwargs.get("body")
415
+ if isinstance(route, str) and "/images/" in route and isinstance(body, dict):
416
+ return body
417
+ return None
418
+
419
+ if is_async:
420
+
421
+ async def tracked_async(*args: Any, **kwargs: Any) -> Any:
422
+ body = images_body(args, kwargs)
423
+ if body is None:
424
+ return await method(*args, **kwargs)
425
+ call = _start(where, body)
426
+ try:
427
+ response = await method(*args, **kwargs)
428
+ except BaseException as e:
429
+ _end(call, ("images",), None, e)
430
+ raise
431
+ _end(call, ("images",), response, None)
432
+ return response
433
+
434
+ return tracked_async
435
+
436
+ def tracked(*args: Any, **kwargs: Any) -> Any:
437
+ body = images_body(args, kwargs)
438
+ if body is None:
439
+ return method(*args, **kwargs)
440
+ call = _start(where, body)
441
+ try:
442
+ response = method(*args, **kwargs)
443
+ except BaseException as e:
444
+ _end(call, ("images",), None, e)
445
+ raise
446
+ _end(call, ("images",), response, None)
447
+ return response
448
+
449
+ return tracked
450
+
451
+
452
+ def _where(client: Any) -> _Where:
453
+ """Which bill the client's calls are on, and where on it: OpenAI; Azure, with the resource name (first
454
+ label of the host); or Vertex AI, with the project and location its base_url names."""
455
+ try:
456
+ url = urlparse(str(getattr(client, "base_url", "") or ""))
457
+ host = url.hostname or ""
458
+ if host == "aiplatform.googleapis.com" or host.endswith("-aiplatform.googleapis.com"):
459
+ found = re.search(r"/projects/([^/]+)/locations/([^/]+)", url.path)
460
+ return _Where(VERTEX, {"gcp_project": found[1], "gcp_location": found[2]} if found else {})
461
+ if "azure" in type(client).__name__.lower() or host.endswith(".azure.com"):
462
+ resource = host.split(".")[0]
463
+ return _Where(AZURE, {"azure_resource": resource} if resource else {})
464
+ except Exception:
465
+ logger.debug("inference_tracker: could not read the openai client's base_url", exc_info=True)
466
+ hint = key_hint(getattr(client, "api_key", None))
467
+ return _Where(OPENAI, {"key_hint": hint} if hint else {})
468
+
469
+
470
+ def key_hint(key: Any) -> str | None:
471
+ """The part of an API key a provider's own key list shows: its first 8 and last 4 characters
472
+ ("sk-proj-…a1b2"). Not secret, and enough to tell an account's keys apart. None for anything too short
473
+ to be a key, so the hint never gives away most of it."""
474
+ if not isinstance(key, str):
475
+ return None
476
+ key = key.strip()
477
+ if key.lower().startswith("bearer "):
478
+ key = key[7:].strip()
479
+ return f"{key[:8]}…{key[-4:]}" if len(key) >= 32 else None
480
+
481
+
482
+ def _vertex_model(model: Any) -> Any:
483
+ """Vertex's OpenAI-compatible endpoint names Google's models "google/<model>"; the bill and the google
484
+ wrapper name them without the prefix. Other publishers' models keep theirs."""
485
+ if isinstance(model, str) and model.startswith("google/"):
486
+ return model[len("google/") :]
487
+ return model
488
+
489
+
490
+ def _start(where: _Where, kwargs: dict[str, Any]) -> _Call | None:
491
+ if not _client.active():
492
+ return None # nothing is recorded: nothing is looked at
493
+ try:
494
+ settings = {k: kwargs[k] for k in SETTINGS if _given(kwargs.get(k))}
495
+ effort = get(kwargs.get("reasoning"), "effort") or kwargs.get("reasoning_effort")
496
+ if _given(effort):
497
+ settings["reasoning_effort"] = effort
498
+ settings.update(where.place)
499
+ model = kwargs.get("model") if _given(kwargs.get("model")) else None
500
+ if where.provider == VERTEX:
501
+ model = _vertex_model(model)
502
+ record = Record.new(
503
+ where.provider, str(model) if model is not None else None, started_at=time.time(), settings=settings
504
+ )
505
+ call = _Call(record, time.monotonic())
506
+ if where.provider == VERTEX:
507
+ call.text_in = not any(
508
+ _has_media(kwargs.get(k)) for k in ("messages", "input", "instructions") if k in kwargs
509
+ )
510
+ modalities = kwargs.get("modalities")
511
+ call.text_out = not isinstance(modalities, list) or all(m == "text" for m in modalities)
512
+ return call
513
+ except Exception:
514
+ logger.exception("inference_tracker: could not start tracking an openai call")
515
+ return None
516
+
517
+
518
+ def _given(value: Any) -> bool:
519
+ """Not None, and not the SDK's "not given" markers (openai.omit, NOT_GIVEN), which the OpenAI Agents SDK
520
+ passes for every setting it leaves out."""
521
+ return value is not None and type(value).__name__ not in ("Omit", "NotGiven")
522
+
523
+
524
+ def _has_media(value: Any, depth: int = 0) -> bool:
525
+ """Whether a request's messages or input hold a part that isn't text (an image, audio, a file). Only the
526
+ parts' "type" is looked at; nothing is kept."""
527
+ if depth > 6:
528
+ return False
529
+ if isinstance(value, (list, tuple)):
530
+ return any(_has_media(v, depth + 1) for v in value)
531
+ kind = get(value, "type") if not isinstance(value, str) else None
532
+ if isinstance(kind, str) and kind in _MEDIA:
533
+ return True
534
+ content = get(value, "content") if not isinstance(value, str) else None
535
+ return isinstance(content, (list, tuple)) and _has_media(content, depth + 1)
536
+
537
+
538
+ def _end(
539
+ call: _Call | None, path: Path, response: Any, error: BaseException | None, error_type: str | None = None
540
+ ) -> None:
541
+ """Records the call. error_type without an error: the provider said the call failed (a failed stream)."""
542
+ if call is None:
543
+ return
544
+ record = call.record
545
+ try:
546
+ record.duration_s = round(time.monotonic() - call.clock, 3)
547
+ # An error can still come with an answer (a parse call whose answer didn't fit the format): the
548
+ # provider billed it, so its id, model and usage go on the record too.
549
+ if error is not None:
550
+ record.status = "cancelled" if cancelled(error) else "error"
551
+ record.error_type = code(getattr(error, "code", None)) or error_name(error)
552
+ record.request_id = getattr(error, "request_id", None) or get(response, "id") or None
553
+ else:
554
+ record.status = "error" if error_type else "ok"
555
+ record.error_type = error_type
556
+ record.request_id = get(response, "id") or getattr(response, "_request_id", None)
557
+ if response is not None:
558
+ answered = get(response, "model")
559
+ if record.provider == VERTEX:
560
+ answered = _vertex_model(answered)
561
+ if isinstance(answered, str) and answered and answered != record.model:
562
+ if record.model:
563
+ record.settings["requested_model"] = record.model
564
+ record.model = answered
565
+ record.units = _units(path, response)
566
+ if record.provider == VERTEX:
567
+ record.units = _as_vertex(record.units, get(response, "usage", "total_tokens"), call)
568
+ _client.record(record)
569
+ except Exception:
570
+ logger.exception("inference_tracker: could not record an openai call")
571
+
572
+
573
+ def _units(path: Path, response: Any) -> dict[str, float]:
574
+ usage = get(response, "usage")
575
+ units: dict[str, float] = {}
576
+ if path[0] == "moderations":
577
+ return units # free today, and the answer reports no usage: the record is the call itself
578
+ if path[0] == "embeddings":
579
+ put(units, "input_tokens", get(usage, "prompt_tokens"))
580
+ return units
581
+ if path[0] == "images":
582
+ data = get(response, "data")
583
+ if isinstance(data, list):
584
+ units["images"] = len(data)
585
+ put(units, "input_tokens", get(usage, "input_tokens"))
586
+ put(units, "output_tokens", get(usage, "output_tokens"))
587
+ put(units, "input_text_tokens", get(usage, "input_tokens_details", "text_tokens"))
588
+ put(units, "input_image_tokens", get(usage, "input_tokens_details", "image_tokens"))
589
+ return units
590
+ if path[0] == "responses":
591
+ put(units, "input_tokens", get(usage, "input_tokens"))
592
+ put(units, "output_tokens", get(usage, "output_tokens"))
593
+ put(units, "cached_input_tokens", get(usage, "input_tokens_details", "cached_tokens"))
594
+ put(units, "cache_write_input_tokens", get(usage, "input_tokens_details", "cache_write_tokens"))
595
+ put(units, "reasoning_tokens", get(usage, "output_tokens_details", "reasoning_tokens"))
596
+ return units
597
+ put(units, "input_tokens", get(usage, "prompt_tokens"))
598
+ put(units, "output_tokens", get(usage, "completion_tokens"))
599
+ put(units, "cached_input_tokens", get(usage, "prompt_tokens_details", "cached_tokens"))
600
+ # GPT-5.6 and later bill writing the prompt cache apart, and say how many input tokens were written.
601
+ put(units, "cache_write_input_tokens", get(usage, "prompt_tokens_details", "cache_write_tokens"))
602
+ put(units, "reasoning_tokens", get(usage, "completion_tokens_details", "reasoning_tokens"))
603
+ return units
604
+
605
+
606
+ def _as_vertex(units: dict[str, float], total: Any, call: _Call) -> dict[str, float]:
607
+ """OpenAI's names for a Vertex call's tokens, turned into the google wrapper's: output_tokens without
608
+ thinking, thinking_tokens apart, and the text part of input and output named as such
609
+ (input_text_tokens, output_text_tokens), which is what Vertex's bill lines are split by.
610
+
611
+ OpenAI counts reasoning inside the output tokens. Vertex's endpoint may count it apart, or report it only
612
+ in the total; the total says which. When the request had an image, audio or a file in it, the input
613
+ isn't all text, and only input_tokens is recorded for it."""
614
+ out = dict(units)
615
+ inp = number(out.get("input_tokens"))
616
+ output = number(out.get("output_tokens"))
617
+ reasoning = number(out.pop("reasoning_tokens", None))
618
+ total = number(total)
619
+ thinking = None
620
+ if inp is not None and output is not None:
621
+ if reasoning is not None:
622
+ thinking = reasoning
623
+ counted_apart = total is not None and total == inp + output + reasoning
624
+ if not counted_apart and output >= reasoning:
625
+ output -= reasoning
626
+ elif total is not None and total > inp + output:
627
+ thinking = total - inp - output # reported only in the total
628
+ if thinking:
629
+ out["thinking_tokens"] = thinking
630
+ if output is not None:
631
+ out["output_tokens"] = output
632
+ if call.text_out:
633
+ out["output_text_tokens"] = output
634
+ if inp is not None and call.text_in:
635
+ out["input_text_tokens"] = inp
636
+ return out
637
+
638
+
639
+ # --- over plain HTTP ---------------------------------------------------------------------------------
640
+ #
641
+ # An app may call OpenAI's API without the openai package: httpx.post("https://api.openai.com/v1/decisions",
642
+ # json=..., headers=...). Once init() has attached, every httpx and requests session is watched (see _attach),
643
+ # and a POST to OpenAI's API is recorded as one "call", the same as the wrapper records it: the model and the
644
+ # usage the answer reports, the settings that change the price, the x-request-id header as the request id when
645
+ # the answer has no id. An endpoint added after this was written is recorded too, since every inference
646
+ # endpoint is a POST and reports its usage the same way.
647
+ #
648
+ # Requests the openai package sends (its X-Stainless-Lang header says so) are left to the wrapper, and those
649
+ # LiteLLM sends are left to LiteLLM's callback: each call is recorded once. So are files, uploads, batches,
650
+ # fine-tuning, vector stores and other requests that aren't an inference call. A streamed request
651
+ # ("stream": true) is recorded without usage: its answer is never read here, so the app gets the stream as it
652
+ # comes.
653
+
654
+ HOSTS = ("api.openai.com",) # and regional ones: eu.api.openai.com
655
+ # First part of the path (after /v1) of requests that aren't an inference call.
656
+ _NOT_CALLS = frozenset(
657
+ {
658
+ "files", "uploads", "batches", "fine_tuning", "vector_stores", "containers", "assistants", "threads",
659
+ "organization", "projects", "evals", "conversations", "chatkit", "models", "realtime",
660
+ }
661
+ ) # fmt: skip
662
+ # The wrapper's path for each endpoint whose usage is read its own way; any other reads like responses.
663
+ _ENDPOINTS = {"chat": ("chat",), "completions": ("chat",), "embeddings": ("embeddings",), "images": ("images",)}
664
+ _ENDPOINTS["moderations"] = ("moderations",)
665
+
666
+
667
+ def track_http(client: Any) -> Any:
668
+ """Watches an httpx.Client, httpx.AsyncClient or requests.Session for calls to OpenAI's API made without the
669
+ openai package, and returns the same client. Only needed with init(attach=False): otherwise every session is
670
+ watched already."""
671
+ from . import _http
672
+
673
+ try:
674
+ if not _http.watch(client, _HttpWatcher()):
675
+ logger.warning("inference_tracker: can't watch a %s for openai calls", type(client).__name__)
676
+ except Exception:
677
+ logger.exception("inference_tracker: could not watch a client for openai calls")
678
+ return client
679
+
680
+
681
+ def _http_where(ex: Any) -> _Where:
682
+ """OpenAI, with the hint of the key the request sent."""
683
+ try:
684
+ hint = key_hint(ex.request_headers.get("authorization"))
685
+ except Exception:
686
+ hint = None
687
+ return _Where(OPENAI, {"key_hint": hint} if hint else {})
688
+
689
+
690
+ class _HttpWatcher:
691
+ name = "openai"
692
+
693
+ def accepts(self, host: str) -> bool:
694
+ return host in HOSTS or host.endswith(".api.openai.com")
695
+
696
+ def wants_body(self, ex: Any) -> bool:
697
+ return self._path(ex) is not None and not _streamed(ex)
698
+
699
+ def seen(self, ex: Any) -> None:
700
+ path = self._path(ex)
701
+ if path is None:
702
+ return
703
+ body = ex.request_json()
704
+ call = _start(_http_where(ex), body if isinstance(body, dict) else {})
705
+ if call is None:
706
+ return
707
+ call.clock = ex.clock
708
+ call.record.started_at = ex.started_at
709
+ answer = ex.body if isinstance(ex.body, dict) else {}
710
+ error_type = None
711
+ if not ex.ok:
712
+ error_type = code(get(answer, "error", "code")) or code(get(answer, "error", "type")) or f"http_{ex.status}"
713
+ answer = {}
714
+ if not get(answer, "id"):
715
+ answer = {**answer, "id": ex.headers.get("x-request-id")} # the Decisions API's answer has no id
716
+ _end(call, path, answer, None, error_type)
717
+
718
+ def failed(self, ex: Any) -> None:
719
+ path = self._path(ex)
720
+ if path is None:
721
+ return
722
+ body = ex.request_json()
723
+ call = _start(_http_where(ex), body if isinstance(body, dict) else {})
724
+ if call is not None:
725
+ call.clock = ex.clock
726
+ call.record.started_at = ex.started_at
727
+ _end(call, path, None, ex.error)
728
+
729
+ def _path(self, ex: Any) -> Path | None:
730
+ """The wrapper's path for this request, None when it isn't an inference call this watcher records."""
731
+ try:
732
+ if ex.method != "POST" or ex.request_headers.get("x-stainless-lang") is not None or _from_litellm():
733
+ return None
734
+ parts = [p for p in ex.path.split("/") if p]
735
+ if parts and parts[0].startswith("v") and parts[0][1:].isdigit():
736
+ parts = parts[1:]
737
+ if not parts or parts[0] in _NOT_CALLS or parts[-1] == "cancel":
738
+ return None
739
+ return _ENDPOINTS.get(parts[0], ("responses",))
740
+ except Exception:
741
+ return None
742
+
743
+
744
+ def _streamed(ex: Any) -> bool:
745
+ body = ex.request_json()
746
+ return isinstance(body, dict) and bool(body.get("stream"))
747
+
748
+
749
+ def _from_litellm() -> bool:
750
+ """Whether LiteLLM is making this request: its callback records the call."""
751
+ try:
752
+ import sys
753
+
754
+ f = sys._getframe(1)
755
+ while f is not None:
756
+ if str(f.f_globals.get("__name__", "")).startswith("litellm"):
757
+ return True
758
+ f = f.f_back
759
+ except Exception:
760
+ pass
761
+ return False