inference-tracker 0.9.4__tar.gz

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.
Files changed (50) hide show
  1. inference_tracker-0.9.4/.github/workflows/publish.yml +36 -0
  2. inference_tracker-0.9.4/.gitignore +8 -0
  3. inference_tracker-0.9.4/LICENSE +202 -0
  4. inference_tracker-0.9.4/PKG-INFO +327 -0
  5. inference_tracker-0.9.4/README.md +318 -0
  6. inference_tracker-0.9.4/pyproject.toml +49 -0
  7. inference_tracker-0.9.4/skills/add-tracking/SKILL.md +241 -0
  8. inference_tracker-0.9.4/skills/find-ai-calls/SKILL.md +310 -0
  9. inference_tracker-0.9.4/skills/track-app/SKILL.md +147 -0
  10. inference_tracker-0.9.4/src/inference_tracker/__init__.py +28 -0
  11. inference_tracker-0.9.4/src/inference_tracker/_attach.py +321 -0
  12. inference_tracker-0.9.4/src/inference_tracker/_bypass.py +53 -0
  13. inference_tracker-0.9.4/src/inference_tracker/_client.py +371 -0
  14. inference_tracker-0.9.4/src/inference_tracker/_code.py +64 -0
  15. inference_tracker-0.9.4/src/inference_tracker/_context.py +98 -0
  16. inference_tracker-0.9.4/src/inference_tracker/_http.py +306 -0
  17. inference_tracker-0.9.4/src/inference_tracker/_proxy.py +71 -0
  18. inference_tracker-0.9.4/src/inference_tracker/_record.py +158 -0
  19. inference_tracker-0.9.4/src/inference_tracker/_transport.py +51 -0
  20. inference_tracker-0.9.4/src/inference_tracker/_version.py +1 -0
  21. inference_tracker-0.9.4/src/inference_tracker/eachlabs.py +262 -0
  22. inference_tracker-0.9.4/src/inference_tracker/fal.py +842 -0
  23. inference_tracker-0.9.4/src/inference_tracker/google.py +388 -0
  24. inference_tracker-0.9.4/src/inference_tracker/litellm.py +471 -0
  25. inference_tracker-0.9.4/src/inference_tracker/modal.py +380 -0
  26. inference_tracker-0.9.4/src/inference_tracker/openai.py +761 -0
  27. inference_tracker-0.9.4/src/inference_tracker/pruna.py +258 -0
  28. inference_tracker-0.9.4/tests/conftest.py +11 -0
  29. inference_tracker-0.9.4/tests/fixtures/fal_workflow_result_ok.json +35 -0
  30. inference_tracker-0.9.4/tests/fixtures/fal_workflow_webhook_fail.json +42 -0
  31. inference_tracker-0.9.4/tests/fixtures/fal_workflow_webhook_ok.json +41 -0
  32. inference_tracker-0.9.4/tests/test_attach.py +388 -0
  33. inference_tracker-0.9.4/tests/test_client.py +339 -0
  34. inference_tracker-0.9.4/tests/test_code.py +61 -0
  35. inference_tracker-0.9.4/tests/test_context.py +63 -0
  36. inference_tracker-0.9.4/tests/test_eachlabs.py +158 -0
  37. inference_tracker-0.9.4/tests/test_fal.py +764 -0
  38. inference_tracker-0.9.4/tests/test_fal_http.py +499 -0
  39. inference_tracker-0.9.4/tests/test_fal_sdk.py +164 -0
  40. inference_tracker-0.9.4/tests/test_google.py +210 -0
  41. inference_tracker-0.9.4/tests/test_google_sdk.py +209 -0
  42. inference_tracker-0.9.4/tests/test_litellm.py +406 -0
  43. inference_tracker-0.9.4/tests/test_modal.py +343 -0
  44. inference_tracker-0.9.4/tests/test_openai.py +329 -0
  45. inference_tracker-0.9.4/tests/test_openai_agents.py +296 -0
  46. inference_tracker-0.9.4/tests/test_openai_sdk.py +476 -0
  47. inference_tracker-0.9.4/tests/test_pruna.py +343 -0
  48. inference_tracker-0.9.4/tests/test_record.py +102 -0
  49. inference_tracker-0.9.4/tests/test_transport.py +64 -0
  50. inference_tracker-0.9.4/uv.lock +4223 -0
@@ -0,0 +1,36 @@
1
+ # Publishes the library to PyPI when a version tag (v0.9.4) is pushed. Uses PyPI's trusted publishing:
2
+ # PyPI trusts this workflow, so no token is stored anywhere.
3
+ name: Publish
4
+
5
+ on:
6
+ push:
7
+ tags: ["v*"]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: astral-sh/setup-uv@v6
15
+ - name: The tag matches the version
16
+ run: |
17
+ version=$(sed -n 's/^__version__ = "\(.*\)"/\1/p' src/inference_tracker/_version.py)
18
+ test "v$version" = "$GITHUB_REF_NAME" || { echo "Tag $GITHUB_REF_NAME, version $version"; exit 1; }
19
+ - run: uv build
20
+ - uses: actions/upload-artifact@v4
21
+ with:
22
+ name: dist
23
+ path: dist/
24
+
25
+ publish:
26
+ needs: build
27
+ runs-on: ubuntu-latest
28
+ environment: pypi
29
+ permissions:
30
+ id-token: write
31
+ steps:
32
+ - uses: actions/download-artifact@v4
33
+ with:
34
+ name: dist
35
+ path: dist/
36
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .env
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -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.