@lov3kaizen/agentsea-costs 0.5.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.
- package/LICENSE +21 -0
- package/README.md +469 -0
- package/dist/index.d.ts +1607 -0
- package/dist/index.js +2867 -0
- package/dist/index.js.map +1 -0
- package/package.json +85 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 lovekaizen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
# @lov3kaizen/agentsea-costs
|
|
2
|
+
|
|
3
|
+
AI cost management platform with real-time tracking, budget enforcement, and optimization recommendations.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Real-time Cost Tracking** - Track API calls and costs as they happen
|
|
8
|
+
- **Token Counting** - Accurate token counting using tiktoken for OpenAI models
|
|
9
|
+
- **Model Pricing Registry** - Up-to-date pricing for major AI providers
|
|
10
|
+
- **Budget Management** - Set and enforce budgets at multiple scopes
|
|
11
|
+
- **Cost Attribution** - Attribute costs to users, agents, projects, features
|
|
12
|
+
- **Analytics** - Cost trends, forecasting, and anomaly detection
|
|
13
|
+
- **Alerts** - Threshold-based notifications via multiple channels
|
|
14
|
+
- **Optimization** - AI-powered cost optimization recommendations
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @lov3kaizen/agentsea-costs
|
|
20
|
+
# or
|
|
21
|
+
pnpm add @lov3kaizen/agentsea-costs
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Quick Start
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import {
|
|
28
|
+
CostManager,
|
|
29
|
+
createCostManager,
|
|
30
|
+
BufferStorage,
|
|
31
|
+
} from '@lov3kaizen/agentsea-costs';
|
|
32
|
+
|
|
33
|
+
// Create a cost manager
|
|
34
|
+
const costManager = createCostManager({
|
|
35
|
+
currency: 'USD',
|
|
36
|
+
defaultAttribution: {
|
|
37
|
+
environment: 'production',
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Track an Anthropic API call
|
|
42
|
+
await costManager.trackAnthropicResponse(
|
|
43
|
+
{
|
|
44
|
+
model: 'claude-3-5-sonnet-20241022',
|
|
45
|
+
usage: {
|
|
46
|
+
input_tokens: 1500,
|
|
47
|
+
output_tokens: 500,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
attribution: {
|
|
52
|
+
userId: 'user-123',
|
|
53
|
+
feature: 'chat',
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
// Get cost summary
|
|
59
|
+
const summary = await costManager.getSummary({
|
|
60
|
+
startDate: new Date('2024-01-01'),
|
|
61
|
+
endDate: new Date(),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
console.log(`Total cost: $${summary.totalCost.toFixed(4)}`);
|
|
65
|
+
console.log(`Total tokens: ${summary.totalTokens}`);
|
|
66
|
+
console.log(`Requests: ${summary.requestCount}`);
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Cost Tracking
|
|
70
|
+
|
|
71
|
+
### Track API Calls
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
import { CostManager, BufferStorage } from '@lov3kaizen/agentsea-costs';
|
|
75
|
+
|
|
76
|
+
// With persistent storage
|
|
77
|
+
const storage = new BufferStorage();
|
|
78
|
+
const costManager = new CostManager({ storage });
|
|
79
|
+
|
|
80
|
+
// Track any LLM call
|
|
81
|
+
await costManager.track({
|
|
82
|
+
provider: 'anthropic',
|
|
83
|
+
model: 'claude-3-5-sonnet-20241022',
|
|
84
|
+
tokens: {
|
|
85
|
+
inputTokens: 1000,
|
|
86
|
+
outputTokens: 500,
|
|
87
|
+
totalTokens: 1500,
|
|
88
|
+
},
|
|
89
|
+
latencyMs: 1200,
|
|
90
|
+
attribution: {
|
|
91
|
+
userId: 'user-123',
|
|
92
|
+
agentId: 'agent-456',
|
|
93
|
+
feature: 'document-analysis',
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// Track OpenAI responses directly
|
|
98
|
+
await costManager.trackOpenAIResponse({
|
|
99
|
+
model: 'gpt-4o',
|
|
100
|
+
usage: {
|
|
101
|
+
prompt_tokens: 1000,
|
|
102
|
+
completion_tokens: 500,
|
|
103
|
+
total_tokens: 1500,
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// Track errors
|
|
108
|
+
await costManager.trackError({
|
|
109
|
+
provider: 'openai',
|
|
110
|
+
model: 'gpt-4o',
|
|
111
|
+
error: 'Rate limit exceeded',
|
|
112
|
+
estimatedInputTokens: 1000,
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Scoped Tracking
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
// Create scoped trackers for specific contexts
|
|
120
|
+
const userTracker = costManager.scoped({
|
|
121
|
+
userId: 'user-123',
|
|
122
|
+
environment: 'production',
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// All calls through this tracker include the scope
|
|
126
|
+
await userTracker.track({
|
|
127
|
+
provider: 'anthropic',
|
|
128
|
+
model: 'claude-3-5-sonnet-20241022',
|
|
129
|
+
tokens: {
|
|
130
|
+
inputTokens: 500,
|
|
131
|
+
outputTokens: 200,
|
|
132
|
+
totalTokens: 700,
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Token Counting
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import { TokenCounter, ModelPricingRegistry } from '@lov3kaizen/agentsea-costs';
|
|
141
|
+
|
|
142
|
+
const registry = new ModelPricingRegistry();
|
|
143
|
+
const counter = new TokenCounter(registry);
|
|
144
|
+
|
|
145
|
+
// Count tokens
|
|
146
|
+
const result = await counter.countTokens({
|
|
147
|
+
text: 'Hello, how can I help you today?',
|
|
148
|
+
model: 'claude-3-5-sonnet-20241022',
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
console.log(`Tokens: ${result.tokens}`);
|
|
152
|
+
console.log(`Estimated cost: $${result.estimatedInputCost}`);
|
|
153
|
+
|
|
154
|
+
// Estimate cost before making a call
|
|
155
|
+
const estimate = await counter.estimateCost({
|
|
156
|
+
input: 'Your prompt here...',
|
|
157
|
+
model: 'claude-3-5-sonnet-20241022',
|
|
158
|
+
estimatedOutputTokens: 1000,
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
console.log(`Estimated total: $${estimate.estimatedCost.toFixed(4)}`);
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Model Pricing
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
import { ModelPricingRegistry } from '@lov3kaizen/agentsea-costs';
|
|
168
|
+
|
|
169
|
+
const registry = new ModelPricingRegistry();
|
|
170
|
+
|
|
171
|
+
// Get pricing for a model
|
|
172
|
+
const pricing = registry.getPricing('anthropic', 'claude-3-5-sonnet-20241022');
|
|
173
|
+
console.log(`Input: $${pricing.inputPricePerMillion}/1M tokens`);
|
|
174
|
+
console.log(`Output: $${pricing.outputPricePerMillion}/1M tokens`);
|
|
175
|
+
|
|
176
|
+
// Calculate cost
|
|
177
|
+
const cost = registry.calculateCost(
|
|
178
|
+
'anthropic',
|
|
179
|
+
'claude-3-5-sonnet-20241022',
|
|
180
|
+
1000, // input tokens
|
|
181
|
+
500, // output tokens
|
|
182
|
+
);
|
|
183
|
+
console.log(`Total: $${cost.totalCost.toFixed(4)}`);
|
|
184
|
+
|
|
185
|
+
// Find cheapest model with requirements
|
|
186
|
+
const cheapest = registry.findCheapestModel({
|
|
187
|
+
requireVision: true,
|
|
188
|
+
requireFunctionCalling: true,
|
|
189
|
+
minContextWindow: 100000,
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// Compare models
|
|
193
|
+
const comparison = registry.comparePricing(
|
|
194
|
+
'claude-3-5-sonnet-20241022',
|
|
195
|
+
'gpt-4o',
|
|
196
|
+
{ input: 1000000, output: 500000 }, // sample workload
|
|
197
|
+
);
|
|
198
|
+
|
|
199
|
+
console.log(
|
|
200
|
+
`${comparison.cheaperModel} is ${comparison.percentageDiff}% cheaper`,
|
|
201
|
+
);
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Budget Management
|
|
205
|
+
|
|
206
|
+
```typescript
|
|
207
|
+
import { BudgetManager, BufferStorage } from '@lov3kaizen/agentsea-costs';
|
|
208
|
+
|
|
209
|
+
const storage = new BufferStorage();
|
|
210
|
+
const budgetManager = new BudgetManager({}, storage);
|
|
211
|
+
|
|
212
|
+
// Create a budget
|
|
213
|
+
const budget = await budgetManager.createBudget({
|
|
214
|
+
name: 'Monthly AI Budget',
|
|
215
|
+
limit: 1000, // $1000
|
|
216
|
+
period: 'monthly',
|
|
217
|
+
scope: 'global',
|
|
218
|
+
warningThresholds: [50, 80, 90],
|
|
219
|
+
actions: [
|
|
220
|
+
{ threshold: 80, action: 'notify', notifyEmails: ['team@example.com'] },
|
|
221
|
+
{ threshold: 100, action: 'block' },
|
|
222
|
+
],
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
// Check budget before making a call
|
|
226
|
+
const check = await budgetManager.checkBudget({
|
|
227
|
+
estimatedCost: 0.05,
|
|
228
|
+
attribution: { userId: 'user-123' },
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
if (check.allowed) {
|
|
232
|
+
// Proceed with API call
|
|
233
|
+
} else {
|
|
234
|
+
console.log(`Blocked: ${check.reason}`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Get budget usage
|
|
238
|
+
const usage = await budgetManager.getUsage(budget.id);
|
|
239
|
+
console.log(`Used: $${usage.currentUsage} of $${usage.limit}`);
|
|
240
|
+
console.log(`${usage.usagePercentage.toFixed(1)}% used`);
|
|
241
|
+
|
|
242
|
+
// Listen for budget events
|
|
243
|
+
budgetManager.on('budget:warning', (alert) => {
|
|
244
|
+
console.log(`Warning: ${alert.message}`);
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
budgetManager.on('budget:exceeded', (alert) => {
|
|
248
|
+
console.log(`Exceeded: ${alert.message}`);
|
|
249
|
+
});
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### Budget Scopes
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
// User-level budget
|
|
256
|
+
await budgetManager.createBudget({
|
|
257
|
+
name: 'User Daily Limit',
|
|
258
|
+
limit: 10,
|
|
259
|
+
period: 'daily',
|
|
260
|
+
scope: 'user',
|
|
261
|
+
scopeId: 'user-123',
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
// Project budget
|
|
265
|
+
await budgetManager.createBudget({
|
|
266
|
+
name: 'Project Budget',
|
|
267
|
+
limit: 500,
|
|
268
|
+
period: 'monthly',
|
|
269
|
+
scope: 'project',
|
|
270
|
+
scopeId: 'project-abc',
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
// Feature-specific budget
|
|
274
|
+
await budgetManager.createBudget({
|
|
275
|
+
name: 'Document Processing',
|
|
276
|
+
limit: 100,
|
|
277
|
+
period: 'weekly',
|
|
278
|
+
scope: 'feature',
|
|
279
|
+
scopeId: 'document-analysis',
|
|
280
|
+
});
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
## Storage Adapters
|
|
284
|
+
|
|
285
|
+
### Buffer Storage (In-Memory)
|
|
286
|
+
|
|
287
|
+
```typescript
|
|
288
|
+
import { BufferStorage } from '@lov3kaizen/agentsea-costs';
|
|
289
|
+
|
|
290
|
+
const storage = new BufferStorage({
|
|
291
|
+
maxRecords: 10000,
|
|
292
|
+
autoFlushInterval: 30000, // 30 seconds
|
|
293
|
+
onFlush: async (records) => {
|
|
294
|
+
// Persist records to external storage
|
|
295
|
+
console.log(`Flushing ${records.length} records`);
|
|
296
|
+
},
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
## Analytics
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
// Get cost summary
|
|
304
|
+
const summary = await costManager.getSummary({
|
|
305
|
+
startDate: new Date('2024-01-01'),
|
|
306
|
+
endDate: new Date(),
|
|
307
|
+
providers: ['anthropic', 'openai'],
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
// Get costs by dimension
|
|
311
|
+
const byModel = await costManager.getCostsByDimension('model', {
|
|
312
|
+
startDate: new Date('2024-01-01'),
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
byModel.forEach((m) => {
|
|
316
|
+
console.log(
|
|
317
|
+
`${m.value}: $${m.totalCost.toFixed(2)} (${m.percentage.toFixed(1)}%)`,
|
|
318
|
+
);
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
// Get cost trends
|
|
322
|
+
const trends = await costManager.getCostTrends({
|
|
323
|
+
granularity: 'day',
|
|
324
|
+
startDate: new Date('2024-01-01'),
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
// Get top consumers
|
|
328
|
+
const topUsers = await costManager.getTopUsers({ limit: 10 });
|
|
329
|
+
const topModels = await costManager.getTopModels({ limit: 5 });
|
|
330
|
+
const topFeatures = await costManager.getTopFeatures({ limit: 5 });
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
## Event Handling
|
|
334
|
+
|
|
335
|
+
```typescript
|
|
336
|
+
costManager.on('cost:recorded', (record) => {
|
|
337
|
+
console.log(
|
|
338
|
+
`Tracked: ${record.model} - $${record.cost.totalCost.toFixed(4)}`,
|
|
339
|
+
);
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
costManager.on('cost:batch', ({ records }) => {
|
|
343
|
+
console.log(`Batch saved: ${records.length} records`);
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
costManager.on('budget:warning', (alert) => {
|
|
347
|
+
sendSlackNotification(alert.message);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
costManager.on('budget:exceeded', (alert) => {
|
|
351
|
+
sendPagerDutyAlert(alert);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
costManager.on('error', (error) => {
|
|
355
|
+
console.error('Cost tracking error:', error.message);
|
|
356
|
+
});
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
## Supported Providers
|
|
360
|
+
|
|
361
|
+
| Provider | Models |
|
|
362
|
+
| --------- | -------------------------------------------------------- |
|
|
363
|
+
| Anthropic | Claude 3.5 Sonnet, Claude 3.5 Haiku, Claude 3 Opus, etc. |
|
|
364
|
+
| OpenAI | GPT-4o, GPT-4o-mini, GPT-4 Turbo, o1, etc. |
|
|
365
|
+
| Google | Gemini 1.5 Pro, Gemini 1.5 Flash, Gemini 2.0 |
|
|
366
|
+
| Mistral | Mistral Large, Mistral Small, Codestral |
|
|
367
|
+
| Cohere | Command R+, Command R |
|
|
368
|
+
|
|
369
|
+
## API Reference
|
|
370
|
+
|
|
371
|
+
### CostManager
|
|
372
|
+
|
|
373
|
+
The main entry point for cost management.
|
|
374
|
+
|
|
375
|
+
```typescript
|
|
376
|
+
interface CostManagerOptions {
|
|
377
|
+
currency?: string; // Default: 'USD'
|
|
378
|
+
autoFlushInterval?: number; // Default: 30000ms
|
|
379
|
+
bufferSize?: number; // Default: 100
|
|
380
|
+
realTimeTracking?: boolean; // Default: true
|
|
381
|
+
defaultAttribution?: Partial<CostAttribution>;
|
|
382
|
+
storage?: CostStorageAdapter;
|
|
383
|
+
pricingRegistry?: ModelPricingRegistry;
|
|
384
|
+
}
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
### BudgetManager
|
|
388
|
+
|
|
389
|
+
Manages budgets and enforces limits.
|
|
390
|
+
|
|
391
|
+
```typescript
|
|
392
|
+
interface BudgetConfig {
|
|
393
|
+
id: string;
|
|
394
|
+
name: string;
|
|
395
|
+
limit: number;
|
|
396
|
+
currency: string;
|
|
397
|
+
period: 'hourly' | 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly';
|
|
398
|
+
scope: 'global' | 'user' | 'agent' | 'project' | 'team' | 'feature';
|
|
399
|
+
scopeId?: string;
|
|
400
|
+
warningThresholds?: number[];
|
|
401
|
+
actions?: BudgetThresholdAction[];
|
|
402
|
+
enabled: boolean;
|
|
403
|
+
}
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
### ModelPricingRegistry
|
|
407
|
+
|
|
408
|
+
Manages model pricing information.
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
interface ModelPricing {
|
|
412
|
+
model: string;
|
|
413
|
+
provider: AIProvider;
|
|
414
|
+
inputPricePerMillion: number;
|
|
415
|
+
outputPricePerMillion: number;
|
|
416
|
+
cacheReadPricePerMillion?: number;
|
|
417
|
+
cacheWritePricePerMillion?: number;
|
|
418
|
+
contextWindow?: number;
|
|
419
|
+
maxOutputTokens?: number;
|
|
420
|
+
currency: string;
|
|
421
|
+
}
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
## Types
|
|
425
|
+
|
|
426
|
+
All types are exported from the package:
|
|
427
|
+
|
|
428
|
+
```typescript
|
|
429
|
+
import type {
|
|
430
|
+
// Cost
|
|
431
|
+
CostRecord,
|
|
432
|
+
CostAttribution,
|
|
433
|
+
CostSummary,
|
|
434
|
+
TokenUsage,
|
|
435
|
+
CostBreakdown,
|
|
436
|
+
|
|
437
|
+
// Pricing
|
|
438
|
+
ModelPricing,
|
|
439
|
+
TokenCountResult,
|
|
440
|
+
CostEstimateResult,
|
|
441
|
+
|
|
442
|
+
// Budget
|
|
443
|
+
BudgetConfig,
|
|
444
|
+
BudgetUsage,
|
|
445
|
+
BudgetCheckResult,
|
|
446
|
+
|
|
447
|
+
// Attribution
|
|
448
|
+
AttributionDimension,
|
|
449
|
+
AttributionSummary,
|
|
450
|
+
|
|
451
|
+
// Analytics
|
|
452
|
+
AnalyticsQuery,
|
|
453
|
+
AnalyticsResult,
|
|
454
|
+
ForecastResult,
|
|
455
|
+
|
|
456
|
+
// Alerts
|
|
457
|
+
AlertRule,
|
|
458
|
+
Alert,
|
|
459
|
+
NotificationConfig,
|
|
460
|
+
|
|
461
|
+
// Storage
|
|
462
|
+
CostStorageAdapter,
|
|
463
|
+
StorageStats,
|
|
464
|
+
} from '@lov3kaizen/agentsea-costs';
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
## License
|
|
468
|
+
|
|
469
|
+
MIT
|