-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai-cost.ts
More file actions
249 lines (227 loc) · 7.23 KB
/
Copy pathai-cost.ts
File metadata and controls
249 lines (227 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import {
clearCache,
readCache,
writeCache,
type EvenStorage,
} from "./live-cache";
import {
LEGACY_AI_PRICING_VERSION,
emptyAiUsageCharge,
mergeAiUsageCharge,
type AiUsageCharge,
} from "./ai-pricing";
export type AiUsage = {
readonly textInputTokens: number;
readonly cachedTextInputTokens: number;
readonly audioInputTokens: number;
readonly cachedAudioInputTokens: number;
readonly textOutputTokens: number;
readonly transcriptionAudioInputTokens: number;
readonly transcriptionTextOutputTokens: number;
readonly searchTextInputTokens: number;
readonly cachedSearchTextInputTokens: number;
readonly searchTextOutputTokens: number;
readonly webSearchCalls: number;
};
export type AiDailyUsage = {
readonly date: string;
readonly usage: AiUsage;
readonly charge: AiUsageCharge;
};
export const EMPTY_AI_USAGE: AiUsage = {
textInputTokens: 0,
cachedTextInputTokens: 0,
audioInputTokens: 0,
cachedAudioInputTokens: 0,
textOutputTokens: 0,
transcriptionAudioInputTokens: 0,
transcriptionTextOutputTokens: 0,
searchTextInputTokens: 0,
cachedSearchTextInputTokens: 0,
searchTextOutputTokens: 0,
webSearchCalls: 0,
};
const PRICE_PER_MILLION = {
textInputTokens: 4,
cachedTextInputTokens: 0.4,
audioInputTokens: 32,
cachedAudioInputTokens: 0.4,
textOutputTokens: 16,
transcriptionAudioInputTokens: 1.25,
transcriptionTextOutputTokens: 5,
searchTextInputTokens: 0.25,
cachedSearchTextInputTokens: 0,
searchTextOutputTokens: 2,
webSearchCalls: 10_000,
} as const satisfies Record<keyof AiUsage, number>;
function safeTokenCount(value: number): number {
return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}
export function addAiUsage(left: AiUsage, right: AiUsage): AiUsage {
return Object.fromEntries(
(Object.keys(EMPTY_AI_USAGE) as Array<keyof AiUsage>).map((key) => [
key,
safeTokenCount(left[key]) + safeTokenCount(right[key]),
]),
) as unknown as AiUsage;
}
export function estimateAiUsageUsd(usage: AiUsage): number {
return (Object.keys(PRICE_PER_MILLION) as Array<keyof AiUsage>)
.reduce(
(total, key) => total
+ safeTokenCount(usage[key]) * PRICE_PER_MILLION[key] / 1_000_000,
0,
);
}
function localDateKey(value: Date): string {
return [
value.getFullYear(),
String(value.getMonth() + 1).padStart(2, "0"),
String(value.getDate()).padStart(2, "0"),
].join("-");
}
export function addDailyAiUsage(
ledger: readonly AiDailyUsage[],
at: Date,
usage: AiUsage,
charge: AiUsageCharge = legacyCharge(usage),
): readonly AiDailyUsage[] {
const date = localDateKey(at);
const previousEntry = ledger.find((entry) => entry.date === date);
return [
...ledger.filter((entry) => entry.date !== date),
{
date,
usage: addAiUsage(previousEntry?.usage ?? EMPTY_AI_USAGE, usage),
charge: mergeAiUsageCharge(
previousEntry?.charge ?? emptyAiUsageCharge(),
charge,
),
},
].sort((left, right) => left.date.localeCompare(right.date)).slice(-400);
}
function legacyCharge(usage: AiUsage): AiUsageCharge {
return {
estimatedNanoUsd: Math.round(estimateAiUsageUsd(usage) * 1_000_000_000),
unpricedEvents: 0,
pricingVersions: [LEGACY_AI_PRICING_VERSION],
};
}
function usageInRange(
ledger: readonly AiDailyUsage[],
start: Date,
end: Date,
): AiUsage {
const startKey = localDateKey(start);
const endKey = localDateKey(end);
return ledger.reduce(
(total, entry) => entry.date >= startKey && entry.date <= endKey
? addAiUsage(total, entry.usage)
: total,
EMPTY_AI_USAGE,
);
}
export function usageForCurrentWeek(
ledger: readonly AiDailyUsage[],
now = new Date(),
): AiUsage {
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const day = start.getDay();
start.setDate(start.getDate() - (day === 0 ? 6 : day - 1));
return usageInRange(ledger, start, now);
}
export function usageForCurrentMonth(
ledger: readonly AiDailyUsage[],
now = new Date(),
): AiUsage {
const start = new Date(now.getFullYear(), now.getMonth(), 1);
return usageInRange(ledger, start, now);
}
function chargeInRange(
ledger: readonly AiDailyUsage[],
start: Date,
end: Date,
): AiUsageCharge {
const startKey = localDateKey(start);
const endKey = localDateKey(end);
return ledger.reduce(
(total, entry) => entry.date >= startKey && entry.date <= endKey
? mergeAiUsageCharge(total, entry.charge)
: total,
emptyAiUsageCharge(),
);
}
export function costSummaryForCurrentPeriod(
ledger: readonly AiDailyUsage[],
now = new Date(),
): { weekUsd: number; monthUsd: number; hasUnpricedUsage: boolean } {
const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const day = weekStart.getDay();
weekStart.setDate(weekStart.getDate() - (day === 0 ? 6 : day - 1));
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const week = chargeInRange(ledger, weekStart, now);
const month = chargeInRange(ledger, monthStart, now);
return {
weekUsd: week.estimatedNanoUsd / 1_000_000_000,
monthUsd: month.estimatedNanoUsd / 1_000_000_000,
hasUnpricedUsage: week.unpricedEvents > 0 || month.unpricedEvents > 0,
};
}
const LEGACY_USAGE_KEYS = Object.keys(EMPTY_AI_USAGE).filter((key) => (
!key.toLowerCase().includes("search")
));
function isUsage(value: unknown): value is AiUsage {
if (typeof value !== "object" || value === null) return false;
const item = value as Record<string, unknown>;
return LEGACY_USAGE_KEYS.every(
(key) => typeof item[key] === "number"
&& Number.isFinite(item[key])
&& (item[key] as number) >= 0,
);
}
function isUsageLedger(value: unknown): value is readonly AiDailyUsage[] {
return Array.isArray(value)
&& value.length <= 400
&& value.every((entry) => (
typeof entry === "object"
&& entry !== null
&& typeof entry.date === "string"
&& /^\d{4}-\d{2}-\d{2}$/.test(entry.date)
&& isUsage(entry.usage)
&& (
entry.charge === undefined
|| isCharge(entry.charge)
)
));
}
function isCharge(value: unknown): value is AiUsageCharge {
if (typeof value !== "object" || value === null) return false;
const item = value as Record<string, unknown>;
return typeof item.estimatedNanoUsd === "number"
&& Number.isFinite(item.estimatedNanoUsd)
&& item.estimatedNanoUsd >= 0
&& typeof item.unpricedEvents === "number"
&& Number.isFinite(item.unpricedEvents)
&& item.unpricedEvents >= 0
&& Array.isArray(item.pricingVersions)
&& item.pricingVersions.every((version) => typeof version === "string");
}
export async function resolveAiUsageLedger(
storage: EvenStorage,
): Promise<readonly AiDailyUsage[]> {
const ledger = await readCache(storage, "ai-usage", isUsageLedger) ?? [];
return ledger.map((entry) => ({
...entry,
usage: addAiUsage(EMPTY_AI_USAGE, entry.usage),
charge: entry.charge ?? legacyCharge(addAiUsage(EMPTY_AI_USAGE, entry.usage)),
}));
}
export function writeAiUsageLedger(
storage: EvenStorage,
ledger: readonly AiDailyUsage[],
): Promise<boolean> {
return writeCache(storage, "ai-usage", ledger.slice(-400));
}
export function clearAiUsageLedger(storage: EvenStorage): Promise<boolean> {
return clearCache(storage, "ai-usage");
}