@majapisoftwares/ai-usage 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.
@@ -0,0 +1,23 @@
1
+ export interface AgentRunModelResponse {
2
+ usage: {
3
+ inputTokens: number;
4
+ outputTokens: number;
5
+ totalTokens: number;
6
+ inputTokensDetails?: unknown;
7
+ };
8
+ }
9
+ export interface AgentRunItem {
10
+ type: string;
11
+ rawItem: {
12
+ type?: string;
13
+ name?: unknown;
14
+ };
15
+ }
16
+ /** Sums what the model reported over every response of one agent run. */
17
+ export declare function collectAgentRunUsage(rawResponses: AgentRunModelResponse[]): {
18
+ cachedInputTokens: number;
19
+ inputTokens: number;
20
+ outputTokens: number;
21
+ totalTokens: number;
22
+ };
23
+ export declare function countWebSearchToolCalls(items: AgentRunItem[]): number;
@@ -0,0 +1,30 @@
1
+ import { readCachedInputTokens } from "./pricing.js";
2
+ /** Sums what the model reported over every response of one agent run. */
3
+ export function collectAgentRunUsage(rawResponses) {
4
+ return rawResponses.reduce((totals, response) => ({
5
+ cachedInputTokens: totals.cachedInputTokens +
6
+ readCachedInputTokens(response.usage.inputTokensDetails),
7
+ inputTokens: totals.inputTokens + response.usage.inputTokens,
8
+ outputTokens: totals.outputTokens + response.usage.outputTokens,
9
+ totalTokens: totals.totalTokens + response.usage.totalTokens,
10
+ }), {
11
+ cachedInputTokens: 0,
12
+ inputTokens: 0,
13
+ outputTokens: 0,
14
+ totalTokens: 0,
15
+ });
16
+ }
17
+ const WEB_SEARCH_TOOL_NAMES = ["web_search_call", "web_search", "web_search_preview"];
18
+ export function countWebSearchToolCalls(items) {
19
+ return items.reduce((count, item) => {
20
+ if (item.type !== "tool_call_item" ||
21
+ item.rawItem.type !== "hosted_tool_call") {
22
+ return count;
23
+ }
24
+ if (typeof item.rawItem.name === "string" &&
25
+ WEB_SEARCH_TOOL_NAMES.includes(item.rawItem.name)) {
26
+ return count + 1;
27
+ }
28
+ return count;
29
+ }, 0);
30
+ }
@@ -0,0 +1,3 @@
1
+ export { calculateAudioTranscriptionCostUsd, calculateEmbeddingCostUsd, calculateTextGenerationCostUsd, clampCount, readCachedInputTokens, roundUsd, type EmbeddingModelPricing, type PricingSource, type TextModelPricing, } from "./pricing.js";
2
+ export { collectAgentRunUsage, countWebSearchToolCalls, type AgentRunItem, type AgentRunModelResponse, } from "./agent-run-usage.js";
3
+ export { createAiUsageRecorder, type AiUsageLogger, type AiUsageRecord, type AiUsageRecorderPorts, type AudioTranscriptionSpendInput, type CostSink, type EmbeddingSpendInput, type TextGenerationSpendInput, } from "./recorder.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { calculateAudioTranscriptionCostUsd, calculateEmbeddingCostUsd, calculateTextGenerationCostUsd, clampCount, readCachedInputTokens, roundUsd, } from "./pricing.js";
2
+ export { collectAgentRunUsage, countWebSearchToolCalls, } from "./agent-run-usage.js";
3
+ export { createAiUsageRecorder, } from "./recorder.js";
@@ -0,0 +1,37 @@
1
+ export type TextModelPricing = {
2
+ cacheWriteUsdPer1M?: number;
3
+ longCacheWriteUsdPer1M?: number;
4
+ cachedInputUsdPer1M: number;
5
+ inputUsdPer1M: number;
6
+ outputUsdPer1M: number;
7
+ };
8
+ export type EmbeddingModelPricing = {
9
+ inputUsdPer1M: number;
10
+ };
11
+ /** Where the prices come from; the app owns them (admin settings, a file, the provider's list). */
12
+ export interface PricingSource {
13
+ textModel(model: string): TextModelPricing | null;
14
+ embeddingModel(model: string): EmbeddingModelPricing | null;
15
+ audioTranscriptionUsdPerMinute(model: string): number;
16
+ webSearchUsdPer1KCalls(): number;
17
+ }
18
+ export declare function roundUsd(value: number): number;
19
+ export declare function clampCount(value: number): number;
20
+ export declare function readCachedInputTokens(details?: unknown): number;
21
+ export declare function calculateTextGenerationCostUsd(pricingSource: PricingSource, input: {
22
+ cacheWriteTokens?: number;
23
+ longCacheWriteTokens?: number;
24
+ cachedInputTokens: number;
25
+ inputTokens: number;
26
+ model: string;
27
+ outputTokens: number;
28
+ webSearchCallCount?: number;
29
+ }): number | null;
30
+ export declare function calculateAudioTranscriptionCostUsd(pricingSource: PricingSource, input: {
31
+ audioSeconds: number;
32
+ model: string;
33
+ }): number;
34
+ export declare function calculateEmbeddingCostUsd(pricingSource: PricingSource, input: {
35
+ inputTokens: number;
36
+ model: string;
37
+ }): number | null;
@@ -0,0 +1,65 @@
1
+ const ONE_MILLION = 1_000_000;
2
+ const ONE_THOUSAND = 1_000;
3
+ export function roundUsd(value) {
4
+ return Number(value.toFixed(12));
5
+ }
6
+ export function clampCount(value) {
7
+ if (!Number.isFinite(value) || value <= 0) {
8
+ return 0;
9
+ }
10
+ return Math.floor(value);
11
+ }
12
+ export function readCachedInputTokens(details) {
13
+ if (!details) {
14
+ return 0;
15
+ }
16
+ if (Array.isArray(details)) {
17
+ return details.reduce((sum, detail) => sum + readCachedInputTokens(detail), 0);
18
+ }
19
+ if (typeof details !== "object" || details === null) {
20
+ return 0;
21
+ }
22
+ const cachedTokens = "cached_tokens" in details ? details.cached_tokens : undefined;
23
+ return typeof cachedTokens === "number" && Number.isFinite(cachedTokens)
24
+ ? cachedTokens
25
+ : 0;
26
+ }
27
+ export function calculateTextGenerationCostUsd(pricingSource, input) {
28
+ const pricing = pricingSource.textModel(input.model);
29
+ if (!pricing) {
30
+ return null;
31
+ }
32
+ const inputTokens = clampCount(input.inputTokens);
33
+ const outputTokens = clampCount(input.outputTokens);
34
+ const cachedInputTokens = Math.min(inputTokens, clampCount(input.cachedInputTokens));
35
+ const cacheWriteTokens = Math.min(inputTokens - cachedInputTokens, clampCount(input.cacheWriteTokens ?? 0));
36
+ const longCacheWriteTokens = Math.min(cacheWriteTokens, clampCount(input.longCacheWriteTokens ?? 0));
37
+ if ((cacheWriteTokens > 0 && pricing.cacheWriteUsdPer1M === undefined) ||
38
+ (longCacheWriteTokens > 0 && pricing.longCacheWriteUsdPer1M === undefined))
39
+ return null;
40
+ const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
41
+ const webSearchCallCount = clampCount(input.webSearchCallCount ?? 0);
42
+ const webSearchUsdPer1KCalls = pricingSource.webSearchUsdPer1KCalls();
43
+ const costUsd = (uncachedInputTokens * pricing.inputUsdPer1M) / ONE_MILLION +
44
+ (cachedInputTokens * pricing.cachedInputUsdPer1M) / ONE_MILLION +
45
+ ((cacheWriteTokens - longCacheWriteTokens) *
46
+ (pricing.cacheWriteUsdPer1M ?? 0)) /
47
+ ONE_MILLION +
48
+ (longCacheWriteTokens * (pricing.longCacheWriteUsdPer1M ?? 0)) /
49
+ ONE_MILLION +
50
+ (outputTokens * pricing.outputUsdPer1M) / ONE_MILLION +
51
+ (webSearchCallCount * webSearchUsdPer1KCalls) / ONE_THOUSAND;
52
+ return roundUsd(costUsd);
53
+ }
54
+ export function calculateAudioTranscriptionCostUsd(pricingSource, input) {
55
+ const seconds = Math.max(0, input.audioSeconds);
56
+ const audioUsdPerMinute = pricingSource.audioTranscriptionUsdPerMinute(input.model);
57
+ return roundUsd((seconds / 60) * audioUsdPerMinute);
58
+ }
59
+ export function calculateEmbeddingCostUsd(pricingSource, input) {
60
+ const pricing = pricingSource.embeddingModel(input.model);
61
+ if (!pricing) {
62
+ return null;
63
+ }
64
+ return roundUsd((clampCount(input.inputTokens) * pricing.inputUsdPer1M) / ONE_MILLION);
65
+ }
@@ -0,0 +1,63 @@
1
+ import { type PricingSource } from "./pricing.js";
2
+ /** One billed AI call. `client` is required: no call is ever recorded without the customer it is billed to. */
3
+ export interface AiUsageRecord<Id extends string, Client extends string, Feature extends string> {
4
+ aiProvider: "openai";
5
+ audioSeconds: number;
6
+ cachedInputTokens: number;
7
+ client: Client;
8
+ costUsd: number;
9
+ dedupeKey?: string;
10
+ feature: Feature;
11
+ inputTokens: number;
12
+ model: string;
13
+ occurredAt: Date;
14
+ outputTokens: number;
15
+ totalTokens: number;
16
+ userId: Id;
17
+ webSearchCallCount: number;
18
+ workspaceId: Id;
19
+ }
20
+ /** Where records are stored; the app implements it over its own database. */
21
+ export interface CostSink<R> {
22
+ insert(record: R): Promise<void>;
23
+ /** Stores the record unless one with the same `dedupeKey` exists; true when it was stored. */
24
+ insertIfNew(record: R): Promise<boolean>;
25
+ }
26
+ export interface AiUsageLogger {
27
+ warn(context: Record<string, unknown>, message: string): void;
28
+ }
29
+ export interface AiUsageRecorderPorts<Id extends string, Client extends string, Feature extends string> {
30
+ logger: AiUsageLogger;
31
+ pricing: PricingSource;
32
+ /** The client a workspace's usage is billed to; throws when it can't be known. */
33
+ resolveClient(workspaceId: Id): Promise<Client>;
34
+ sink: CostSink<AiUsageRecord<Id, Client, Feature>>;
35
+ }
36
+ type SpendBase<Id extends string, Feature extends string> = {
37
+ dedupeKey?: string;
38
+ feature: Feature;
39
+ model: string;
40
+ occurredAt?: Date;
41
+ userId: Id;
42
+ workspaceId: Id;
43
+ };
44
+ export type TextGenerationSpendInput<Id extends string, Feature extends string> = SpendBase<Id, Feature> & {
45
+ cachedInputTokens: number;
46
+ inputTokens: number;
47
+ outputTokens: number;
48
+ totalTokens: number;
49
+ webSearchCallCount?: number;
50
+ };
51
+ export type AudioTranscriptionSpendInput<Id extends string, Feature extends string> = SpendBase<Id, Feature> & {
52
+ audioSeconds: number;
53
+ };
54
+ export type EmbeddingSpendInput<Id extends string, Feature extends string> = SpendBase<Id, Feature> & {
55
+ inputTokens: number;
56
+ totalTokens: number;
57
+ };
58
+ export declare function createAiUsageRecorder<Id extends string, Client extends string, Feature extends string>(ports: AiUsageRecorderPorts<Id, Client, Feature>): {
59
+ recordTextGenerationSpend(input: TextGenerationSpendInput<Id, Feature>): Promise<boolean>;
60
+ recordAudioTranscriptionSpend(input: AudioTranscriptionSpendInput<Id, Feature>): Promise<boolean>;
61
+ recordEmbeddingSpend(input: EmbeddingSpendInput<Id, Feature>): Promise<boolean>;
62
+ };
63
+ export {};
@@ -0,0 +1,91 @@
1
+ import { calculateAudioTranscriptionCostUsd, calculateEmbeddingCostUsd, calculateTextGenerationCostUsd, clampCount, } from "./pricing.js";
2
+ export function createAiUsageRecorder(ports) {
3
+ async function persist(input) {
4
+ const record = {
5
+ ...input,
6
+ aiProvider: "openai",
7
+ client: await ports.resolveClient(input.workspaceId),
8
+ occurredAt: input.occurredAt ?? new Date(),
9
+ };
10
+ if (input.dedupeKey) {
11
+ return ports.sink.insertIfNew(record);
12
+ }
13
+ await ports.sink.insert(record);
14
+ return true;
15
+ }
16
+ return {
17
+ async recordTextGenerationSpend(input) {
18
+ const costUsd = calculateTextGenerationCostUsd(ports.pricing, {
19
+ cachedInputTokens: input.cachedInputTokens,
20
+ inputTokens: input.inputTokens,
21
+ model: input.model,
22
+ outputTokens: input.outputTokens,
23
+ webSearchCallCount: input.webSearchCallCount,
24
+ });
25
+ if (costUsd === null) {
26
+ ports.logger.warn({ feature: input.feature, model: input.model }, "Skipping OpenAI AI call cost because pricing is unknown for this model");
27
+ return false;
28
+ }
29
+ return persist({
30
+ audioSeconds: 0,
31
+ cachedInputTokens: clampCount(input.cachedInputTokens),
32
+ costUsd,
33
+ dedupeKey: input.dedupeKey,
34
+ feature: input.feature,
35
+ inputTokens: clampCount(input.inputTokens),
36
+ model: input.model,
37
+ occurredAt: input.occurredAt,
38
+ outputTokens: clampCount(input.outputTokens),
39
+ totalTokens: Math.max(clampCount(input.totalTokens), clampCount(input.inputTokens) + clampCount(input.outputTokens)),
40
+ userId: input.userId,
41
+ webSearchCallCount: clampCount(input.webSearchCallCount ?? 0),
42
+ workspaceId: input.workspaceId,
43
+ });
44
+ },
45
+ async recordAudioTranscriptionSpend(input) {
46
+ return persist({
47
+ audioSeconds: Math.max(0, input.audioSeconds),
48
+ cachedInputTokens: 0,
49
+ costUsd: calculateAudioTranscriptionCostUsd(ports.pricing, {
50
+ audioSeconds: input.audioSeconds,
51
+ model: input.model,
52
+ }),
53
+ dedupeKey: input.dedupeKey,
54
+ feature: input.feature,
55
+ inputTokens: 0,
56
+ model: input.model,
57
+ occurredAt: input.occurredAt,
58
+ outputTokens: 0,
59
+ totalTokens: 0,
60
+ userId: input.userId,
61
+ webSearchCallCount: 0,
62
+ workspaceId: input.workspaceId,
63
+ });
64
+ },
65
+ async recordEmbeddingSpend(input) {
66
+ const costUsd = calculateEmbeddingCostUsd(ports.pricing, {
67
+ inputTokens: input.inputTokens,
68
+ model: input.model,
69
+ });
70
+ if (costUsd === null) {
71
+ ports.logger.warn({ feature: input.feature, model: input.model }, "Skipping OpenAI embedding cost because pricing is unknown for this model");
72
+ return false;
73
+ }
74
+ return persist({
75
+ audioSeconds: 0,
76
+ cachedInputTokens: 0,
77
+ costUsd,
78
+ dedupeKey: input.dedupeKey,
79
+ feature: input.feature,
80
+ inputTokens: clampCount(input.inputTokens),
81
+ model: input.model,
82
+ occurredAt: input.occurredAt,
83
+ outputTokens: 0,
84
+ totalTokens: Math.max(clampCount(input.totalTokens), clampCount(input.inputTokens)),
85
+ userId: input.userId,
86
+ webSearchCallCount: 0,
87
+ workspaceId: input.workspaceId,
88
+ });
89
+ },
90
+ };
91
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@majapisoftwares/ai-usage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/majapisoftwares/platform.git",
10
+ "directory": "packages/ai-usage"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
31
+ "typecheck": "tsc --noEmit"
32
+ }
33
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.