@majapisoftwares/ai-usage 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collectAgentRunUsage = collectAgentRunUsage;
4
+ exports.countWebSearchToolCalls = countWebSearchToolCalls;
5
+ const pricing_js_1 = require("./pricing.js");
6
+ /** Sums what the model reported over every response of one agent run. */
7
+ function collectAgentRunUsage(rawResponses) {
8
+ return rawResponses.reduce((totals, response) => ({
9
+ cachedInputTokens: totals.cachedInputTokens +
10
+ (0, pricing_js_1.readCachedInputTokens)(response.usage.inputTokensDetails),
11
+ inputTokens: totals.inputTokens + response.usage.inputTokens,
12
+ outputTokens: totals.outputTokens + response.usage.outputTokens,
13
+ totalTokens: totals.totalTokens + response.usage.totalTokens,
14
+ }), {
15
+ cachedInputTokens: 0,
16
+ inputTokens: 0,
17
+ outputTokens: 0,
18
+ totalTokens: 0,
19
+ });
20
+ }
21
+ const WEB_SEARCH_TOOL_NAMES = ["web_search_call", "web_search", "web_search_preview"];
22
+ function countWebSearchToolCalls(items) {
23
+ return items.reduce((count, item) => {
24
+ if (item.type !== "tool_call_item" ||
25
+ item.rawItem.type !== "hosted_tool_call") {
26
+ return count;
27
+ }
28
+ if (typeof item.rawItem.name === "string" &&
29
+ WEB_SEARCH_TOOL_NAMES.includes(item.rawItem.name)) {
30
+ return count + 1;
31
+ }
32
+ return count;
33
+ }, 0);
34
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAiUsageRecorder = exports.countWebSearchToolCalls = exports.collectAgentRunUsage = exports.roundUsd = exports.readCachedInputTokens = exports.clampCount = exports.calculateTextGenerationCostUsd = exports.calculateEmbeddingCostUsd = exports.calculateAudioTranscriptionCostUsd = void 0;
4
+ var pricing_js_1 = require("./pricing.js");
5
+ Object.defineProperty(exports, "calculateAudioTranscriptionCostUsd", { enumerable: true, get: function () { return pricing_js_1.calculateAudioTranscriptionCostUsd; } });
6
+ Object.defineProperty(exports, "calculateEmbeddingCostUsd", { enumerable: true, get: function () { return pricing_js_1.calculateEmbeddingCostUsd; } });
7
+ Object.defineProperty(exports, "calculateTextGenerationCostUsd", { enumerable: true, get: function () { return pricing_js_1.calculateTextGenerationCostUsd; } });
8
+ Object.defineProperty(exports, "clampCount", { enumerable: true, get: function () { return pricing_js_1.clampCount; } });
9
+ Object.defineProperty(exports, "readCachedInputTokens", { enumerable: true, get: function () { return pricing_js_1.readCachedInputTokens; } });
10
+ Object.defineProperty(exports, "roundUsd", { enumerable: true, get: function () { return pricing_js_1.roundUsd; } });
11
+ var agent_run_usage_js_1 = require("./agent-run-usage.js");
12
+ Object.defineProperty(exports, "collectAgentRunUsage", { enumerable: true, get: function () { return agent_run_usage_js_1.collectAgentRunUsage; } });
13
+ Object.defineProperty(exports, "countWebSearchToolCalls", { enumerable: true, get: function () { return agent_run_usage_js_1.countWebSearchToolCalls; } });
14
+ var recorder_js_1 = require("./recorder.js");
15
+ Object.defineProperty(exports, "createAiUsageRecorder", { enumerable: true, get: function () { return recorder_js_1.createAiUsageRecorder; } });
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.roundUsd = roundUsd;
4
+ exports.clampCount = clampCount;
5
+ exports.readCachedInputTokens = readCachedInputTokens;
6
+ exports.calculateTextGenerationCostUsd = calculateTextGenerationCostUsd;
7
+ exports.calculateAudioTranscriptionCostUsd = calculateAudioTranscriptionCostUsd;
8
+ exports.calculateEmbeddingCostUsd = calculateEmbeddingCostUsd;
9
+ const ONE_MILLION = 1_000_000;
10
+ const ONE_THOUSAND = 1_000;
11
+ function roundUsd(value) {
12
+ return Number(value.toFixed(12));
13
+ }
14
+ function clampCount(value) {
15
+ if (!Number.isFinite(value) || value <= 0) {
16
+ return 0;
17
+ }
18
+ return Math.floor(value);
19
+ }
20
+ function readCachedInputTokens(details) {
21
+ if (!details) {
22
+ return 0;
23
+ }
24
+ if (Array.isArray(details)) {
25
+ return details.reduce((sum, detail) => sum + readCachedInputTokens(detail), 0);
26
+ }
27
+ if (typeof details !== "object" || details === null) {
28
+ return 0;
29
+ }
30
+ const cachedTokens = "cached_tokens" in details ? details.cached_tokens : undefined;
31
+ return typeof cachedTokens === "number" && Number.isFinite(cachedTokens)
32
+ ? cachedTokens
33
+ : 0;
34
+ }
35
+ function calculateTextGenerationCostUsd(pricingSource, input) {
36
+ const pricing = pricingSource.textModel(input.model);
37
+ if (!pricing) {
38
+ return null;
39
+ }
40
+ const inputTokens = clampCount(input.inputTokens);
41
+ const outputTokens = clampCount(input.outputTokens);
42
+ const cachedInputTokens = Math.min(inputTokens, clampCount(input.cachedInputTokens));
43
+ const cacheWriteTokens = Math.min(inputTokens - cachedInputTokens, clampCount(input.cacheWriteTokens ?? 0));
44
+ const longCacheWriteTokens = Math.min(cacheWriteTokens, clampCount(input.longCacheWriteTokens ?? 0));
45
+ if ((cacheWriteTokens > 0 && pricing.cacheWriteUsdPer1M === undefined) ||
46
+ (longCacheWriteTokens > 0 && pricing.longCacheWriteUsdPer1M === undefined))
47
+ return null;
48
+ const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
49
+ const webSearchCallCount = clampCount(input.webSearchCallCount ?? 0);
50
+ const webSearchUsdPer1KCalls = pricingSource.webSearchUsdPer1KCalls();
51
+ const costUsd = (uncachedInputTokens * pricing.inputUsdPer1M) / ONE_MILLION +
52
+ (cachedInputTokens * pricing.cachedInputUsdPer1M) / ONE_MILLION +
53
+ ((cacheWriteTokens - longCacheWriteTokens) *
54
+ (pricing.cacheWriteUsdPer1M ?? 0)) /
55
+ ONE_MILLION +
56
+ (longCacheWriteTokens * (pricing.longCacheWriteUsdPer1M ?? 0)) /
57
+ ONE_MILLION +
58
+ (outputTokens * pricing.outputUsdPer1M) / ONE_MILLION +
59
+ (webSearchCallCount * webSearchUsdPer1KCalls) / ONE_THOUSAND;
60
+ return roundUsd(costUsd);
61
+ }
62
+ function calculateAudioTranscriptionCostUsd(pricingSource, input) {
63
+ const seconds = Math.max(0, input.audioSeconds);
64
+ const audioUsdPerMinute = pricingSource.audioTranscriptionUsdPerMinute(input.model);
65
+ return roundUsd((seconds / 60) * audioUsdPerMinute);
66
+ }
67
+ function calculateEmbeddingCostUsd(pricingSource, input) {
68
+ const pricing = pricingSource.embeddingModel(input.model);
69
+ if (!pricing) {
70
+ return null;
71
+ }
72
+ return roundUsd((clampCount(input.inputTokens) * pricing.inputUsdPer1M) / ONE_MILLION);
73
+ }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAiUsageRecorder = createAiUsageRecorder;
4
+ const pricing_js_1 = require("./pricing.js");
5
+ function createAiUsageRecorder(ports) {
6
+ async function persist(input) {
7
+ const record = {
8
+ ...input,
9
+ aiProvider: "openai",
10
+ client: await ports.resolveClient(input.workspaceId),
11
+ occurredAt: input.occurredAt ?? new Date(),
12
+ };
13
+ if (input.dedupeKey) {
14
+ return ports.sink.insertIfNew(record);
15
+ }
16
+ await ports.sink.insert(record);
17
+ return true;
18
+ }
19
+ return {
20
+ async recordTextGenerationSpend(input) {
21
+ const costUsd = (0, pricing_js_1.calculateTextGenerationCostUsd)(ports.pricing, {
22
+ cachedInputTokens: input.cachedInputTokens,
23
+ inputTokens: input.inputTokens,
24
+ model: input.model,
25
+ outputTokens: input.outputTokens,
26
+ webSearchCallCount: input.webSearchCallCount,
27
+ });
28
+ if (costUsd === null) {
29
+ ports.logger.warn({ feature: input.feature, model: input.model }, "Skipping OpenAI AI call cost because pricing is unknown for this model");
30
+ return false;
31
+ }
32
+ return persist({
33
+ audioSeconds: 0,
34
+ cachedInputTokens: (0, pricing_js_1.clampCount)(input.cachedInputTokens),
35
+ costUsd,
36
+ dedupeKey: input.dedupeKey,
37
+ feature: input.feature,
38
+ inputTokens: (0, pricing_js_1.clampCount)(input.inputTokens),
39
+ model: input.model,
40
+ occurredAt: input.occurredAt,
41
+ outputTokens: (0, pricing_js_1.clampCount)(input.outputTokens),
42
+ totalTokens: Math.max((0, pricing_js_1.clampCount)(input.totalTokens), (0, pricing_js_1.clampCount)(input.inputTokens) + (0, pricing_js_1.clampCount)(input.outputTokens)),
43
+ userId: input.userId,
44
+ webSearchCallCount: (0, pricing_js_1.clampCount)(input.webSearchCallCount ?? 0),
45
+ workspaceId: input.workspaceId,
46
+ });
47
+ },
48
+ async recordAudioTranscriptionSpend(input) {
49
+ return persist({
50
+ audioSeconds: Math.max(0, input.audioSeconds),
51
+ cachedInputTokens: 0,
52
+ costUsd: (0, pricing_js_1.calculateAudioTranscriptionCostUsd)(ports.pricing, {
53
+ audioSeconds: input.audioSeconds,
54
+ model: input.model,
55
+ }),
56
+ dedupeKey: input.dedupeKey,
57
+ feature: input.feature,
58
+ inputTokens: 0,
59
+ model: input.model,
60
+ occurredAt: input.occurredAt,
61
+ outputTokens: 0,
62
+ totalTokens: 0,
63
+ userId: input.userId,
64
+ webSearchCallCount: 0,
65
+ workspaceId: input.workspaceId,
66
+ });
67
+ },
68
+ async recordEmbeddingSpend(input) {
69
+ const costUsd = (0, pricing_js_1.calculateEmbeddingCostUsd)(ports.pricing, {
70
+ inputTokens: input.inputTokens,
71
+ model: input.model,
72
+ });
73
+ if (costUsd === null) {
74
+ ports.logger.warn({ feature: input.feature, model: input.model }, "Skipping OpenAI embedding cost because pricing is unknown for this model");
75
+ return false;
76
+ }
77
+ return persist({
78
+ audioSeconds: 0,
79
+ cachedInputTokens: 0,
80
+ costUsd,
81
+ dedupeKey: input.dedupeKey,
82
+ feature: input.feature,
83
+ inputTokens: (0, pricing_js_1.clampCount)(input.inputTokens),
84
+ model: input.model,
85
+ occurredAt: input.occurredAt,
86
+ outputTokens: 0,
87
+ totalTokens: Math.max((0, pricing_js_1.clampCount)(input.totalTokens), (0, pricing_js_1.clampCount)(input.inputTokens)),
88
+ userId: input.userId,
89
+ webSearchCallCount: 0,
90
+ workspaceId: input.workspaceId,
91
+ });
92
+ },
93
+ };
94
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@majapisoftwares/ai-usage",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Cost of each AI call, always billed to a client: pricing math, usage collection and a recorder over ports the app implements.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -12,7 +12,9 @@
12
12
  "exports": {
13
13
  ".": {
14
14
  "types": "./dist/index.d.ts",
15
- "import": "./dist/index.js"
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/cjs/index.js",
17
+ "default": "./dist/index.js"
16
18
  }
17
19
  },
18
20
  "main": "./dist/index.js",
@@ -27,7 +29,7 @@
27
29
  "access": "public"
28
30
  },
29
31
  "scripts": {
30
- "build": "rm -rf dist && tsc -p tsconfig.build.json",
32
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node ../../scripts/mark-cjs.mjs dist/cjs",
31
33
  "typecheck": "tsc --noEmit"
32
34
  }
33
35
  }