@ai-cost-guard/sdk
v1.0.2
Published
Monitor every LLM API call and never get surprised by your AI bill again. Real-time cost tracking for OpenAI, Anthropic, Google Gemini, Cohere, Mistral, and 50+ models.
Downloads
66
Maintainers
Keywords
Readme
@ai-cost-guard/sdk
See exactly how much money your app spends on AI — for free.
Think of it like a bank statement for your AI API bills. Every time your code calls OpenAI, Anthropic, or Google AI, it costs money (charged per "token"). This SDK records every call automatically, counts the tokens, calculates the dollar cost, and sends it to your dashboard so you can see everything in one place.
What Does This Do?
| Problem | What this SDK fixes | |---------|-------------------| | Surprise AI bills at end of month | See costs live as they happen | | No idea which feature is expensive | Tag every call with a feature name | | Can't tell which model costs most | Per-model breakdown in your dashboard | | No alerts before you overspend | Set budget thresholds | | Different provider APIs everywhere | One unified SDK for all of them |
Before You Start — Get Your Free API Key
You cannot use this SDK without an API key. The key tells the server which project to save your cost data into. Getting one is free and takes less than 2 minutes.
Step 1 — Create a Free Account
Go to https://aicostguard.com and click the "Get Started" button (top-right corner).
Fill in:
- Your name
- Your email address
- A password
Click "Sign Up". You land on your dashboard automatically.
Step 2 — Create a Project
A project is a container for one app. One project = one API key = one set of cost data in your dashboard.
1. You are now on the Dashboard: https://aicostguard.com/dashboard
2. Click "Projects" in the left sidebar
3. Click the "New Project" button (top-right of the page)
4. Fill in:
Project Name e.g. My Chatbot App
Description e.g. Tracks GPT-4o costs for my support bot
5. Click "Create Project"
6. Your new project card appears on the Projects pageStep 3 — Copy Your API Key
1. On your project card, click the "API Keys" button
2. You will see a default API key that looks like:
acg_live_abc123def456ghi789...
3. Click "Copy" to copy it to your clipboard
4. Keep it safe — treat it like a passwordTip: Click "Generate New Key" at any time to get a fresh key.
Step 4 — Install the SDK
npm install @ai-cost-guard/sdk
# or
yarn add @ai-cost-guard/sdk
# or
pnpm add @ai-cost-guard/sdkStep 5 — Add Two Lines to Your Code
Replace acg_live_YOUR_KEY_HERE with the key you copied in Step 3.
import { createClient } from '@ai-cost-guard/sdk';
const monitor = createClient({
apiKey: 'acg_live_YOUR_KEY_HERE', // paste your key here
});Then add one tracking call after each AI request (see examples below).
Step 6 — See Your Costs in the Dashboard
After your app makes a few AI calls, open:
https://aicostguard.com/dashboard
You will see live cost data: total spend, cost per model, daily chart, and more.
OpenAI Integration (Full Working Example)
import OpenAI from 'openai';
import { createClient } from '@ai-cost-guard/sdk';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });
async function chat(userMessage: string) {
const startTime = Date.now();
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: userMessage }],
});
// One line to track the cost
await monitor.trackOpenAI({
model: response.model,
usage: response.usage!, // prompt_tokens + completion_tokens
latencyMs: Date.now() - startTime, // how long the call took
feature: 'chatbot', // tag so you can filter in dashboard
});
return response.choices[0].message.content;
}Anthropic (Claude) Integration
import Anthropic from '@anthropic-ai/sdk';
import { createClient } from '@ai-cost-guard/sdk';
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });
async function summarize(text: string) {
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [{ role: 'user', content: `Summarize: ${text}` }],
});
await monitor.trackAnthropic({
model: response.model,
usage: response.usage, // input_tokens + output_tokens
feature: 'summarizer',
});
return response.content[0].type === 'text' ? response.content[0].text : '';
}Google Gemini Integration
import { GoogleGenerativeAI } from '@google/generative-ai';
import { createClient } from '@ai-cost-guard/sdk';
const genai = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY!);
const monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });
async function generate(prompt: string) {
const model = genai.getGenerativeModel({ model: 'gemini-1.5-pro' });
const result = await model.generateContent(prompt);
const meta = result.response.usageMetadata!;
await monitor.trackGemini({
model: 'gemini-1.5-pro',
usage: {
promptTokenCount: meta.promptTokenCount,
candidatesTokenCount: meta.candidatesTokenCount,
},
feature: 'content-generator',
});
return result.response.text();
}Manual Tracking (Any Provider)
Use monitor.track() for any provider not listed above:
await monitor.track({
provider: 'openai', // required: provider name
model: 'gpt-4o', // required: model name
inputTokens: 1200, // required: prompt/input tokens
outputTokens: 300, // required: completion/output tokens
latencyMs: 342, // optional: response time in ms
feature: 'chatbot', // optional: tag for dashboard filtering
userId: 'user_abc123', // optional: track per-user costs
success: true, // optional: was the call successful?
metadata: { // optional: any extra data
endpoint: '/api/chat',
sessionId: 'sess_xyz',
},
});Track Per-User Costs
Pass userId to see how much each of your users is costing you:
await monitor.trackOpenAI({
model: response.model,
usage: response.usage!,
feature: 'chatbot',
userId: req.user.id, // any string that identifies your user
});In the dashboard under "Cost by User" you will see a breakdown per user.
Express.js Example
Track every AI call across your whole API:
import express from 'express';
import OpenAI from 'openai';
import { createClient } from '@ai-cost-guard/sdk';
const app = express();
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });
app.use(express.json());
app.post('/api/chat', async (req, res) => {
const start = Date.now();
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: req.body.messages,
});
await monitor.trackOpenAI({
model: response.model,
usage: response.usage!,
latencyMs: Date.now() - start,
feature: 'chat-api',
userId: req.headers['x-user-id'] as string,
});
res.json({ message: response.choices[0].message.content });
});
// Always flush before shutting down (see below)
process.on('SIGTERM', async () => {
await monitor.shutdown();
process.exit(0);
});
app.listen(3000);Configuration Options
const monitor = createClient({
apiKey: 'acg_live_...', // REQUIRED — your project API key
// Optional (all have sensible defaults)
debug: false, // Print debug logs to console (default: false)
batchEvents: true, // Collect and send in batches (default: true)
batchIntervalMs: 5000, // How often to send a batch, in ms (default: 5000)
maxBatchSize: 50, // Max events per batch (default: 50)
maxRetries: 3, // Retry failed sends (default: 3)
defaultFeature: 'my-app', // Tag every event with this label by default
maxEventsPerSecond: 100, // Client-side rate limit (default: 100)
});What does batchEvents mean?
By default the SDK collects events in memory and sends them all together every 5 seconds. This is more efficient (fewer HTTP requests) and does not slow down your API.
If you need events to appear in the dashboard instantly, set batchEvents: false.
Graceful Shutdown
Important: always call monitor.shutdown() before your process exits.
This flushes any events still waiting in the buffer — without it, the last few events may be lost.
process.on('SIGTERM', async () => {
await monitor.shutdown();
process.exit(0);
});
process.on('SIGINT', async () => {
await monitor.shutdown();
process.exit(0);
});Supported Providers and Models
| Provider | Tracking helper | Example models |
|----------|----------------|----------------|
| OpenAI | trackOpenAI() | gpt-4o, gpt-4o-mini, gpt-4-turbo, o1, o3-mini |
| Anthropic | trackAnthropic() | claude-3-5-sonnet, claude-3-5-haiku, claude-3-opus |
| Google | trackGemini() | gemini-1.5-pro, gemini-1.5-flash, gemini-2.0-flash |
| Cohere | trackCohere() | command-r-plus, command-r |
| Any other | track() | Pass provider and model as strings |
Requirements
- Node.js 18 or newer — needs the built-in
fetchAPI (available since Node 18) - A free AI Cost Guard account — create one at https://aicostguard.com
Troubleshooting
"apiKey is required" error
You forgot to pass the apiKey option to createClient(). Copy your key from:
https://aicostguard.com/dashboard/projects → open your project → click "API Keys".
"API key format may be invalid" warning
Your key must start with acg_live_ (production) or acg_test_ (testing).
Make sure you copied the full key with no extra spaces.
Events not showing in dashboard
- Wait up to 10 seconds — the default batch interval is 5 seconds.
- Turn on debug mode to see what is happening:
const monitor = createClient({ apiKey: 'acg_live_...', debug: true }); - Confirm your API key matches the project you are viewing.
"HTTP 401: Unauthorized" Your API key is wrong or has been deleted. Go to: https://aicostguard.com/dashboard/projects → open project → "API Keys" → copy a valid key.
"HTTP 403: Forbidden" Your project may have reached its plan event limit. Check at: https://aicostguard.com/dashboard
Events lost on shutdown
Add the SIGTERM / SIGINT handlers shown in the "Graceful Shutdown" section above.
Still stuck?
- Email: [email protected]
- GitHub Issues: https://github.com/aicostguard/sdk-js/issues
Related Tools
| Tool | What it does | How to get it |
|------|-------------|---------------|
| ai-cost-cli | See your costs in the terminal | npm install -g ai-cost-cli |
| Python SDK | Same SDK for Python | pip install ai-cost-guard-sdk |
Links
| | | |--|--| | Website | https://aicostguard.com | | Sign Up Free | https://aicostguard.com/signup | | Dashboard | https://aicostguard.com/dashboard | | Projects and API Keys | https://aicostguard.com/dashboard/projects | | npm | https://www.npmjs.com/package/@ai-cost-guard/sdk | | Report a Bug | https://github.com/aicostguard/sdk-js/issues |
License
MIT (c) AI Cost Guard — https://aicostguard.com
