@tokonomics/sdk
v1.0.0
Published
Official JavaScript/TypeScript SDK for Tokonomics — AI cost metering proxy for any LLM provider
Downloads
156
Maintainers
Readme
@tokonomics/sdk
Official JavaScript/TypeScript SDK for Tokonomics — the budget-first AI cost metering proxy for any LLM provider.
Track every token, set budget alerts, and never get surprised by your AI bill again. Works with OpenAI, Anthropic, DeepSeek, Gemini, xAI, and any OpenAI-compatible API.
Installation
npm install @tokonomics/sdkQuick Start
import { Tokonomics } from '@tokonomics/sdk';
const tk = new Tokonomics({ apiKey: 'mk_your_api_key' });
// Proxy an OpenAI request — same format, automatic cost tracking
const response = await tk.openai.chat({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'What is AI cost metering?' }],
tags: { team: 'growth', feature: 'chatbot' },
});
console.log(response.choices[0].message.content);Providers
OpenAI
const response = await tk.openai.chat({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello' }],
max_tokens: 500,
});Anthropic
const response = await tk.anthropic.messages({
model: 'claude-sonnet-4-6',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello' }],
});
console.log(response.content[0].text);DeepSeek
const response = await tk.deepseek.chat({
model: 'deepseek-chat',
messages: [{ role: 'user', content: 'Hello' }],
});Gemini
const response = await tk.gemini.chat({
model: 'gemini-2.0-flash',
messages: [{ role: 'user', content: 'Hello' }],
});xAI (Grok)
const response = await tk.xai.chat({
model: 'grok-3',
messages: [{ role: 'user', content: 'Hello' }],
});Streaming
for await (const chunk of tk.openai.chatStream({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Tell me a story' }],
})) {
const data = JSON.parse(chunk);
process.stdout.write(data.choices?.[0]?.delta?.content ?? '');
}Analytics
// Current month spend summary
const summary = await tk.analytics.summary();
console.log(`Spent $${summary.current_month_spend} of $${summary.monthly_budget}`);
// Daily spend for last 30 days
const daily = await tk.analytics.daily({ days: 30 });
// Spend grouped by tag
const byTeam = await tk.analytics.byTag('team');
// Raw usage events
const events = await tk.analytics.events({ limit: 100 });Cost Attribution with Tags
Tag every request with custom metadata for per-team, per-feature, or per-customer cost tracking:
const response = await tk.openai.chat({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Summarize this document' }],
tags: {
team: 'engineering',
feature: 'doc-summary',
customer: 'acme-corp',
environment: 'production',
},
});Then query costs by any tag:
const byFeature = await tk.analytics.byTag('feature');
// [{ tag_value: 'doc-summary', cost_usd: 12.50, request_count: 850 }, ...]Error Handling
import {
Tokonomics,
BudgetExceededError,
RateLimitError,
AuthenticationError,
} from '@tokonomics/sdk';
try {
const response = await tk.openai.chat({ ... });
} catch (error) {
if (error instanceof BudgetExceededError) {
console.log('Monthly budget exceeded — upgrade your plan or wait for reset');
} else if (error instanceof RateLimitError) {
console.log(`Rate limited — retry after ${error.retryAfter}s`);
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key');
}
}Configuration
const tk = new Tokonomics({
apiKey: 'mk_your_api_key', // Required — your Tokonomics API key
baseUrl: 'https://tokonomics.ca', // Optional — default
timeout: 120_000, // Optional — request timeout in ms (default: 120s)
});Migrating from Direct API Calls
Replace your base URL and add your Tokonomics API key. That's it — request and response formats stay identical:
- const response = await fetch('https://api.openai.com/v1/chat/completions', {
- headers: { 'Authorization': 'Bearer sk-...' },
+ const response = await fetch('https://tokonomics.ca/proxy/openai/chat/completions', {
+ headers: { 'Authorization': 'Bearer mk_...' },
...
});Or use this SDK for a cleaner interface with TypeScript types and streaming support.
Requirements
- Node.js 18+ (uses native
fetch) - A free Tokonomics account
Links
License
MIT
