AgentSea

Package

@lov3kaizen/agentsea-costs

Records LLM usage costs with attribution to users or features, and enforces spending budgets.

v1.2.1On npm

01Install

Install from npm into your project.

BASH
npm install @lov3kaizen/agentsea-costs

02Example

TS
import { createCostManager } from '@lov3kaizen/agentsea-costs';

const costManager = createCostManager({ currency: 'USD', defaultAttribution: { environment: 'production' } });
await costManager.trackAnthropicResponse(
  { model: 'claude-sonnet-4-6', usage: { input_tokens: 1500, output_tokens: 500 } },
  { attribution: { userId: 'user-123', feature: 'chat' } },
);
const summary = await costManager.getSummary({ startDate: new Date('2024-01-01'), endDate: new Date() });
console.log('Total cost: $' + summary.totalCost.toFixed(4));

03Key API

CostManager.track(options) / trackOpenAIResponse(response)
Records the cost of one model call.
CostManager.getSummary(query)
Returns total cost for a date range.
CostManager.getTopUsers() / getTopModels() / getTopFeatures()
Lists the highest-cost users, models or features.
BudgetManager.createBudget({ name, limit, period, scope, actions })
Defines a budget with warning thresholds and actions.
ModelPricingRegistry.calculateCost(provider, model, inputTokens, outputTokens)
Works out the cost of a call from a model's pricing.

04Caveats

  • Records are held in memory by default. To persist them, pass an onFlush handler that writes to your store.
  • Token counting uses tiktoken for OpenAI models only. No counting method is documented for other providers.
  • The supported-models table lists older Claude models than the examples. Check pricing before relying on it.
  • Requires Node.js 20 or later. SQLite, Postgres, Stripe and NestJS support are optional peer dependencies.

05Scoped tracking

A scoped tracker adds the same attribution to every call it records. Use one per user, project or feature.

TS
const userTracker = costManager.scoped({ userId: 'user-123', environment: 'production' });
await userTracker.trackAnthropicResponse({
  model: 'claude-sonnet-4-6',
  usage: { input_tokens: 500, output_tokens: 200 },
});
CostManager.trackError(options)
Records a failed call, with the error message and the estimated input tokens.
CostManager.countTokens(...) / estimateCost(...)
Counts tokens and estimates a call's cost before you make it.

06Budgets

BudgetManager is a separate class. Pass it the same storage you use for records, then create budgets with a period, a scope and warning thresholds.

TS
import { BudgetManager, BufferStorage } from '@lov3kaizen/agentsea-costs';

const budgets = new BudgetManager({}, new BufferStorage());
const budget = await budgets.createBudget({
  name: 'Monthly AI Budget',
  limit: 1000,
  period: 'monthly',
  scope: 'global',
  warningThresholds: [50, 80, 90],
});

budgets.on('budget:warning', (alert) => console.log('Warning:', alert.message));
budgets.on('budget:exceeded', (alert) => console.log('Exceeded:', alert.message));

Scopes other than global take a scopeId, for example one budget per user with scope: 'user' and scopeId: 'user-123'.

07Reports and events

TS
const topModels = await costManager.getTopModels({ limit: 5 });
const topUsers = await costManager.getTopUsers({ limit: 10 });

costManager.on('cost:recorded', (record) => {
  console.log('Tracked:', record.model, record.cost.totalCost);
});
costManager.on('error', (error) => console.error('Cost tracking error:', error.message));

getCostsByDimension and getCostTrends break spend down by model, user or feature, and over time.

08Storage

BufferStorage keeps records in memory and flushes them on a timer or when it is full. Your onFlush handler writes them to your own store.

TS
import { BufferStorage } from '@lov3kaizen/agentsea-costs';

const storage = new BufferStorage({
  maxRecords: 10000,
  autoFlushInterval: 30000, // 30 seconds
  onFlush: async (records) => {
    // Persist records to your database
  },
});