@tensorcost/otel-genai-cost 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @tensorcost/otel-genai-cost
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reads an OpenTelemetry GenAI span and returns one call shape: provider, model, input and output tokens, cache read and write tokens, the response id and who made the call. It is the same code TensorCost's inference proxy runs on spans from Kong, LiteLLM and plain OpenTelemetry exporters, published so the mapping can be read, checked and corrected in the open.
4
+
5
+ It has no runtime dependencies and does not read the network. Input is an OTLP/JSON span, output is a plain object.
6
+
7
+ ```ts
8
+ import { mapGenAiSpan, storedInputTokens } from "@tensorcost/otel-genai-cost";
9
+
10
+ const call = mapGenAiSpan(span); // null when the span is not an LLM call
11
+ call?.provider; // "anthropic" | "openai" | "bedrock" | "azure_openai" | "vertex" | null
12
+ call?.inputTokens; // already adjusted by storedInputTokens
13
+ ```
14
+
15
+ Exports: `mapGenAiSpan`, `detectEmitter`, `storedInputTokens`, `spanCorrelationId`, `normalizeProviderName` and the types `GenAiCall`, `GatewayCaller`, `GatewayEmitter`, `GenAiProviderId`, `OtlpSpanLike`, `OtlpAttributeLike`.
16
+
17
+ ## Attributes read
18
+
19
+ Where a row lists several keys, they are tried in order and the first one present wins, except for the provider, which is described below the table.
20
+
21
+ | Field | Attribute keys |
22
+ | --- | --- |
23
+ | provider | `gen_ai.provider.name`, then `gen_ai.system`, then `llm.provider` (first one that names a known provider) |
24
+ | model | `gen_ai.request.model`, `gen_ai.response.model`, `llm.model_name` |
25
+ | input tokens | `gen_ai.usage.input_tokens`, `llm.token_count.prompt` |
26
+ | output tokens | `gen_ai.usage.output_tokens`, `llm.token_count.completion` |
27
+ | cache read tokens | `gen_ai.usage.cache_read.input_tokens`, `llm.token_count.prompt_details.cache_read` |
28
+ | cache write tokens | `gen_ai.usage.cache_creation.input_tokens`, `llm.token_count.prompt_details.cache_write` |
29
+ | response id | `gen_ai.response.id` |
30
+ | max tokens | `gen_ai.request.max_tokens` |
31
+ | status | `gen_ai.response.status`, then `error.type`; any value other than `success` is an error |
32
+ | caller (consumer) | `kong.auth.consumer.name` |
33
+ | caller (workspace) | `kong.workspace.name` |
34
+ | caller (user) | `user.email` |
35
+
36
+ The operation is the span name, or `gen_ai.operation.name` when the span has none. Missing token and cache counts are 0.
37
+
38
+ Provider names are matched case-insensitively against a fixed list: `anthropic`; `openai`; `aws.bedrock`, `bedrock`, `amazon_bedrock` (all `bedrock`); `azure.ai.openai`, `azure.ai.inference`, `azure`, `azure_openai` (all `azure_openai`); `gcp.vertex_ai`, `gcp.gemini`, `gcp.gen_ai`, `vertex_ai`, `vertex` (all `vertex`). The raw value is kept in `providerRaw`.
39
+
40
+ ## Unknown providers and non-LLM spans
41
+
42
+ The three provider keys are tried in order and the first value that matches the list gives `provider`. `providerRaw` is the first provider value present on the span, matched or not, so `gen_ai.provider.name=foo` with `gen_ai.system=anthropic` gives `provider: "anthropic"` and `providerRaw: "foo"`. If no key matches, `provider` is `null`. It is never replaced with a default vendor, because a guessed vendor prices the call from the wrong rate card. Check `providerRaw` to see what the gateway sent.
43
+
44
+ A span that is not an LLM call gives `null` from `mapGenAiSpan`. That is any span with no model, and any span with a model but no token usage and no response id, which is a wrapper around the real call and would count the spend twice if kept.
45
+
46
+ ## Token convention
47
+
48
+ The stored input token count includes cache reads and cache writes. A call that sent 300 uncached input tokens, read 800 tokens from the cache and wrote 100 to it is stored as 1200 input tokens, with `cacheReadTokens` 800 and `cacheWriteTokens` 100 kept alongside.
49
+
50
+ Emitters do not agree on whether the number on the span already includes the cache, so `storedInputTokens(emitter, provider, reportedInput, cacheRead, cacheWrite)` adds the cache back where it is missing. `mapGenAiSpan` calls it for you.
51
+
52
+ | Emitter | Reported input | Stored input |
53
+ | --- | --- | --- |
54
+ | `otel` (OpenTelemetry semconv) | includes cache | as reported |
55
+ | `litellm` | includes cache | as reported |
56
+ | `kong`, provider `anthropic` | excludes cache (unverified) | reported + cache read + cache write |
57
+ | `kong`, any other provider | includes cache | as reported |
58
+
59
+ The Kong and Anthropic row is unverified. It follows Anthropic's own usage block, which reports the uncached remainder, and has not been checked against a live Kong gateway. If you run one and see otherwise, open an issue.
60
+
61
+ `detectEmitter` returns `kong` when any attribute starts with `kong.` and `otel` otherwise. LiteLLM spans carry no marker, so pass `"litellm"` to `mapGenAiSpan` yourself.
62
+
63
+ `spanCorrelationId(traceId, spanId)` returns a UUID-shaped id from both ids. A trace id alone is shared by every call in an agent run.
64
+
65
+ ## Reporting a semconv rename
66
+
67
+ The OpenTelemetry GenAI conventions are still changing, and attribute names move between releases. If a gateway or SDK sends a name this package does not read, or a rename changes what a field means, open an issue on https://github.com/vaadhlabs/tensorcost-integrations. Include the attribute names, the semconv or gateway version, and one span as OTLP/JSON with prompts and any personal data removed. A pull request that adds the key to the table above and a test is welcome.
68
+
69
+ ## License
70
+
71
+ Apache-2.0.
@@ -0,0 +1,3 @@
1
+ export { normalizeProviderName, type GenAiProviderId } from "./provider-name.js";
2
+ export { detectEmitter, mapGenAiSpan, spanCorrelationId, storedInputTokens, type GatewayCaller, type GatewayEmitter, type GenAiCall, type OtlpAttributeLike, type OtlpSpanLike, } from "./map-span.js";
3
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { normalizeProviderName } from "./provider-name.js";
2
+ export { detectEmitter, mapGenAiSpan, spanCorrelationId, storedInputTokens, } from "./map-span.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,80 @@
1
+ import { type GenAiProviderId } from "./provider-name.js";
2
+ export interface OtlpAttributeLike {
3
+ key: string;
4
+ value?: {
5
+ stringValue?: string;
6
+ intValue?: string | number;
7
+ doubleValue?: number;
8
+ boolValue?: boolean;
9
+ };
10
+ }
11
+ export interface OtlpSpanLike {
12
+ traceId?: string;
13
+ spanId?: string;
14
+ name?: string;
15
+ startTimeUnixNano?: string;
16
+ endTimeUnixNano?: string;
17
+ attributes?: OtlpAttributeLike[];
18
+ }
19
+ export type GatewayEmitter = "kong" | "litellm" | "otel";
20
+ export interface GatewayCaller {
21
+ kind: string;
22
+ id: string;
23
+ }
24
+ /**
25
+ * One LLM call as a gateway reported it. inputTokens is what the span said;
26
+ * run it through storedInputTokens before storing, because emitters disagree
27
+ * on whether it already contains the cache tokens.
28
+ */
29
+ export interface GenAiCall {
30
+ provider: GenAiProviderId | null;
31
+ providerRaw: string | null;
32
+ model: string;
33
+ operation: string | null;
34
+ inputTokens: number;
35
+ outputTokens: number;
36
+ cacheReadTokens: number;
37
+ cacheWriteTokens: number;
38
+ responseId: string | null;
39
+ traceId: string | null;
40
+ spanId: string | null;
41
+ maxTokens: number | null;
42
+ callers: GatewayCaller[];
43
+ startedAt: string;
44
+ endedAt: string | null;
45
+ status: "success" | "error";
46
+ errorType: string | null;
47
+ }
48
+ /**
49
+ * Kong's AI plugins stamp kong.* attributes on the span; plain OTel and
50
+ * LiteLLM spans don't. LiteLLM is never detected here (its spans carry no
51
+ * reliable marker), so pass it explicitly.
52
+ */
53
+ export declare function detectEmitter(span: OtlpSpanLike): GatewayEmitter;
54
+ /**
55
+ * Reads one span. Null means the span is not an LLM call: it has no model, or
56
+ * it has a model but neither usage nor a response id (a wrapper span around
57
+ * the real call, which would double count if it were kept).
58
+ *
59
+ * inputTokens is the stored value: for an emitter whose input excludes the
60
+ * cache (Kong with Anthropic) the cache reads and writes are added back, see
61
+ * storedInputTokens. The emitter is detected from kong.* attributes unless
62
+ * the caller passes it.
63
+ */
64
+ export declare function mapGenAiSpan(span: OtlpSpanLike, emitter?: GatewayEmitter): GenAiCall | null;
65
+ /**
66
+ * A UUID-shaped id from the trace id and span id together. The trace id alone
67
+ * is shared by every call in an agent run, so five calls would collapse into
68
+ * one row.
69
+ */
70
+ export declare function spanCorrelationId(traceId: string, spanId: string): string;
71
+ /**
72
+ * The input_tokens value to store, where stored input counts everything the
73
+ * model read, cache reads and writes included. Whether the reported number
74
+ * already includes the cache depends on who emitted the span: OTel semconv
75
+ * and LiteLLM include it; Kong follows each provider's own usage block, so an
76
+ * Anthropic span reports the uncached remainder only. The Kong rows are
77
+ * unverified against a live gateway.
78
+ */
79
+ export declare function storedInputTokens(emitter: GatewayEmitter, provider: GenAiProviderId | null, reportedInput: number, cacheRead: number, cacheWrite: number): number;
80
+ //# sourceMappingURL=map-span.d.ts.map
@@ -0,0 +1,140 @@
1
+ import { createHash } from "node:crypto";
2
+ import { normalizeProviderName } from "./provider-name.js";
3
+ const PROVIDER_KEYS = ["gen_ai.provider.name", "gen_ai.system", "llm.provider"];
4
+ const MODEL_KEYS = ["gen_ai.request.model", "gen_ai.response.model", "llm.model_name"];
5
+ const INPUT_KEYS = ["gen_ai.usage.input_tokens", "llm.token_count.prompt"];
6
+ const OUTPUT_KEYS = ["gen_ai.usage.output_tokens", "llm.token_count.completion"];
7
+ const CACHE_READ_KEYS = [
8
+ "gen_ai.usage.cache_read.input_tokens",
9
+ "llm.token_count.prompt_details.cache_read",
10
+ ];
11
+ const CACHE_WRITE_KEYS = [
12
+ "gen_ai.usage.cache_creation.input_tokens",
13
+ "llm.token_count.prompt_details.cache_write",
14
+ ];
15
+ const CALLER_KEYS = [
16
+ { key: "kong.auth.consumer.name", kind: "consumer" },
17
+ { key: "kong.workspace.name", kind: "workspace" },
18
+ { key: "user.email", kind: "user" },
19
+ ];
20
+ function attrString(attrs, keys) {
21
+ for (const key of keys) {
22
+ const v = attrs.find((a) => a.key === key)?.value;
23
+ if (!v)
24
+ continue;
25
+ if (v.stringValue)
26
+ return v.stringValue;
27
+ if (v.intValue != null)
28
+ return String(v.intValue);
29
+ if (v.doubleValue != null)
30
+ return String(v.doubleValue);
31
+ }
32
+ return undefined;
33
+ }
34
+ function attrNumber(attrs, keys) {
35
+ const raw = attrString(attrs, keys);
36
+ if (raw == null)
37
+ return undefined;
38
+ const n = Number(raw);
39
+ return Number.isFinite(n) ? n : undefined;
40
+ }
41
+ function nanoToIso(nano) {
42
+ if (!nano)
43
+ return null;
44
+ const ms = Math.floor(Number(nano) / 1_000_000);
45
+ if (!Number.isFinite(ms))
46
+ return null;
47
+ return new Date(ms).toISOString();
48
+ }
49
+ /**
50
+ * Kong's AI plugins stamp kong.* attributes on the span; plain OTel and
51
+ * LiteLLM spans don't. LiteLLM is never detected here (its spans carry no
52
+ * reliable marker), so pass it explicitly.
53
+ */
54
+ export function detectEmitter(span) {
55
+ const kong = (span.attributes ?? []).some((a) => a.key.startsWith("kong."));
56
+ return kong ? "kong" : "otel";
57
+ }
58
+ /**
59
+ * Reads one span. Null means the span is not an LLM call: it has no model, or
60
+ * it has a model but neither usage nor a response id (a wrapper span around
61
+ * the real call, which would double count if it were kept).
62
+ *
63
+ * inputTokens is the stored value: for an emitter whose input excludes the
64
+ * cache (Kong with Anthropic) the cache reads and writes are added back, see
65
+ * storedInputTokens. The emitter is detected from kong.* attributes unless
66
+ * the caller passes it.
67
+ */
68
+ export function mapGenAiSpan(span, emitter) {
69
+ const attrs = span.attributes ?? [];
70
+ const model = attrString(attrs, MODEL_KEYS);
71
+ if (!model)
72
+ return null;
73
+ const input = attrNumber(attrs, INPUT_KEYS);
74
+ const output = attrNumber(attrs, OUTPUT_KEYS);
75
+ const responseId = attrString(attrs, ["gen_ai.response.id"]) ?? null;
76
+ if (input === undefined && output === undefined && responseId === null)
77
+ return null;
78
+ let providerRaw = null;
79
+ let provider = null;
80
+ for (const key of PROVIDER_KEYS) {
81
+ const raw = attrString(attrs, [key]);
82
+ if (!raw)
83
+ continue;
84
+ providerRaw ??= raw;
85
+ provider = normalizeProviderName(raw);
86
+ if (provider)
87
+ break;
88
+ }
89
+ const callers = [];
90
+ for (const { key, kind } of CALLER_KEYS) {
91
+ const id = attrString(attrs, [key]);
92
+ if (id)
93
+ callers.push({ kind, id });
94
+ }
95
+ const cacheRead = attrNumber(attrs, CACHE_READ_KEYS) ?? 0;
96
+ const cacheWrite = attrNumber(attrs, CACHE_WRITE_KEYS) ?? 0;
97
+ const statusRaw = attrString(attrs, ["gen_ai.response.status", "error.type"]);
98
+ const failed = statusRaw !== undefined && statusRaw !== "success";
99
+ return {
100
+ provider,
101
+ providerRaw,
102
+ model,
103
+ operation: span.name ?? attrString(attrs, ["gen_ai.operation.name"]) ?? null,
104
+ inputTokens: storedInputTokens(emitter ?? detectEmitter(span), provider, input ?? 0, cacheRead, cacheWrite),
105
+ outputTokens: output ?? 0,
106
+ cacheReadTokens: cacheRead,
107
+ cacheWriteTokens: cacheWrite,
108
+ responseId,
109
+ traceId: span.traceId ?? null,
110
+ spanId: span.spanId ?? null,
111
+ maxTokens: attrNumber(attrs, ["gen_ai.request.max_tokens"]) ?? null,
112
+ callers,
113
+ startedAt: nanoToIso(span.startTimeUnixNano) ?? new Date().toISOString(),
114
+ endedAt: nanoToIso(span.endTimeUnixNano),
115
+ status: failed ? "error" : "success",
116
+ errorType: failed ? (statusRaw ?? null) : null,
117
+ };
118
+ }
119
+ /**
120
+ * A UUID-shaped id from the trace id and span id together. The trace id alone
121
+ * is shared by every call in an agent run, so five calls would collapse into
122
+ * one row.
123
+ */
124
+ export function spanCorrelationId(traceId, spanId) {
125
+ const h = createHash("sha256").update(`${traceId}:${spanId}`).digest("hex");
126
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
127
+ }
128
+ /**
129
+ * The input_tokens value to store, where stored input counts everything the
130
+ * model read, cache reads and writes included. Whether the reported number
131
+ * already includes the cache depends on who emitted the span: OTel semconv
132
+ * and LiteLLM include it; Kong follows each provider's own usage block, so an
133
+ * Anthropic span reports the uncached remainder only. The Kong rows are
134
+ * unverified against a live gateway.
135
+ */
136
+ export function storedInputTokens(emitter, provider, reportedInput, cacheRead, cacheWrite) {
137
+ const excludesCache = emitter === "kong" && provider === "anthropic";
138
+ return excludesCache ? reportedInput + cacheRead + cacheWrite : reportedInput;
139
+ }
140
+ //# sourceMappingURL=map-span.js.map
@@ -0,0 +1,8 @@
1
+ export type GenAiProviderId = "anthropic" | "openai" | "bedrock" | "azure_openai" | "vertex";
2
+ /**
3
+ * Maps the provider name a gateway puts on a span (the OTel GenAI names plus
4
+ * the spellings Kong and LiteLLM use) to the id TensorCost stores. Anything
5
+ * else is null: guessing a provider writes spend under the wrong price list.
6
+ */
7
+ export declare function normalizeProviderName(raw: string | null | undefined): GenAiProviderId | null;
8
+ //# sourceMappingURL=provider-name.d.ts.map
@@ -0,0 +1,27 @@
1
+ const PROVIDER_NAMES = {
2
+ anthropic: "anthropic",
3
+ openai: "openai",
4
+ "aws.bedrock": "bedrock",
5
+ bedrock: "bedrock",
6
+ amazon_bedrock: "bedrock",
7
+ "azure.ai.openai": "azure_openai",
8
+ "azure.ai.inference": "azure_openai",
9
+ azure: "azure_openai",
10
+ azure_openai: "azure_openai",
11
+ "gcp.vertex_ai": "vertex",
12
+ "gcp.gemini": "vertex",
13
+ "gcp.gen_ai": "vertex",
14
+ vertex_ai: "vertex",
15
+ vertex: "vertex",
16
+ };
17
+ /**
18
+ * Maps the provider name a gateway puts on a span (the OTel GenAI names plus
19
+ * the spellings Kong and LiteLLM use) to the id TensorCost stores. Anything
20
+ * else is null: guessing a provider writes spend under the wrong price list.
21
+ */
22
+ export function normalizeProviderName(raw) {
23
+ if (!raw)
24
+ return null;
25
+ return PROVIDER_NAMES[raw.trim().toLowerCase()] ?? null;
26
+ }
27
+ //# sourceMappingURL=provider-name.js.map
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@tensorcost/otel-genai-cost",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "description": "Reads OpenTelemetry GenAI spans (Kong, LiteLLM, plain OTel) into one call shape with provider, cache tokens and caller identity.",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/vaadhlabs/tensorcost-integrations.git",
9
+ "directory": "packages/otel-genai-cost"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "keywords": [
15
+ "opentelemetry",
16
+ "genai",
17
+ "llm",
18
+ "cost",
19
+ "tokens"
20
+ ],
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "scripts": {
31
+ "build": "tsc -b",
32
+ "dev": "tsc -b --watch",
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "vitest run",
35
+ "lint": "echo 'no lint configured'"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^22.0.0",
39
+ "typescript": "^5.6.0",
40
+ "vitest": "^3.2.6"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "!dist/**/*.map",
45
+ "README.md",
46
+ "LICENSE"
47
+ ]
48
+ }