Installation
npm install @aicostguard/sdk # or yarn add @aicostguard/sdk # or pnpm add @aicostguard/sdk
Configuration
import { CostGuard } from '@aicostguard/sdk';
const guard = new CostGuard({
apiKey: 'cg_your_key_here', // Required
projectId: 'my-project', // Optional — groups costs by project
environment: 'production', // Optional — dev | staging | production
baseUrl: 'https://api.aicostguard.com', // Optional — self-hosted override
flushInterval: 5000, // Optional — batch send interval (ms)
debug: false, // Optional — enable debug logging
});
Wrapping Providers
OpenAI
import OpenAI from 'openai'; const openai = guard.wrap(new OpenAI());
Anthropic
import Anthropic from '@anthropic-ai/sdk'; const anthropic = guard.wrap(new Anthropic());
Google Generative AI
import { GoogleGenerativeAI } from '@google/generative-ai';
const genai = guard.wrap(new GoogleGenerativeAI(apiKey));
Custom Metadata
Attach metadata to any request for fine-grained attribution:
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello' }],
}, {
costGuard: {
userId: 'user_123',
feature: 'customer-support',
tags: { sprint: '24', ticket: 'JIRA-456' },
},
});
Budget Alerts
await guard.budgets.create({
name: 'Production Daily Cap',
amount: 100, // $100
period: 'daily', // daily | weekly | monthly
alertThresholds: [50, 80, 100],
autoStop: true, // Pause API calls at 100%
notifyChannels: ['slack', 'email'],
});
Cost Query API
const costs = await guard.costs.query({
from: '2026-03-01',
to: '2026-03-15',
groupBy: ['model', 'feature'],
projectId: 'my-project',
});
console.log(costs);
// [{ model: 'gpt-4o', feature: 'chat', totalCost: 142.50, requests: 23400 }, ...]
Error Handling
try {
const chat = await openai.chat.completions.create({ ... });
} catch (error) {
// CostGuard never blocks your API calls
// If tracking fails, your LLM call still succeeds
// Errors are logged to guard.on('error', handler)
}
TypeScript Types
The SDK is fully typed. Key interfaces:
CostGuardConfig — constructor optionsCostEntry — individual cost recordBudgetConfig — budget alert settingsCostQuery / CostResult — query API types