@frugalco/frugal-sdk-node 0.1.0

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 (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +227 -0
  3. package/dist/block-hash-lru.d.ts +18 -0
  4. package/dist/block-hash-lru.d.ts.map +1 -0
  5. package/dist/block-hash-lru.js +48 -0
  6. package/dist/block-hash-lru.js.map +1 -0
  7. package/dist/caller.d.ts +23 -0
  8. package/dist/caller.d.ts.map +1 -0
  9. package/dist/caller.js +204 -0
  10. package/dist/caller.js.map +1 -0
  11. package/dist/config.d.ts +21 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +165 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/index.d.ts +6 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +5 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/instrument.d.ts +49 -0
  20. package/dist/instrument.d.ts.map +1 -0
  21. package/dist/instrument.js +194 -0
  22. package/dist/instrument.js.map +1 -0
  23. package/dist/otel.d.ts +27 -0
  24. package/dist/otel.d.ts.map +1 -0
  25. package/dist/otel.js +211 -0
  26. package/dist/otel.js.map +1 -0
  27. package/dist/prompt-analyzer.d.ts +26 -0
  28. package/dist/prompt-analyzer.d.ts.map +1 -0
  29. package/dist/prompt-analyzer.js +210 -0
  30. package/dist/prompt-analyzer.js.map +1 -0
  31. package/dist/semconv.d.ts +52 -0
  32. package/dist/semconv.d.ts.map +1 -0
  33. package/dist/semconv.js +53 -0
  34. package/dist/semconv.js.map +1 -0
  35. package/dist/streams.d.ts +21 -0
  36. package/dist/streams.d.ts.map +1 -0
  37. package/dist/streams.js +85 -0
  38. package/dist/streams.js.map +1 -0
  39. package/dist/track.d.ts +44 -0
  40. package/dist/track.d.ts.map +1 -0
  41. package/dist/track.js +170 -0
  42. package/dist/track.js.map +1 -0
  43. package/dist/wrappers/anthropic.d.ts +2 -0
  44. package/dist/wrappers/anthropic.d.ts.map +1 -0
  45. package/dist/wrappers/anthropic.js +229 -0
  46. package/dist/wrappers/anthropic.js.map +1 -0
  47. package/dist/wrappers/bedrock-models.d.ts +26 -0
  48. package/dist/wrappers/bedrock-models.d.ts.map +1 -0
  49. package/dist/wrappers/bedrock-models.js +320 -0
  50. package/dist/wrappers/bedrock-models.js.map +1 -0
  51. package/dist/wrappers/bedrock.d.ts +2 -0
  52. package/dist/wrappers/bedrock.d.ts.map +1 -0
  53. package/dist/wrappers/bedrock.js +284 -0
  54. package/dist/wrappers/bedrock.js.map +1 -0
  55. package/dist/wrappers/openai.d.ts +2 -0
  56. package/dist/wrappers/openai.d.ts.map +1 -0
  57. package/dist/wrappers/openai.js +347 -0
  58. package/dist/wrappers/openai.js.map +1 -0
  59. package/package.json +60 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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.
package/README.md ADDED
@@ -0,0 +1,227 @@
1
+ # Frugal SDK for Node
2
+
3
+ Instrument your AI API calls with one line of code. Get per-call-site metrics — token usage, latency, call counts — exported via OpenTelemetry to any collector.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @frugalco/frugal-sdk-node
9
+
10
+ # Plus whichever provider SDKs you use (peer dependencies):
11
+ npm install openai @anthropic-ai/sdk
12
+ ```
13
+
14
+ Requires Node.js 18+.
15
+
16
+ ## Quick start
17
+
18
+ ```ts
19
+ import { wrapOpenAI, wrapAnthropic, wrapBedrock } from "@frugalco/frugal-sdk-node";
20
+ import OpenAI from "openai";
21
+ import Anthropic from "@anthropic-ai/sdk";
22
+ import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
23
+
24
+ const openai = wrapOpenAI(new OpenAI());
25
+ const anthropic = wrapAnthropic(new Anthropic());
26
+ const bedrock = wrapBedrock(new BedrockRuntimeClient({ region: "us-west-2" }));
27
+
28
+ // Every call now emits metrics — no other code changes needed
29
+ const response = await openai.chat.completions.create({
30
+ model: "gpt-4o",
31
+ messages: [...],
32
+ });
33
+ ```
34
+
35
+ ## Configuration
36
+
37
+ All configuration is via environment variables. No `init()` call, no config objects.
38
+
39
+ ### Required
40
+
41
+ Set both or the wrapper silently returns the client unmodified:
42
+
43
+ | Variable | Purpose |
44
+ | ------------------- | ---------------------------------------------------------- |
45
+ | `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`.) |
46
+ | `FRUGAL_PROJECT_ID` | The Frugal project this deployment belongs to. Stats are attributed per project, so the same repo across microservices no longer collides. |
47
+
48
+ ### Optional
49
+
50
+ | Variable | Purpose |
51
+ | ---------------------------------------- | --------------------------------------------------------------------------------------- |
52
+ | `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. |
53
+ | `FRUGAL_REPO_ROOT` | Absolute path to the source root; the strip prefix for `caller_file`. Defaults to the process working directory. |
54
+ | `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`. |
55
+ | `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`. |
56
+ | `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. |
57
+ | `FRUGAL_PATH_BLOCK_LIST` | Comma-separated repo-relative paths to skip for caller attribution (see below). |
58
+ | `FRUGAL_METRIC_EXPORT_INTERVAL_MS` | Export cadence in milliseconds. Default `60000`. |
59
+ | `FRUGAL_MAX_CALL_SITES` | Cardinality cap — max distinct `(caller_file, caller_function)` pairs to attribute. Default `500`. Set to `0` to disable. |
60
+ | `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. |
61
+ | `FRUGAL_DISABLED` | Set to `1` to disable all instrumentation without uninstalling. |
62
+
63
+ ## What gets captured
64
+
65
+ Every wrapped call emits OTel metrics tagged with the caller's source file and function, the provider, and the model:
66
+
67
+ | Metric | Kind | Description | Additional attributes |
68
+ | --------------------------------------- | --------- | ------------------------------------------------------------ | -------------------------------------- |
69
+ | `gen_ai.client.operation.duration` | histogram | Call latency in seconds | — |
70
+ | `gen_ai.client.token.usage` | histogram | Input and output token counts | `gen_ai.token.type` |
71
+ | `frugal.gen_ai.calls` | counter | Number of calls per site | — |
72
+ | `frugal.gen_ai.cache_read_tokens` | histogram | Prompt cache hits | — |
73
+ | `frugal.gen_ai.cache_write_tokens` | histogram | Prompt cache writes | — |
74
+ | `frugal.gen_ai.reasoning_tokens` | histogram | OpenAI reasoning tokens (o-series), Anthropic thinking tokens| — |
75
+ | `frugal.gen_ai.errors` | counter | Errors by exception type | `frugal.error.type` |
76
+ | `frugal.gen_ai.internal_errors` | counter | frugal-metrics internal failures (cardinality cap, bugs) | `frugal.internal_error.stage` |
77
+ | `frugal.gen_ai.output_cap_utilization` | histogram | `output_tokens / max_tokens` ratio when `max_tokens` is set | `frugal.structured_output_mode` |
78
+ | `frugal.gen_ai.history_depth` | histogram | `messages.length` (analyzer-sampled) | — |
79
+ | `frugal.gen_ai.few_shot_count` | histogram | Few-shot exemplar pairs before final user (analyzer-sampled) | — |
80
+ | `frugal.gen_ai.noise_ratio` | histogram | HTML/base64/whitespace fraction of input (analyzer-sampled) | — |
81
+ | `frugal.gen_ai.cache_prefix_stable` | counter | Per-block prompt-cache stability (analyzer-sampled) | `frugal.block`, `frugal.stable` |
82
+ | `frugal.gen_ai.structured_output_hint` | counter | "Return JSON" prompts missing `response_format`/`tools` | — |
83
+
84
+ The bottom block of analyzer-sampled metrics fires on a fraction of calls
85
+ (`FRUGAL_PROMPT_ANALYSIS_SAMPLE_RATE`, default 10%); the token-side metrics are
86
+ 100% — never sampled.
87
+
88
+ Every metric carries this base attribute set:
89
+
90
+ - `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
91
+ - `frugal.caller_file`, `frugal.caller_function` — auto-detected from the call stack
92
+ - `gen_ai.system` — `openai`, `anthropic`, `aws.bedrock`, `vertex_ai`, or `custom` (the default for hand-instrumented call sites; override via the `provider` field)
93
+ - `gen_ai.request.model`, `gen_ai.response.model` — the model used
94
+ - `gen_ai.operation.name` — `chat`, `text_completion`, or `embeddings`
95
+ - `frugal.batched` — `true` for batch-API submissions, `false` otherwise
96
+
97
+ 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.
98
+
99
+ Metrics are aggregated per export interval (not sent per call), so network overhead is minimal regardless of call volume.
100
+
101
+ ## Supported providers
102
+
103
+ | Provider | Usage |
104
+ | ---------------------------------------------- | -------------------------------------------------------------- |
105
+ | OpenAI | `wrapOpenAI(new OpenAI())` |
106
+ | Anthropic | `wrapAnthropic(new Anthropic())` |
107
+ | Claude on AWS Bedrock (via Anthropic SDK) | `wrapAnthropic(new AnthropicBedrock())` |
108
+ | AWS Bedrock — any model, AWS SDKs directly | `wrapBedrock(new BedrockRuntimeClient({ region: "..." }))` |
109
+ | Claude on Google Vertex | `wrapAnthropic(new AnthropicVertex())` |
110
+
111
+ `wrapBedrock` covers all four `bedrock-runtime` commands (`InvokeModelCommand`,
112
+ `InvokeModelWithResponseStreamCommand`, `ConverseCommand`,
113
+ `ConverseStreamCommand`) across every model on Bedrock — Anthropic, OpenAI
114
+ gpt-oss, Amazon Nova, Meta Llama, Mistral, Cohere, AI21, DeepSeek, Qwen,
115
+ Kimi, etc. Cross-region inference profile prefixes (`us.`, `eu.`, `jp.`,
116
+ `apac.`, `au.`, `global.`) are preserved in `gen_ai.request.model`. See
117
+ [`docs/quickstart.md`](docs/quickstart.md#native-aws-bedrock-wrapbedrock) for the full Bedrock walkthrough.
118
+
119
+ ## Custom call sites
120
+
121
+ For AI calls that don't go through a wrapped client — a `fetch()` to a model gateway, a CLI shell-out, or an internal helper that returns raw usage — mark the call site yourself and feed in the usage you have. You get the same metrics and the same caller attribution as the auto-wrappers.
122
+
123
+ ```ts
124
+ import { trackAICall } from "@frugalco/frugal-sdk-node";
125
+
126
+ const answer = await trackAICall(
127
+ { provider: "anthropic", model: "claude-sonnet-4-20250514" },
128
+ async (report) => {
129
+ const res = await myCustomLlmCall(prompt);
130
+ report({
131
+ inputTokens: res.usage.input_tokens,
132
+ outputTokens: res.usage.output_tokens,
133
+ responseModel: res.model,
134
+ });
135
+ return res.text;
136
+ },
137
+ );
138
+ ```
139
+
140
+ `trackAICall(info, fn)` runs `fn`, times it, and emits metrics when it finishes — or an error metric if `fn` throws (the original return value and any error always pass through untouched). Works with sync or `async` callbacks. Call `report(usage)` with whatever token counts you have once the response is back; if you never call it, you still get a call-count and latency point.
141
+
142
+ For calls that span function boundaries — where a single callback won't fit — use the manual handle:
143
+
144
+ ```ts
145
+ import { startAICall } from "@frugalco/frugal-sdk-node";
146
+
147
+ const call = startAICall({ provider: "anthropic", model: "claude-sonnet-4-20250514" });
148
+ try {
149
+ const res = await myCustomLlmCall(prompt);
150
+ call.end({
151
+ inputTokens: res.usage.input_tokens,
152
+ outputTokens: res.usage.output_tokens,
153
+ responseModel: res.model,
154
+ });
155
+ } catch (err) {
156
+ call.fail(err);
157
+ throw err;
158
+ }
159
+ ```
160
+
161
+ `end()` and `fail()` finalize the call exactly once and are idempotent — extra calls are ignored, so a `try/finally` that always calls `end()` won't double-count.
162
+
163
+ **Metadata** — `info` (all optional): `provider` (→ `gen_ai.system`, default `"custom"`), `operation` (default `"chat"`), `model` (→ `gen_ai.request.model`, default `"<unknown>"`). To also run the sampled prompt analyzer, pass any of `messages` / `system` / `tools` / `responseFormat` / `maxTokens`.
164
+
165
+ **Usage** — `report(...)` / `end(...)` fields (all optional): `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `responseModel`.
166
+
167
+ The same env-var configuration, safety guarantees, and exported metrics apply.
168
+
169
+ ## Streaming
170
+
171
+ Streaming works with no extra setup. The wrapper returns a drop-in async iterable that passes events through and emits metrics when the stream finishes.
172
+
173
+ ```ts
174
+ // OpenAI — opt in to include_usage for token counts in streams
175
+ const stream = await openai.chat.completions.create({
176
+ model: "gpt-4o",
177
+ messages: [...],
178
+ stream: true,
179
+ stream_options: { include_usage: true },
180
+ });
181
+ for await (const chunk of stream) {
182
+ // ...
183
+ }
184
+
185
+ // Anthropic — token counts available natively, no opt-in needed
186
+ const stream = await anthropic.messages.create({
187
+ model: "claude-sonnet-4-20250514",
188
+ max_tokens: 1024,
189
+ messages: [...],
190
+ stream: true,
191
+ });
192
+ for await (const event of stream) {
193
+ // ...
194
+ }
195
+ ```
196
+
197
+ ## Internal library attribution
198
+
199
+ 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:
200
+
201
+ ```bash
202
+ FRUGAL_PATH_BLOCK_LIST="src/acme-ai-helpers,libs/llm-utils"
203
+ ```
204
+
205
+ ## Safety guarantees
206
+
207
+ - If any required env var is unset, `wrapOpenAI` / `wrapAnthropic` return the client completely unmodified with zero overhead.
208
+ - If any part of our instrumentation fails at runtime (OTel init, stack walking, metric emission), the original SDK call executes normally. We never throw our own exceptions into your code.
209
+ - Wrapping is idempotent — calling `wrapOpenAI(client)` twice on the same client is safe.
210
+
211
+ ## Verifying the setup
212
+
213
+ Set the OTLP endpoint to empty to print metrics to the console instead of exporting them:
214
+
215
+ ```bash
216
+ export FRUGAL_API_KEY=local
217
+ export FRUGAL_PROJECT_ID=my-project
218
+ export FRUGAL_OTEL_EXPORTER_OTLP_ENDPOINT= # empty → ConsoleMetricExporter
219
+ export FRUGAL_METRIC_EXPORT_INTERVAL_MS=5000
220
+ node my_script.js
221
+ ```
222
+
223
+ You should see JSON metric records with `gen_ai.*` and `frugal.*` attributes every 5 seconds.
224
+
225
+ ## License
226
+
227
+ This project is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). A copy of the license is also included in the root of the installed package.
@@ -0,0 +1,18 @@
1
+ export interface BlockHashes {
2
+ systemHash: string | null;
3
+ userHash: string | null;
4
+ toolsHash: string | null;
5
+ schemaHash: string | null;
6
+ }
7
+ export declare class BlockHashLRU {
8
+ private readonly capacity;
9
+ private readonly map;
10
+ constructor(capacity?: number);
11
+ get(callSiteId: string): BlockHashes | undefined;
12
+ set(callSiteId: string, hashes: BlockHashes): void;
13
+ size(): number;
14
+ clear(): void;
15
+ }
16
+ export declare function getSharedBlockHashLRU(capacity?: number): BlockHashLRU;
17
+ export declare function resetSharedBlockHashLRUForTests(): void;
18
+ //# sourceMappingURL=block-hash-lru.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-hash-lru.d.ts","sourceRoot":"","sources":["../src/block-hash-lru.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,WAAW;IAC1B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,qBAAa,YAAY;IAGX,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAFrC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAkC;gBAEzB,QAAQ,GAAE,MAAY;IAEnD,GAAG,CAAC,UAAU,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS;IAQhD,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,IAAI;IAUlD,IAAI,IAAI,MAAM;IAId,KAAK,IAAI,IAAI;CAGd;AAID,wBAAgB,qBAAqB,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,YAAY,CAGrE;AAED,wBAAgB,+BAA+B,IAAI,IAAI,CAEtD"}
@@ -0,0 +1,48 @@
1
+ // Per-call-site LRU storing the previous call's block hashes. Used by the
2
+ // prompt analyzer to derive cache_prefix_stable signals without leaving raw
3
+ // hashes anywhere outside the process.
4
+ //
5
+ // Default capacity matches the existing call-site cardinality cap so a busy
6
+ // process can't blow memory by tracking thousands of distinct sites.
7
+ export class BlockHashLRU {
8
+ capacity;
9
+ map = new Map();
10
+ constructor(capacity = 500) {
11
+ this.capacity = capacity;
12
+ }
13
+ get(callSiteId) {
14
+ const entry = this.map.get(callSiteId);
15
+ if (entry === undefined)
16
+ return undefined;
17
+ this.map.delete(callSiteId);
18
+ this.map.set(callSiteId, entry);
19
+ return entry;
20
+ }
21
+ set(callSiteId, hashes) {
22
+ if (this.map.has(callSiteId)) {
23
+ this.map.delete(callSiteId);
24
+ }
25
+ else if (this.capacity > 0 && this.map.size >= this.capacity) {
26
+ const oldest = this.map.keys().next().value;
27
+ if (oldest !== undefined)
28
+ this.map.delete(oldest);
29
+ }
30
+ this.map.set(callSiteId, hashes);
31
+ }
32
+ size() {
33
+ return this.map.size;
34
+ }
35
+ clear() {
36
+ this.map.clear();
37
+ }
38
+ }
39
+ let shared = null;
40
+ export function getSharedBlockHashLRU(capacity) {
41
+ if (shared === null)
42
+ shared = new BlockHashLRU(capacity);
43
+ return shared;
44
+ }
45
+ export function resetSharedBlockHashLRUForTests() {
46
+ shared = null;
47
+ }
48
+ //# sourceMappingURL=block-hash-lru.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-hash-lru.js","sourceRoot":"","sources":["../src/block-hash-lru.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,4EAA4E;AAC5E,uCAAuC;AACvC,EAAE;AACF,4EAA4E;AAC5E,qEAAqE;AASrE,MAAM,OAAO,YAAY;IAGM;IAFZ,GAAG,GAAG,IAAI,GAAG,EAAuB,CAAC;IAEtD,YAA6B,WAAmB,GAAG;QAAtB,aAAQ,GAAR,QAAQ,CAAc;IAAG,CAAC;IAEvD,GAAG,CAAC,UAAkB;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACvC,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,SAAS,CAAC;QAC1C,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC5B,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;QAChC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,GAAG,CAAC,UAAkB,EAAE,MAAmB;QACzC,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7B,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC9B,CAAC;aAAM,IAAI,IAAI,CAAC,QAAQ,GAAG,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC/D,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YAC5C,IAAI,MAAM,KAAK,SAAS;gBAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACpD,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACnC,CAAC;IAED,IAAI;QACF,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;IACvB,CAAC;IAED,KAAK;QACH,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;CACF;AAED,IAAI,MAAM,GAAwB,IAAI,CAAC;AAEvC,MAAM,UAAU,qBAAqB,CAAC,QAAiB;IACrD,IAAI,MAAM,KAAK,IAAI;QAAE,MAAM,GAAG,IAAI,YAAY,CAAC,QAAQ,CAAC,CAAC;IACzD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,+BAA+B;IAC7C,MAAM,GAAG,IAAI,CAAC;AAChB,CAAC"}
@@ -0,0 +1,23 @@
1
+ export interface CallerInfo {
2
+ file: string;
3
+ function: string;
4
+ }
5
+ export interface ResolveCallerArgs {
6
+ skipPackageDirs: readonly string[];
7
+ blockList: readonly string[];
8
+ repoRoot: string;
9
+ /** Max distinct (file, function) pairs to attribute before overflow. 0 = unlimited. */
10
+ maxCallSites: number;
11
+ skipFrames?: number;
12
+ }
13
+ export declare function resolveCaller(args: ResolveCallerArgs): CallerInfo;
14
+ /**
15
+ * Returns true iff a cardinality cap was crossed since the last call.
16
+ * Designed to be called once per `startCall` so the instrument layer can
17
+ * emit a single `frugal.gen_ai.internal_errors{stage=cardinality_cap_hit}`.
18
+ */
19
+ export declare function consumeCapHitEvent(): boolean;
20
+ export declare function packageDirFor(anyPathInPackage: string): string;
21
+ /** Test-only hook — clear all caches. */
22
+ export declare function resetCachesForTests(): void;
23
+ //# sourceMappingURL=caller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caller.d.ts","sourceRoot":"","sources":["../src/caller.ts"],"names":[],"mappings":"AAuBA,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CAClB;AAQD,MAAM,WAAW,iBAAiB;IAChC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,uFAAuF;IACvF,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAkBD,wBAAgB,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,UAAU,CAqCjE;AA8BD;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,OAAO,CAM5C;AA6ED,wBAAgB,aAAa,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAiB9D;AAED,yCAAyC;AACzC,wBAAgB,mBAAmB,IAAI,IAAI,CAO1C"}