frugal-sdk-python 0.1.0__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 (71) hide show
  1. frugal_sdk_python-0.1.0/.github/workflows/cd.yml +63 -0
  2. frugal_sdk_python-0.1.0/.gitignore +94 -0
  3. frugal_sdk_python-0.1.0/LICENSES/Apache-2.0.txt +187 -0
  4. frugal_sdk_python-0.1.0/PKG-INFO +195 -0
  5. frugal_sdk_python-0.1.0/README.md +166 -0
  6. frugal_sdk_python-0.1.0/REUSE.toml +17 -0
  7. frugal_sdk_python-0.1.0/docs/metrics-reference.md +135 -0
  8. frugal_sdk_python-0.1.0/docs/quickstart.md +289 -0
  9. frugal_sdk_python-0.1.0/examples/test-env/README.md +110 -0
  10. frugal_sdk_python-0.1.0/examples/test-env/collector/otel-collector-config.yaml +34 -0
  11. frugal_sdk_python-0.1.0/examples/test-env/docker-compose.yml +95 -0
  12. frugal_sdk_python-0.1.0/examples/test-env/grafana/dashboards/frugal-metrics.json +290 -0
  13. frugal_sdk_python-0.1.0/examples/test-env/grafana/provisioning/dashboards/frugal.yml +12 -0
  14. frugal_sdk_python-0.1.0/examples/test-env/grafana/provisioning/datasources/prometheus.yml +10 -0
  15. frugal_sdk_python-0.1.0/examples/test-env/mockllm/Dockerfile +9 -0
  16. frugal_sdk_python-0.1.0/examples/test-env/mockllm/package.json +12 -0
  17. frugal_sdk_python-0.1.0/examples/test-env/mockllm/src/server.js +179 -0
  18. frugal_sdk_python-0.1.0/examples/test-env/prometheus/consoles/index.html.example +30 -0
  19. frugal_sdk_python-0.1.0/examples/test-env/prometheus/consoles/models.html +69 -0
  20. frugal_sdk_python-0.1.0/examples/test-env/prometheus/consoles/overview.html +57 -0
  21. frugal_sdk_python-0.1.0/examples/test-env/prometheus/consoles/sites.html +67 -0
  22. frugal_sdk_python-0.1.0/examples/test-env/prometheus/prometheus.yml +8 -0
  23. frugal_sdk_python-0.1.0/examples/test-env/sample-app/Dockerfile +23 -0
  24. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/__init__.py +0 -0
  25. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/clients.py +34 -0
  26. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/__init__.py +0 -0
  27. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/anon.py +18 -0
  28. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/classify.py +21 -0
  29. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/deferred.py +25 -0
  30. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/fail.py +30 -0
  31. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/pipeline.py +18 -0
  32. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/summarize.py +59 -0
  33. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/translate.py +18 -0
  34. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/via_blocked_lib.py +13 -0
  35. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/handlers/via_unblocked_lib.py +13 -0
  36. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/internal_lib/__init__.py +0 -0
  37. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/internal_lib/ai_helper.py +16 -0
  38. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/main.py +90 -0
  39. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/sibling_lib/__init__.py +0 -0
  40. frugal_sdk_python-0.1.0/examples/test-env/sample-app/app/sibling_lib/ai_helper.py +15 -0
  41. frugal_sdk_python-0.1.0/examples/test-env/sample-app/pyproject.toml +13 -0
  42. frugal_sdk_python-0.1.0/examples/test-env/sample-app/requirements.txt +13 -0
  43. frugal_sdk_python-0.1.0/examples/test-env/scripts/verify.sh +148 -0
  44. frugal_sdk_python-0.1.0/pyproject.toml +57 -0
  45. frugal_sdk_python-0.1.0/src/frugal_metrics/__init__.py +13 -0
  46. frugal_sdk_python-0.1.0/src/frugal_metrics/block_hash_lru.py +75 -0
  47. frugal_sdk_python-0.1.0/src/frugal_metrics/caller.py +213 -0
  48. frugal_sdk_python-0.1.0/src/frugal_metrics/config.py +231 -0
  49. frugal_sdk_python-0.1.0/src/frugal_metrics/instrument.py +268 -0
  50. frugal_sdk_python-0.1.0/src/frugal_metrics/otel.py +321 -0
  51. frugal_sdk_python-0.1.0/src/frugal_metrics/prompt_analyzer.py +273 -0
  52. frugal_sdk_python-0.1.0/src/frugal_metrics/safe.py +34 -0
  53. frugal_sdk_python-0.1.0/src/frugal_metrics/semconv.py +70 -0
  54. frugal_sdk_python-0.1.0/src/frugal_metrics/streams.py +172 -0
  55. frugal_sdk_python-0.1.0/src/frugal_metrics/wrappers/__init__.py +1 -0
  56. frugal_sdk_python-0.1.0/src/frugal_metrics/wrappers/anthropic.py +277 -0
  57. frugal_sdk_python-0.1.0/src/frugal_metrics/wrappers/bedrock.py +358 -0
  58. frugal_sdk_python-0.1.0/src/frugal_metrics/wrappers/bedrock_models.py +430 -0
  59. frugal_sdk_python-0.1.0/src/frugal_metrics/wrappers/openai.py +465 -0
  60. frugal_sdk_python-0.1.0/tests/__init__.py +0 -0
  61. frugal_sdk_python-0.1.0/tests/conftest.py +152 -0
  62. frugal_sdk_python-0.1.0/tests/test_bedrock_models.py +324 -0
  63. frugal_sdk_python-0.1.0/tests/test_block_hash_lru.py +48 -0
  64. frugal_sdk_python-0.1.0/tests/test_caller.py +158 -0
  65. frugal_sdk_python-0.1.0/tests/test_caller_edge_cases.py +270 -0
  66. frugal_sdk_python-0.1.0/tests/test_config.py +163 -0
  67. frugal_sdk_python-0.1.0/tests/test_prompt_analyzer.py +203 -0
  68. frugal_sdk_python-0.1.0/tests/test_wrap_anthropic.py +252 -0
  69. frugal_sdk_python-0.1.0/tests/test_wrap_bedrock.py +401 -0
  70. frugal_sdk_python-0.1.0/tests/test_wrap_openai.py +381 -0
  71. frugal_sdk_python-0.1.0/tests/test_wrap_openai_analyzer.py +188 -0
@@ -0,0 +1,63 @@
1
+ name: CD
2
+
3
+ on:
4
+ pull_request:
5
+ release:
6
+ types: [published]
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ build:
13
+ name: Build Python distribution
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - name: Check out repository
17
+ uses: actions/checkout@v4
18
+ with:
19
+ fetch-depth: 0
20
+ - name: Set up Python
21
+ uses: actions/setup-python@v5
22
+ with:
23
+ python-version: "3.12"
24
+ - name: Install build tooling
25
+ run: python -m pip install --upgrade build twine hatchling hatch-vcs
26
+ - name: Install test dependencies
27
+ run: python -m pip install -e '.[dev]'
28
+ - name: Check REUSE compliance
29
+ run: python -m reuse lint
30
+ - name: Run tests
31
+ run: python -m pytest
32
+ - name: Show package version
33
+ run: python -m hatchling version
34
+ - name: Build sdist and wheel
35
+ run: python -m build
36
+ - name: Check package metadata
37
+ run: python -m twine check dist/*
38
+ - name: Upload distributions
39
+ uses: actions/upload-artifact@v4
40
+ with:
41
+ name: python-distributions
42
+ path: dist/*
43
+ if-no-files-found: error
44
+
45
+ publish:
46
+ name: Publish to PyPI
47
+ runs-on: ubuntu-latest
48
+ needs: build
49
+ if: github.event_name == 'release' && github.event.action == 'published'
50
+ permissions:
51
+ contents: read
52
+ id-token: write
53
+ environment:
54
+ name: pypi
55
+ url: https://pypi.org/project/frugal-sdk-python/
56
+ steps:
57
+ - name: Download distributions
58
+ uses: actions/download-artifact@v4
59
+ with:
60
+ name: python-distributions
61
+ path: dist/
62
+ - name: Publish distributions
63
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,94 @@
1
+ # ---------------------------------------------------------------------------
2
+ # Python
3
+ # ---------------------------------------------------------------------------
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+ *.so
8
+
9
+ # Distribution / build artifacts
10
+ build/
11
+ dist/
12
+ *.egg-info/
13
+ *.egg
14
+ .eggs/
15
+ wheels/
16
+ pip-wheel-metadata/
17
+ share/python-wheels/
18
+ MANIFEST
19
+
20
+ # Virtual environments
21
+ .venv/
22
+ venv/
23
+ env/
24
+ .env/
25
+ ENV/
26
+ env.bak/
27
+ venv.bak/
28
+
29
+ # Installer logs
30
+ pip-log.txt
31
+ pip-delete-this-directory.txt
32
+
33
+ # Testing / coverage
34
+ .pytest_cache/
35
+ .cache/
36
+ .coverage
37
+ .coverage.*
38
+ htmlcov/
39
+ .tox/
40
+ .nox/
41
+ coverage.xml
42
+ *.cover
43
+ *.py,cover
44
+ .hypothesis/
45
+
46
+ # Type checkers
47
+ .mypy_cache/
48
+ .dmypy.json
49
+ dmypy.json
50
+ .pyre/
51
+ .pytype/
52
+ .ruff_cache/
53
+
54
+ # Jupyter
55
+ .ipynb_checkpoints/
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Environment / secrets
59
+ # ---------------------------------------------------------------------------
60
+ .env
61
+ .env.*
62
+ !.env.example
63
+ !.env.sample
64
+
65
+ # ---------------------------------------------------------------------------
66
+ # Editors / IDEs
67
+ # ---------------------------------------------------------------------------
68
+ .idea/
69
+ .vscode/
70
+ *.swp
71
+ *.swo
72
+ *.swn
73
+ *~
74
+ .project
75
+ .classpath
76
+ .settings/
77
+
78
+ # ---------------------------------------------------------------------------
79
+ # OS
80
+ # ---------------------------------------------------------------------------
81
+ .DS_Store
82
+ .DS_Store?
83
+ ._*
84
+ .Spotlight-V100
85
+ .Trashes
86
+ ehthumbs.db
87
+ Thumbs.db
88
+ Desktop.ini
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Tooling
92
+ # ---------------------------------------------------------------------------
93
+ .direnv/
94
+ .tool-versions.local
@@ -0,0 +1,187 @@
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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty percent
20
+ (50%) or more of the outstanding shares, or (iii) beneficial ownership of
21
+ such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ 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 source, and
28
+ configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation or
31
+ translation of a Source form, including but not limited to compiled object
32
+ code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that is
36
+ included in or attached to the work (an example is provided in the Appendix
37
+ below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
40
+ is based on (or derived from) the Work and for which the editorial revisions,
41
+ annotations, elaborations, or other modifications represent, as a whole, an
42
+ original work of authorship. For the purposes of this License, Derivative
43
+ Works shall not include works that remain separable from, or merely link (or
44
+ bind by name) to the interfaces of, the Work and Derivative Works thereof.
45
+
46
+ "Contribution" shall mean any work of authorship, including the original
47
+ version of the Work and any modifications or additions to that Work or
48
+ Derivative Works thereof, that is intentionally submitted to Licensor for
49
+ inclusion in the Work by the copyright owner or by an individual or Legal
50
+ Entity authorized to submit on behalf of the copyright owner. For the purposes
51
+ of this definition, "submitted" means any form of electronic, verbal, or
52
+ written communication sent to the Licensor or its representatives, including
53
+ but not limited to communication on electronic mailing lists, source code
54
+ control systems, and issue tracking systems that are managed by, or on behalf
55
+ of, the Licensor for the purpose of discussing and improving the Work, but
56
+ excluding communication that is conspicuously marked or otherwise designated
57
+ in writing by the copyright owner as "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
60
+ of whom a Contribution has been received by Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
64
+ License, each Contributor hereby grants to You a perpetual, worldwide,
65
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
66
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
67
+ sublicense, and distribute the Work and such Derivative Works in Source or
68
+ Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of this
71
+ License, each Contributor hereby grants to You a perpetual, worldwide,
72
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
73
+ section) patent license to make, have made, use, offer to sell, sell, import,
74
+ and otherwise transfer the Work, where such license applies only to those
75
+ patent claims licensable by such Contributor that are necessarily infringed by
76
+ their Contribution(s) alone or by combination of their Contribution(s) with the
77
+ Work to which such Contribution(s) was submitted. If You institute patent
78
+ litigation against any entity (including a cross-claim or counterclaim in a
79
+ lawsuit) alleging that the Work or a Contribution incorporated within the Work
80
+ constitutes direct or contributory patent infringement, then any patent
81
+ licenses granted to You under this License for that Work shall terminate as of
82
+ the date such litigation is filed.
83
+
84
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
85
+ Derivative Works thereof in any medium, with or without modifications, and in
86
+ Source or Object form, provided that You meet the following conditions:
87
+
88
+ (a) You must give any other recipients of the Work or Derivative Works a
89
+ copy of this License; and
90
+
91
+ (b) You must cause any modified files to carry prominent notices stating
92
+ that You changed the files; and
93
+
94
+ (c) You must retain, in the Source form of any Derivative Works that You
95
+ distribute, all copyright, patent, trademark, and attribution notices
96
+ from the Source form of the Work, excluding those notices that do not
97
+ pertain to any part of the Derivative Works; and
98
+
99
+ (d) If the Work includes a "NOTICE" text file as part of its distribution,
100
+ then any Derivative Works that You distribute must include a readable
101
+ copy of the attribution notices contained within such NOTICE file,
102
+ excluding those notices that do not pertain to any part of the
103
+ Derivative Works, in at least one of the following places: within a
104
+ NOTICE text file distributed as part of the Derivative Works; within the
105
+ Source form or documentation, if provided along with the Derivative
106
+ Works; or, within a display generated by the Derivative Works, if and
107
+ wherever such third-party notices normally appear. The contents of the
108
+ NOTICE file are for informational purposes only and do not modify the
109
+ License. You may add Your own attribution notices within Derivative
110
+ Works that You distribute, alongside or as an addendum to the NOTICE
111
+ text from the Work, provided that such additional attribution notices
112
+ cannot be construed as modifying the License.
113
+
114
+ You may add Your own copyright statement to Your modifications and may
115
+ provide additional or different license terms and conditions for use,
116
+ reproduction, or distribution of Your modifications, or for any such
117
+ Derivative Works as a whole, provided Your use, reproduction, and
118
+ distribution of the Work otherwise complies with the conditions stated in
119
+ this License.
120
+
121
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
122
+ Contribution intentionally submitted for inclusion in the Work by You to the
123
+ Licensor shall be under the terms and conditions of this License, without any
124
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
125
+ supersede or modify the terms of any separate license agreement you may have
126
+ executed with Licensor regarding such Contributions.
127
+
128
+ 6. Trademarks. This License does not grant permission to use the trade names,
129
+ trademarks, service marks, or product names of the Licensor, except as required
130
+ for reasonable and customary use in describing the origin of the Work and
131
+ reproducing the content of the NOTICE file.
132
+
133
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
134
+ writing, Licensor provides the Work (and each Contributor provides its
135
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
136
+ KIND, either express or implied, including, without limitation, any warranties
137
+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
138
+ PARTICULAR PURPOSE. You are solely responsible for determining the
139
+ appropriateness of using or redistributing the Work and assume any risks
140
+ associated with Your exercise of permissions under this License.
141
+
142
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
143
+ tort (including negligence), contract, or otherwise, unless required by
144
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
145
+ writing, shall any Contributor be liable to You for damages, including any
146
+ direct, indirect, special, incidental, or consequential damages of any
147
+ character arising as a result of this License or out of the use or inability
148
+ to use the Work (including but not limited to damages for loss of goodwill,
149
+ work stoppage, computer failure or malfunction, or any and all other
150
+ commercial damages or losses), even if such Contributor has been advised of
151
+ the possibility of such damages.
152
+
153
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
154
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
155
+ acceptance of support, warranty, indemnity, or other liability obligations
156
+ and/or rights consistent with this License. However, in accepting such
157
+ obligations, You may act only on Your own behalf and on Your sole
158
+ responsibility, not on behalf of any other Contributor, and only if You agree
159
+ to indemnify, defend, and hold each Contributor harmless for any liability
160
+ incurred by, or claims asserted against, such Contributor by reason of your
161
+ accepting any such warranty or additional liability.
162
+
163
+ END OF TERMS AND CONDITIONS
164
+
165
+ APPENDIX: How to apply the Apache License to your work.
166
+
167
+ To apply the Apache License to your work, attach the following boilerplate
168
+ notice, with the fields enclosed by brackets "[]" replaced with your own
169
+ identifying information. (Don't include the brackets!) The text should be
170
+ enclosed in the appropriate comment syntax for the file format. We also
171
+ recommend that a file or class name and description of purpose be included on
172
+ the same "printed page" as the copyright notice for easier identification
173
+ within third-party archives.
174
+
175
+ Copyright [yyyy] [name of copyright owner]
176
+
177
+ Licensed under the Apache License, Version 2.0 (the "License");
178
+ you may not use this file except in compliance with the License.
179
+ You may obtain a copy of the License at
180
+
181
+ http://www.apache.org/licenses/LICENSE-2.0
182
+
183
+ Unless required by applicable law or agreed to in writing, software
184
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
185
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
186
+ License for the specific language governing permissions and limitations
187
+ under the License.
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.4
2
+ Name: frugal-sdk-python
3
+ Version: 0.1.0
4
+ Summary: Instrumentation for Cost-to-Code attribution.
5
+ Project-URL: Homepage, https://frugal.co
6
+ Author: Frugal AI Inc.
7
+ License: Apache-2.0
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: opentelemetry-api>=1.25.0
16
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.25.0
17
+ Requires-Dist: opentelemetry-sdk>=1.25.0
18
+ Provides-Extra: anthropic
19
+ Requires-Dist: anthropic>=0.34.0; extra == 'anthropic'
20
+ Provides-Extra: dev
21
+ Requires-Dist: anthropic>=0.34.0; extra == 'dev'
22
+ Requires-Dist: openai>=1.40.0; extra == 'dev'
23
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
24
+ Requires-Dist: pytest>=8.0; extra == 'dev'
25
+ Requires-Dist: reuse[charset-normalizer]>=5.0; extra == 'dev'
26
+ Provides-Extra: openai
27
+ Requires-Dist: openai>=1.40.0; extra == 'openai'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # Frugal SDK for Python
31
+
32
+ Instrument AI API calls with one line of code. Get per-call-site metrics — token usage, latency, call counts — exported via OpenTelemetry to any collector.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install frugal-sdk-python
38
+
39
+ # Plus whichever provider SDKs you use:
40
+ pip install openai anthropic
41
+ ```
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ from frugal_metrics import wrap_openai, wrap_anthropic, wrap_bedrock
47
+ from openai import OpenAI
48
+ from anthropic import Anthropic
49
+ import boto3
50
+
51
+ client = wrap_openai(OpenAI())
52
+ anthropic_client = wrap_anthropic(Anthropic())
53
+ bedrock_client = wrap_bedrock(boto3.client("bedrock-runtime", region_name="us-west-2"))
54
+
55
+ # Every call now emits metrics — no other code changes needed
56
+ response = client.chat.completions.create(model="gpt-4o", messages=[...])
57
+ ```
58
+
59
+ ## Configuration
60
+
61
+ All configuration is via environment variables. No `init()` call, no configuration objects.
62
+
63
+ ### Required
64
+
65
+ Set both or the wrapper silently returns the client unmodified:
66
+
67
+ | Variable | Purpose |
68
+ | ------------------- | ---------------------------------------------------------- |
69
+ | `FRUGAL_API_KEY` | Per-customer bearer token issued by Frugal. Builds the export `Authorization` header. (Or supply the bearer yourself via `FRUGAL_OTEL_EXPORTER_OTLP_HEADERS`.) |
70
+ | `FRUGAL_PROJECT_ID` | The Frugal project this deployment belongs to. Stats are attributed per project, so the same repo across microservices no longer collides. |
71
+
72
+ ### Optional
73
+
74
+ | Variable | Purpose |
75
+ | ---------------------------------------- | --------------------------------------------------------------------------------------- |
76
+ | `FRUGAL_CUSTOMER_ID` | Customer ID issued by Frugal. When unset, the tenant label (auto-injected server-side by VMAuth from the bearer token) identifies the customer and `frugal.customer_id` is omitted. |
77
+ | `FRUGAL_REPO_ROOT` | Absolute path to the source root; the strip prefix for `caller_file`. Defaults to the process working directory. |
78
+ | `FRUGAL_OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector URL for Frugal metrics. Defaults to `https://metrics.frugal.co/opentelemetry/v1/metrics`. Falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`. |
79
+ | `FRUGAL_OTEL_EXPORTER_OTLP_HEADERS` | Export auth headers (e.g. `Authorization=Bearer ...`). Overrides the header built from `FRUGAL_API_KEY`. Falls back to `OTEL_EXPORTER_OTLP_HEADERS`. |
80
+ | `FRUGAL_COMPONENTS` | Comma-separated logical components (e.g. `ai-handler,reco`). When set, each metric is ALSO emitted once per component (tagged `frugal.component`) on top of the base project series, so usage can be viewed for the whole project or split by component. |
81
+ | `FRUGAL_PATH_BLOCK_LIST` | Comma-separated repo-relative paths to skip for caller attribution (see below). |
82
+ | `FRUGAL_METRIC_EXPORT_INTERVAL_MS` | Export cadence in milliseconds. Default `60000`. |
83
+ | `FRUGAL_MAX_CALL_SITES` | Cardinality cap — max distinct `(caller_file, caller_function)` pairs to attribute. Default `500`. Set to `0` to disable. |
84
+ | `FRUGAL_PROMPT_ANALYSIS_SAMPLE_RATE` | Fraction of calls (0..1) that run the lightweight prompt analyzer. Default `0.1`. Set to `0` to disable, `1` for every call. |
85
+ | `FRUGAL_DISABLED` | Set to `1` to disable all instrumentation without uninstalling. |
86
+
87
+ ## What gets captured
88
+
89
+ Every wrapped call emits OTel metrics tagged with the caller's source file and function, the provider, and the model:
90
+
91
+ | Metric | Kind | Description | Additional attributes |
92
+ | --------------------------------------- | --------- | ------------------------------------------------------------ | -------------------------------------- |
93
+ | `gen_ai.client.operation.duration` | histogram | Call latency in seconds | — |
94
+ | `gen_ai.client.token.usage` | histogram | Input and output token counts | `gen_ai.token.type` |
95
+ | `frugal.gen_ai.calls` | counter | Number of calls per site | — |
96
+ | `frugal.gen_ai.cache_read_tokens` | histogram | Prompt cache hits | — |
97
+ | `frugal.gen_ai.cache_write_tokens` | histogram | Prompt cache writes | — |
98
+ | `frugal.gen_ai.reasoning_tokens` | histogram | OpenAI reasoning tokens (o-series), Anthropic thinking tokens| — |
99
+ | `frugal.gen_ai.errors` | counter | Errors by exception type | `frugal.error.type` |
100
+ | `frugal.gen_ai.internal_errors` | counter | frugal-metrics internal failures (cardinality cap, bugs) | `frugal.internal_error.stage` |
101
+ | `frugal.gen_ai.output_cap_utilization` | histogram | `output_tokens / max_tokens` ratio when `max_tokens` is set | `frugal.structured_output_mode` |
102
+ | `frugal.gen_ai.history_depth` | histogram | `messages.length` (analyzer-sampled) | — |
103
+ | `frugal.gen_ai.few_shot_count` | histogram | Few-shot exemplar pairs before final user (analyzer-sampled) | — |
104
+ | `frugal.gen_ai.noise_ratio` | histogram | HTML/base64/whitespace fraction of input (analyzer-sampled) | — |
105
+ | `frugal.gen_ai.cache_prefix_stable` | counter | Per-block prompt-cache stability (analyzer-sampled) | `frugal.block`, `frugal.stable` |
106
+ | `frugal.gen_ai.structured_output_hint` | counter | "Return JSON" prompts missing `response_format`/`tools` | — |
107
+
108
+ The bottom block of analyzer-sampled metrics fires on a fraction of calls
109
+ (`FRUGAL_PROMPT_ANALYSIS_SAMPLE_RATE`, default 10%); the token-side metrics are
110
+ 100% — never sampled.
111
+
112
+ Every metric carries this base attribute set:
113
+
114
+ - `frugal.project_id` — from your env vars (`frugal.customer_id` too when set); `frugal.component` is added on the per-component series when `FRUGAL_COMPONENTS` is set
115
+ - `frugal.caller_file`, `frugal.caller_function` — auto-detected from the call stack
116
+ - `gen_ai.system` — `openai`, `anthropic`, `aws.bedrock`, or `vertex_ai`
117
+ - `gen_ai.request.model`, `gen_ai.response.model` — the model used
118
+ - `gen_ai.operation.name` — `chat`, `text_completion`, or `embeddings`
119
+ - `frugal.batched` — `true` for batch-API submissions, `false` otherwise
120
+
121
+ The "Additional attributes" column above lists what each metric carries on top of the base set. See [`docs/metrics-reference.md`](docs/metrics-reference.md) for the values each attribute takes, sentinel values for caller fields, and the full internal-error-stage list.
122
+
123
+ Metrics are aggregated per export interval (not sent per call), so network overhead is minimal regardless of call volume.
124
+
125
+ ## Supported providers
126
+
127
+ | Provider | Usage |
128
+ | ---------------------------------------------- | ------------------------------------------------------ |
129
+ | OpenAI | `wrap_openai(OpenAI())` |
130
+ | Anthropic | `wrap_anthropic(Anthropic())` |
131
+ | Claude on AWS Bedrock (via Anthropic SDK) | `wrap_anthropic(AnthropicBedrock())` |
132
+ | AWS Bedrock — any model, AWS SDKs directly | `wrap_bedrock(boto3.client("bedrock-runtime"))` |
133
+ | Claude on Google Vertex | `wrap_anthropic(AnthropicVertex())` |
134
+
135
+ `wrap_bedrock` covers all four `bedrock-runtime` operations (`invoke_model`,
136
+ `invoke_model_with_response_stream`, `converse`, `converse_stream`) across
137
+ every model on Bedrock — Anthropic, OpenAI gpt-oss, Amazon Nova, Meta Llama,
138
+ Mistral, Cohere, AI21, DeepSeek, Qwen, Kimi, etc. Cross-region inference
139
+ profile prefixes (`us.`, `eu.`, `jp.`, `apac.`, `au.`, `global.`) are
140
+ preserved in `gen_ai.request.model`. Async clients (`aiobotocore` /
141
+ `aioboto3`) are detected automatically. See [`docs/quickstart.md`](docs/quickstart.md#native-aws-bedrock-wrap_bedrock) for the full Bedrock walkthrough.
142
+
143
+ ## Streaming
144
+
145
+ Streaming works with no extra setup. The wrapper returns a drop-in replacement that passes events through and emits metrics when the stream finishes.
146
+
147
+ ```python
148
+ # OpenAI — opt in to include_usage for token counts in streams
149
+ stream = client.chat.completions.create(
150
+ model="gpt-4o",
151
+ messages=[...],
152
+ stream=True,
153
+ stream_options={"include_usage": True},
154
+ )
155
+ for chunk in stream:
156
+ ...
157
+
158
+ # Anthropic — token counts available natively, no opt-in needed
159
+ stream = anthropic_client.messages.create(
160
+ model="claude-sonnet-4-20250514",
161
+ max_tokens=1024,
162
+ messages=[...],
163
+ stream=True,
164
+ )
165
+ for event in stream:
166
+ ...
167
+ ```
168
+
169
+ ## Internal library attribution
170
+
171
+ If your code calls an internal helper library that wraps the AI SDK (e.g. `acme_ai_helpers`), add it to the block list so attribution lands on your business code:
172
+
173
+ ```bash
174
+ FRUGAL_PATH_BLOCK_LIST="src/acme_ai_helpers,libs/llm_utils"
175
+ ```
176
+
177
+ ## Safety guarantees
178
+
179
+ - If any required env var is unset, `wrap_openai` / `wrap_anthropic` return the client completely unmodified with zero overhead.
180
+ - If any part of our instrumentation fails at runtime (OTel init, stack walking, metric emission), the original SDK call executes normally. We never raise our own exceptions into your code.
181
+ - Wrapping is idempotent — calling `wrap_openai(client)` twice on the same client is safe.
182
+
183
+ ## Verifying the setup
184
+
185
+ Set the OTLP endpoint to empty to print metrics to the console instead of exporting them:
186
+
187
+ ```bash
188
+ export FRUGAL_API_KEY=local
189
+ export FRUGAL_PROJECT_ID=my-project
190
+ export FRUGAL_OTEL_EXPORTER_OTLP_ENDPOINT= # empty → ConsoleMetricExporter
191
+ export FRUGAL_METRIC_EXPORT_INTERVAL_MS=5000
192
+ python my_script.py
193
+ ```
194
+
195
+ You should see JSON metric records with `gen_ai.*` and `frugal.*` attributes every 5 seconds.