{"_id":"@ai-cost-guard/sdk","name":"@ai-cost-guard/sdk","dist-tags":{"latest":"1.0.2"},"versions":{"1.0.2":{"name":"@ai-cost-guard/sdk","version":"1.0.2","description":"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.","main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","require":"./dist/index.js"}},"scripts":{"build":"tsc","dev":"tsc --watch","clean":"rm -rf dist","prepublishOnly":"npm run build"},"keywords":["ai","llm","cost","cost-tracking","cost-monitoring","cost-optimization","openai","gpt-4","gpt-4o","chatgpt","anthropic","claude","gemini","google-ai","cohere","mistral","token","token-counting","token-tracking","api-cost","api-monitoring","llm-monitoring","llm-cost","llm-ops","mlops","ai-ops","budget","budget-alerts","analytics","observability","ai-observability","optimization","usage-tracking","billing"],"author":{"name":"aicostguard"},"license":"MIT","homepage":"https://aicostguard.com","repository":{"type":"git","url":"git+https://github.com/aicostguard/sdk-js.git"},"bugs":{"url":"https://github.com/aicostguard/sdk-js/issues"},"engines":{"node":">=18.0.0"},"devDependencies":{"typescript":"^5.7.0","@types/node":"^22.0.0"},"_id":"@ai-cost-guard/sdk@1.0.2","gitHead":"1d757ac2346c5f93ee0c3fdbe12aee149f0c7bb7","_nodeVersion":"22.19.0","_npmVersion":"10.9.3","dist":{"integrity":"sha512-D9QCWOXZD5levPngMkLlxc/EIw68UWmoy6nmRo6kQ0q/RBT1BCJWDjDAtiusrQRAhCkrvvmSsndSm3voayA3uw==","shasum":"cbab614d410718d7d28bf4d9ecb548ba2d364b35","tarball":"https://registry.npmjs.org/@ai-cost-guard/sdk/-/sdk-1.0.2.tgz","fileCount":14,"unpackedSize":42167,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIE7PNeFpt3XXk/M19yzYgfaPGIlyW1jOIQDscrSzAmLrAiA6GsVEg80GMakYZtn/DWcS6VLy3sY8xy3Fp2zGriiAbw=="}]},"_npmUser":{"name":"aicostguard","email":"km003355@gmail.com"},"directories":{},"maintainers":[{"name":"aicostguard","email":"km003355@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/sdk_1.0.2_1773055111474_0.20047053612036625"},"_hasShrinkwrap":false}},"time":{"created":"2026-03-09T11:18:31.393Z","1.0.2":"2026-03-09T11:18:31.638Z","modified":"2026-03-09T11:18:31.915Z"},"maintainers":[{"name":"aicostguard","email":"km003355@gmail.com"}],"description":"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.","homepage":"https://aicostguard.com","keywords":["ai","llm","cost","cost-tracking","cost-monitoring","cost-optimization","openai","gpt-4","gpt-4o","chatgpt","anthropic","claude","gemini","google-ai","cohere","mistral","token","token-counting","token-tracking","api-cost","api-monitoring","llm-monitoring","llm-cost","llm-ops","mlops","ai-ops","budget","budget-alerts","analytics","observability","ai-observability","optimization","usage-tracking","billing"],"repository":{"type":"git","url":"git+https://github.com/aicostguard/sdk-js.git"},"author":{"name":"aicostguard"},"bugs":{"url":"https://github.com/aicostguard/sdk-js/issues"},"license":"MIT","readme":"# @ai-cost-guard/sdk\n\n> **See exactly how much money your app spends on AI — for free.**\n\nThink of it like a **bank statement for your AI API bills**.\nEvery time your code calls OpenAI, Anthropic, or Google AI, it costs money (charged per \"token\").\nThis SDK records every call automatically, counts the tokens, calculates the dollar cost, and\nsends it to your dashboard so you can see everything in one place.\n\n[![npm version](https://img.shields.io/npm/v/@ai-cost-guard/sdk?color=blue)](https://www.npmjs.com/package/@ai-cost-guard/sdk)\n[![npm downloads](https://img.shields.io/npm/dm/@ai-cost-guard/sdk)](https://www.npmjs.com/package/@ai-cost-guard/sdk)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n---\n\n## What Does This Do?\n\n| Problem | What this SDK fixes |\n|---------|-------------------|\n| Surprise AI bills at end of month | See costs **live** as they happen |\n| No idea which feature is expensive | Tag every call with a **feature name** |\n| Can't tell which model costs most | **Per-model breakdown** in your dashboard |\n| No alerts before you overspend | Set **budget thresholds** |\n| Different provider APIs everywhere | **One unified SDK** for all of them |\n\n---\n\n## Before You Start — Get Your Free API Key\n\n**You cannot use this SDK without an API key.**\nThe key tells the server which project to save your cost data into.\nGetting one is free and takes less than 2 minutes.\n\n---\n\n### Step 1 — Create a Free Account\n\nGo to **https://aicostguard.com** and click the **\"Get Started\"** button (top-right corner).\n\nFill in:\n- Your name\n- Your email address\n- A password\n\nClick **\"Sign Up\"**. You land on your dashboard automatically.\n\n---\n\n### Step 2 — Create a Project\n\nA **project** is a container for one app.\nOne project = one API key = one set of cost data in your dashboard.\n\n```\n1.  You are now on the Dashboard:  https://aicostguard.com/dashboard\n2.  Click \"Projects\" in the left sidebar\n3.  Click the \"New Project\" button (top-right of the page)\n4.  Fill in:\n      Project Name   e.g.  My Chatbot App\n      Description    e.g.  Tracks GPT-4o costs for my support bot\n5.  Click \"Create Project\"\n6.  Your new project card appears on the Projects page\n```\n\n---\n\n### Step 3 — Copy Your API Key\n\n```\n1.  On your project card, click the \"API Keys\" button\n2.  You will see a default API key that looks like:\n        acg_live_abc123def456ghi789...\n3.  Click \"Copy\" to copy it to your clipboard\n4.  Keep it safe — treat it like a password\n```\n\n> **Tip:** Click \"Generate New Key\" at any time to get a fresh key.\n\n---\n\n### Step 4 — Install the SDK\n\n```bash\nnpm install @ai-cost-guard/sdk\n# or\nyarn add @ai-cost-guard/sdk\n# or\npnpm add @ai-cost-guard/sdk\n```\n\n---\n\n### Step 5 — Add Two Lines to Your Code\n\nReplace `acg_live_YOUR_KEY_HERE` with the key you copied in Step 3.\n\n```typescript\nimport { createClient } from '@ai-cost-guard/sdk';\n\nconst monitor = createClient({\n  apiKey: 'acg_live_YOUR_KEY_HERE',  // paste your key here\n});\n```\n\nThen add one tracking call after each AI request (see examples below).\n\n---\n\n### Step 6 — See Your Costs in the Dashboard\n\nAfter your app makes a few AI calls, open:\n\n**https://aicostguard.com/dashboard**\n\nYou will see live cost data: total spend, cost per model, daily chart, and more.\n\n---\n\n## OpenAI Integration (Full Working Example)\n\n```typescript\nimport OpenAI from 'openai';\nimport { createClient } from '@ai-cost-guard/sdk';\n\nconst openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\nconst monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });\n\nasync function chat(userMessage: string) {\n  const startTime = Date.now();\n\n  const response = await openai.chat.completions.create({\n    model: 'gpt-4o',\n    messages: [{ role: 'user', content: userMessage }],\n  });\n\n  // One line to track the cost\n  await monitor.trackOpenAI({\n    model: response.model,\n    usage: response.usage!,              // prompt_tokens + completion_tokens\n    latencyMs: Date.now() - startTime,   // how long the call took\n    feature: 'chatbot',                  // tag so you can filter in dashboard\n  });\n\n  return response.choices[0].message.content;\n}\n```\n\n---\n\n## Anthropic (Claude) Integration\n\n```typescript\nimport Anthropic from '@anthropic-ai/sdk';\nimport { createClient } from '@ai-cost-guard/sdk';\n\nconst anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\nconst monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });\n\nasync function summarize(text: string) {\n  const response = await anthropic.messages.create({\n    model: 'claude-3-5-sonnet-20241022',\n    max_tokens: 1024,\n    messages: [{ role: 'user', content: `Summarize: ${text}` }],\n  });\n\n  await monitor.trackAnthropic({\n    model: response.model,\n    usage: response.usage,   // input_tokens + output_tokens\n    feature: 'summarizer',\n  });\n\n  return response.content[0].type === 'text' ? response.content[0].text : '';\n}\n```\n\n---\n\n## Google Gemini Integration\n\n```typescript\nimport { GoogleGenerativeAI } from '@google/generative-ai';\nimport { createClient } from '@ai-cost-guard/sdk';\n\nconst genai = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY!);\nconst monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });\n\nasync function generate(prompt: string) {\n  const model = genai.getGenerativeModel({ model: 'gemini-1.5-pro' });\n  const result = await model.generateContent(prompt);\n  const meta = result.response.usageMetadata!;\n\n  await monitor.trackGemini({\n    model: 'gemini-1.5-pro',\n    usage: {\n      promptTokenCount: meta.promptTokenCount,\n      candidatesTokenCount: meta.candidatesTokenCount,\n    },\n    feature: 'content-generator',\n  });\n\n  return result.response.text();\n}\n```\n\n---\n\n## Manual Tracking (Any Provider)\n\nUse `monitor.track()` for any provider not listed above:\n\n```typescript\nawait monitor.track({\n  provider: 'openai',        // required: provider name\n  model: 'gpt-4o',           // required: model name\n  inputTokens: 1200,         // required: prompt/input tokens\n  outputTokens: 300,         // required: completion/output tokens\n  latencyMs: 342,            // optional: response time in ms\n  feature: 'chatbot',        // optional: tag for dashboard filtering\n  userId: 'user_abc123',     // optional: track per-user costs\n  success: true,             // optional: was the call successful?\n  metadata: {                // optional: any extra data\n    endpoint: '/api/chat',\n    sessionId: 'sess_xyz',\n  },\n});\n```\n\n---\n\n## Track Per-User Costs\n\nPass `userId` to see how much each of your users is costing you:\n\n```typescript\nawait monitor.trackOpenAI({\n  model: response.model,\n  usage: response.usage!,\n  feature: 'chatbot',\n  userId: req.user.id,   // any string that identifies your user\n});\n```\n\nIn the dashboard under **\"Cost by User\"** you will see a breakdown per user.\n\n---\n\n## Express.js Example\n\nTrack every AI call across your whole API:\n\n```typescript\nimport express from 'express';\nimport OpenAI from 'openai';\nimport { createClient } from '@ai-cost-guard/sdk';\n\nconst app = express();\nconst openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\nconst monitor = createClient({ apiKey: 'acg_live_YOUR_KEY_HERE' });\n\napp.use(express.json());\n\napp.post('/api/chat', async (req, res) => {\n  const start = Date.now();\n\n  const response = await openai.chat.completions.create({\n    model: 'gpt-4o',\n    messages: req.body.messages,\n  });\n\n  await monitor.trackOpenAI({\n    model: response.model,\n    usage: response.usage!,\n    latencyMs: Date.now() - start,\n    feature: 'chat-api',\n    userId: req.headers['x-user-id'] as string,\n  });\n\n  res.json({ message: response.choices[0].message.content });\n});\n\n// Always flush before shutting down (see below)\nprocess.on('SIGTERM', async () => {\n  await monitor.shutdown();\n  process.exit(0);\n});\n\napp.listen(3000);\n```\n\n---\n\n## Configuration Options\n\n```typescript\nconst monitor = createClient({\n  apiKey: 'acg_live_...',        // REQUIRED — your project API key\n\n  // Optional (all have sensible defaults)\n  debug: false,                  // Print debug logs to console (default: false)\n  batchEvents: true,             // Collect and send in batches (default: true)\n  batchIntervalMs: 5000,         // How often to send a batch, in ms (default: 5000)\n  maxBatchSize: 50,              // Max events per batch (default: 50)\n  maxRetries: 3,                 // Retry failed sends (default: 3)\n  defaultFeature: 'my-app',      // Tag every event with this label by default\n  maxEventsPerSecond: 100,       // Client-side rate limit (default: 100)\n});\n```\n\n### What does `batchEvents` mean?\n\nBy default the SDK collects events in memory and sends them all together every 5 seconds.\nThis is more efficient (fewer HTTP requests) and does not slow down your API.\n\nIf you need events to appear in the dashboard instantly, set `batchEvents: false`.\n\n---\n\n## Graceful Shutdown\n\n**Important:** always call `monitor.shutdown()` before your process exits.\nThis flushes any events still waiting in the buffer — without it, the last few events may be lost.\n\n```typescript\nprocess.on('SIGTERM', async () => {\n  await monitor.shutdown();\n  process.exit(0);\n});\n\nprocess.on('SIGINT', async () => {\n  await monitor.shutdown();\n  process.exit(0);\n});\n```\n\n---\n\n## Supported Providers and Models\n\n| Provider | Tracking helper | Example models |\n|----------|----------------|----------------|\n| **OpenAI** | `trackOpenAI()` | gpt-4o, gpt-4o-mini, gpt-4-turbo, o1, o3-mini |\n| **Anthropic** | `trackAnthropic()` | claude-3-5-sonnet, claude-3-5-haiku, claude-3-opus |\n| **Google** | `trackGemini()` | gemini-1.5-pro, gemini-1.5-flash, gemini-2.0-flash |\n| **Cohere** | `trackCohere()` | command-r-plus, command-r |\n| **Any other** | `track()` | Pass `provider` and `model` as strings |\n\n---\n\n## Requirements\n\n- **Node.js 18 or newer** — needs the built-in `fetch` API (available since Node 18)\n- A **free AI Cost Guard account** — create one at https://aicostguard.com\n\n---\n\n## Troubleshooting\n\n**\"apiKey is required\" error**\nYou forgot to pass the `apiKey` option to `createClient()`. Copy your key from:\nhttps://aicostguard.com/dashboard/projects → open your project → click \"API Keys\".\n\n**\"API key format may be invalid\" warning**\nYour key must start with `acg_live_` (production) or `acg_test_` (testing).\nMake sure you copied the full key with no extra spaces.\n\n**Events not showing in dashboard**\n- Wait up to 10 seconds — the default batch interval is 5 seconds.\n- Turn on debug mode to see what is happening:\n  ```typescript\n  const monitor = createClient({ apiKey: 'acg_live_...', debug: true });\n  ```\n- Confirm your API key matches the project you are viewing.\n\n**\"HTTP 401: Unauthorized\"**\nYour API key is wrong or has been deleted. Go to:\nhttps://aicostguard.com/dashboard/projects → open project → \"API Keys\" → copy a valid key.\n\n**\"HTTP 403: Forbidden\"**\nYour project may have reached its plan event limit. Check at:\nhttps://aicostguard.com/dashboard\n\n**Events lost on shutdown**\nAdd the `SIGTERM` / `SIGINT` handlers shown in the \"Graceful Shutdown\" section above.\n\n**Still stuck?**\n- Email: info@aicostguard.com\n- GitHub Issues: https://github.com/aicostguard/sdk-js/issues\n\n---\n\n## Related Tools\n\n| Tool | What it does | How to get it |\n|------|-------------|---------------|\n| **[ai-cost-cli](https://www.npmjs.com/package/ai-cost-cli)** | See your costs in the terminal | `npm install -g ai-cost-cli` |\n| **[Python SDK](https://pypi.org/project/ai-cost-guard-sdk/)** | Same SDK for Python | `pip install ai-cost-guard-sdk` |\n\n---\n\n## Links\n\n| | |\n|--|--|\n| Website | https://aicostguard.com |\n| Sign Up Free | https://aicostguard.com/signup |\n| Dashboard | https://aicostguard.com/dashboard |\n| Projects and API Keys | https://aicostguard.com/dashboard/projects |\n| npm | https://www.npmjs.com/package/@ai-cost-guard/sdk |\n| Report a Bug | https://github.com/aicostguard/sdk-js/issues |\n\n---\n\n## License\n\nMIT (c) AI Cost Guard — https://aicostguard.com\n","readmeFilename":"README.md","_rev":"1-4a2fb2e034ca1d160e898a01c167703a"}