Optional observability, monitoring, and cost tracking package for AI Kit. Track API usage, monitor performance, set cost alerts, and visualize metrics with React dashboards.
Many developers building MVPs or prototypes don't need comprehensive monitoring from day one. By extracting observability features into a separate package, we:
- Reduce core bundle size by ~30KB (from ~45KB to ~35KB)
- Improve tree-shaking - only import what you need
- Speed up cold starts - fewer dependencies to load
- Keep costs predictable - opt-in to advanced monitoring
Install this package when you're ready to monitor production usage, track costs, or need detailed insights into your AI application's performance.
npm install @ainative/ai-kit-observability
# Or with pnpm
pnpm add @ainative/ai-kit-observability
# Or with yarn
yarn add @ainative/ai-kit-observability- Usage Tracking - Track API calls, tokens, and costs across providers
- Cost Monitoring - Real-time cost calculation for OpenAI, Anthropic, and more
- Alerts - Set thresholds and get notified when limits are reached
- Instrumentation - Automatic tracing for LLM calls, tools, and agents
- Query Monitoring - Detect patterns, anomalies, and performance issues
- Reporting - Generate usage reports in JSON, CSV, Markdown, or HTML
- React Dashboards - Pre-built components for usage visualization
import { UsageTracker, InMemoryStorage } from '@ainative/ai-kit-observability';
// Create a tracker with in-memory storage
const tracker = new UsageTracker({
storage: new InMemoryStorage(),
autoTrack: true,
});
// Track an API call
await tracker.track({
provider: 'openai',
model: 'gpt-4',
operation: 'completion',
promptTokens: 150,
completionTokens: 50,
totalTokens: 200,
userId: 'user-123',
conversationId: 'conv-456',
});
// Get aggregated usage
const usage = await tracker.getAggregatedUsage({
startDate: new Date('2024-01-01'),
endDate: new Date(),
});
console.log('Total cost:', usage.totalCost);
console.log('Total tokens:', usage.totalTokens);import { UsageTracker, FileStorage } from '@ainative/ai-kit-observability';
// Use file-based storage for persistence
const tracker = new UsageTracker({
storage: new FileStorage({
filepath: './data/usage.json',
autoSave: true,
}),
});import { AlertManager } from '@ainative/ai-kit-observability';
const alertManager = new AlertManager({
rules: [
{
id: 'daily-cost-limit',
name: 'Daily Cost Limit',
type: 'cost',
threshold: 100, // $100 per day
window: '24h',
severity: 'high',
},
{
id: 'token-limit',
name: 'Token Usage Alert',
type: 'usage',
threshold: 1000000, // 1M tokens
window: '1h',
severity: 'warning',
},
],
channels: [
{
type: 'console',
enabled: true,
},
{
type: 'webhook',
url: 'https://your-app.com/api/alerts',
enabled: true,
},
],
});
// Check usage against rules
await alertManager.check(tracker);import { createQueryMonitor } from '@ainative/ai-kit-observability';
const monitor = createQueryMonitor({
enabled: true,
sampleRate: 1.0, // Track 100% of queries
detectPatterns: true,
detectAnomalies: true,
});
// Monitor a query
monitor.startQuery('query-1', {
provider: 'openai',
model: 'gpt-4',
userId: 'user-123',
});
// ... perform the query ...
monitor.endQuery('query-1', {
tokens: 200,
cost: 0.004,
success: true,
});
// Get metrics
const metrics = monitor.getMetrics();
console.log('Average latency:', metrics.avgLatency);
console.log('Error rate:', metrics.errorRate);Automatically track all LLM calls, tool executions, and agent operations:
import {
InstrumentationManager,
OpenAIInterceptor,
ToolCallInterceptor,
} from '@ainative/ai-kit-observability';
const instrumentation = new InstrumentationManager({
enabled: true,
tracingBackend: {
name: 'console',
export: (span) => console.log('Trace:', span),
},
metricsBackend: {
name: 'console',
record: (metric) => console.log('Metric:', metric),
},
});
// Add interceptors
instrumentation.addInterceptor(new OpenAIInterceptor());
instrumentation.addInterceptor(new ToolCallInterceptor());
// Your LLM calls will now be automatically trackedimport { ReportGenerator, UsageTrackerAdapter } from '@ainative/ai-kit-observability';
const generator = new ReportGenerator({
dataSource: new UsageTrackerAdapter(tracker),
defaultFormat: 'markdown',
});
// Generate a daily report
const report = await generator.generate({
type: 'usage',
startDate: new Date('2024-01-01'),
endDate: new Date('2024-01-02'),
format: 'markdown',
sections: ['summary', 'by-model', 'by-user', 'costs'],
});
console.log(report.content);import { UsageMetrics, CostAnalysis } from '@ainative/ai-kit-observability/react';
function DashboardPage() {
return (
<div>
<h1>AI Usage Dashboard</h1>
<UsageMetrics tracker={tracker} refreshInterval={30000} />
<CostAnalysis
tracker={tracker}
groupBy="model"
timeRange="7d"
/>
</div>
);
}import { ModelComparison } from '@ainative/ai-kit-observability/react';
function ComparisonPage() {
return (
<ModelComparison
tracker={tracker}
models={['gpt-4', 'gpt-3.5-turbo', 'claude-3-opus']}
metrics={['cost', 'latency', 'tokens']}
/>
);
}Main class for tracking API usage and costs.
class UsageTracker {
constructor(config: TrackingConfig);
// Track a single API call
track(record: UsageRecord): Promise<void>;
// Get aggregated usage data
getAggregatedUsage(filter?: UsageFilter): Promise<AggregatedUsage>;
// Get usage by provider
getByProvider(provider: LLMProvider): Promise<ProviderUsage>;
// Get usage by model
getByModel(model: string): Promise<ModelUsage>;
// Export data
export(format: ExportFormat): Promise<string>;
}Manage cost and usage alerts.
class AlertManager {
constructor(config: AlertConfig);
// Add a new alert rule
addRule(rule: AlertRule): void;
// Check usage against all rules
check(tracker: UsageTracker): Promise<Alert[]>;
// Get triggered alerts
getAlerts(filter?: { severity?: AlertSeverity }): Alert[];
}Automatic instrumentation for tracing and metrics.
class InstrumentationManager {
constructor(config: InstrumentationConfig);
// Add an interceptor
addInterceptor(interceptor: Interceptor): void;
// Start a span
startSpan(name: string, context?: SpanContext): Span;
// Record a metric
recordMetric(metric: Metric): void;
}Monitor query patterns and performance.
class QueryMonitor {
constructor(config: QueryMonitorConfig);
// Start tracking a query
startQuery(id: string, metadata: any): void;
// End tracking a query
endQuery(id: string, result: any): void;
// Get metrics
getMetrics(): QueryMetrics;
// Get detected patterns
getPatterns(): QueryPattern[];
}Fast, ephemeral storage for development and testing.
const storage = new InMemoryStorage({
maxRecords: 10000, // Keep last 10k records
});JSON file-based persistence.
const storage = new FileStorage({
filepath: './data/usage.json',
autoSave: true,
saveInterval: 60000, // Save every minute
});Implement your own storage backend:
import { StorageBackend, UsageRecord } from '@ainative/ai-kit-observability';
class DatabaseStorage implements StorageBackend {
async save(record: UsageRecord): Promise<void> {
// Save to database
}
async load(filter?: UsageFilter): Promise<UsageRecord[]> {
// Load from database
}
async clear(): Promise<void> {
// Clear database
}
}The package includes built-in pricing for major providers:
import {
OPENAI_PRICING,
ANTHROPIC_PRICING,
calculateCost
} from '@ainative/ai-kit-observability';
// Calculate cost for a specific call
const cost = calculateCost({
provider: 'openai',
model: 'gpt-4',
promptTokens: 150,
completionTokens: 50,
});
console.log('Cost:', cost); // $0.0115Pricing is automatically updated, but you can override it:
import { getModelPricing } from '@ainative/ai-kit-observability';
const pricing = getModelPricing('openai', 'gpt-4');
pricing.promptPrice = 0.03; // Custom pricingGenerate reports in multiple formats:
- JSON - Structured data for programmatic processing
- CSV - Import into Excel, Google Sheets, etc.
- Markdown - Human-readable reports for documentation
- HTML - Rich formatted reports with charts
// Generate HTML report with charts
const report = await generator.generate({
type: 'usage',
format: 'html',
startDate: new Date('2024-01-01'),
endDate: new Date('2024-01-31'),
sections: ['summary', 'charts', 'breakdown'],
});
// Save to file
fs.writeFileSync('report.html', report.content);Begin with basic usage tracking in development, add alerts and dashboards as you scale:
// Development
const tracker = new UsageTracker({
storage: new InMemoryStorage(),
});
// Production
const tracker = new UsageTracker({
storage: new DatabaseStorage(),
autoTrack: true,
batchSize: 100,
flushInterval: 5000,
});Configure alerts based on your budget and usage patterns:
const alertManager = new AlertManager({
rules: [
// Warning at 80% of budget
{ threshold: 80, severity: 'warning' },
// Critical at 95% of budget
{ threshold: 95, severity: 'critical' },
],
});For high-throughput applications, use sampling to reduce overhead:
const monitor = createQueryMonitor({
sampleRate: 0.1, // Track 10% of queries
detectPatterns: true,
});Schedule regular usage reports:
// Generate weekly reports
setInterval(async () => {
const report = await generator.generate({
type: 'usage',
format: 'markdown',
startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
endDate: new Date(),
});
await sendReport(report);
}, 7 * 24 * 60 * 60 * 1000);Full TypeScript support with comprehensive type definitions:
import type {
UsageRecord,
AggregatedUsage,
AlertRule,
QueryMetrics,
} from '@ainative/ai-kit-observability';If you were previously using observability features from @ainative/ai-kit-core, update your imports:
// Before
import { UsageTracker } from '@ainative/ai-kit-core/observability';
// After
import { UsageTracker } from '@ainative/ai-kit-observability';The API remains the same, only the package name has changed.
See the examples directory for complete working examples:
- Basic Usage Tracking - Simple console-based tracking
- Cost Dashboard - React dashboard with charts
- Alert System - Email and webhook notifications
- Production Monitoring - Full production setup with instrumentation
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.
MIT License - see LICENSE for details.
- Documentation: https://ainative.studio/ai-kit
- Issues: https://github.com/AINative-Studio/ai-kit/issues
- Discord: https://discord.com/invite/paipalooza-studio
Made with ❤️ by AINative Studio