Package Exports
- supertokentracker
- supertokentracker/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (supertokentracker) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
supertokentracker
Automatically track Google Gemini token usage with built-in logging and analytics
Track every Gemini API call with zero configuration. Perfect for monitoring usage, debugging, cost analysis, and building analytics.
Features
✅ Automatic Tracking - Drop-in replacement for @google/genai
✅ Backward Compatible - Works with code written for legacy @google/generative-ai
✅ Local Storage - Save to JSON files on your machine
✅ Cloud Storage - Optional cloud sync with tokentracker.dev (coming soon)
✅ Full Request Data - Captures prompts, responses, token usage, and errors
✅ Stream Support - Works with both generateContent and generateContentStream
✅ TypeScript - Full type safety included
Installation
npm install supertokentracker @google/genaiQuick Start
Local Storage (JSON File)
import { TokenTracker } from "supertokentracker";
const tracker = new TokenTracker({
apiKey: process.env.GEMINI_API_KEY,
});
const response = await tracker.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain quantum computing in 3 sentences",
});
console.log(response.text);
// Get all tracked requests
const history = await tracker.getTrackedRequests();
console.log(`Total requests: ${history.length}`);
console.log(`Tokens used: ${history[0].usage?.totalTokens}`);Data is automatically saved to ./gemini-tracker-logs.json.
Cloud Storage (Coming Soon)
Sync your tracking data to the cloud for team analytics and dashboards:
import { TokenTracker } from "supertokentracker";
const tracker = new TokenTracker({
apiKey: process.env.GEMINI_API_KEY,
remoteStorage: {
apiKey: "your-tokentracker-api-key", // Get from tokentracker.dev
projectName: "my-project",
},
});
const response = await tracker.models.generateContent({
model: "gemini-2.5-flash",
contents: "Hello world",
});Sign up at tokentracker.dev to get your API key and access the analytics dashboard.
Configuration
TrackerOptions
interface TrackerOptions {
// Gemini API credentials
apiKey?: string;
apiVersion?: string;
location?: string;
project?: string;
vertexai?: boolean;
// Storage mode (optional - inferred from config if omitted)
storage?: "local" | "file" | "remote";
// File storage options
localStorage?: {
filePath?: string; // Default: './gemini-tracker-logs.json'
autoSave?: boolean; // Default: true
};
fileStorage?: {
filePath?: string;
autoSave?: boolean;
};
// Remote storage options
remoteStorage?: {
endpoint?: string; // Default: https://api.tokentracker.dev/api/track
apiKey: string; // Your API key for authentication
projectName?: string;
timeout?: number; // Default: 10000ms
retries?: number; // Default: 3
retryDelay?: number; // Default: 1000ms (exponential backoff)
};
}
// If `remoteStorage` is provided the tracker will automatically use cloud storage.
// If `fileStorage` (or legacy `localStorage`) is provided the tracker uses file storage.
// You can still set `storage` explicitly to override the default behaviour.What Gets Tracked
Every request captures:
{
id: "uuid-v4",
timestamp: "2025-10-17T10:30:00.000Z",
model: "gemini-2.5-flash",
prompt: { /* your input */ },
response: { /* full API response */ },
usage: {
promptTokens: 7,
completionTokens: 15,
totalTokens: 22
},
error: null // or error details if request failed
}API Methods
getTrackedRequests()
Retrieve all tracked requests (local or remote):
const requests = await tracker.getTrackedRequests();loadHistory() (Local only)
Load previously saved requests from disk:
await tracker.loadHistory();saveHistory() (Local only)
Manually save tracked requests to disk:
await tracker.saveHistory();clearHistory()
Clear all tracked requests from memory:
tracker.clearHistory();Use Cases
1. Development Debugging
Track all requests during development to debug prompts and responses.
2. Cost Monitoring
Analyze token usage to optimize costs:
const history = await tracker.getTrackedRequests();
const totalTokens = history.reduce(
(sum, req) => sum + (req.usage?.totalTokens || 0),
0
);
console.log(`Total tokens used: ${totalTokens}`);3. Analytics Dashboard
Build usage dashboards with tracked data:
- Requests per day
- Average response time
- Most used models
- Token consumption trends
4. Multi-tenant SaaS
Track usage per customer with cloud storage:
- Monitor API usage across your customer base
- Implement usage-based billing
- Set limits per subscription tier
Error Handling
The tracker gracefully handles storage failures without breaking your app:
// If storage fails, the API call still succeeds
const response = await tracker.models.generateContent({...});
// Response is returned even if tracking failsFailed storage attempts are logged to console.error but don't throw exceptions.
Stream Support
Streaming responses are fully supported:
const stream = await tracker.models.generateContentStream({
model: "gemini-2.5-flash",
contents: "Write a story",
});
for await (const chunk of stream) {
process.stdout.write(chunk.text);
}
// Full response is tracked after stream completesTypeScript
Full type definitions included:
import {
TokenTracker,
TrackedRequest,
TrackerOptions,
StorageMode,
} from "supertokentracker";Backward Compatibility
This package wraps the new @google/genai SDK but maintains full backward compatibility with code written for the legacy @google/generative-ai SDK.
Both access patterns work:
const result = await tracker.models.generateContent({...});
// ✅ NEW SDK style (@google/genai)
console.log(result.candidates);
console.log(result.usageMetadata);
// ✅ OLD SDK style (@google/generative-ai) - ALSO WORKS!
console.log(result.response.candidates);
console.log(result.response.usageMetadata);This means you can:
- Migrate from
@google/generative-aiwithout changing your code - Use code examples from either SDK documentation
- Mix both access patterns in the same project
Note: The legacy @google/generative-ai package is deprecated and support ends August 31, 2025. This tracker helps you migrate to the new SDK while maintaining compatibility with your existing code.
Contributing
Contributions welcome! Please open an issue or PR.
License
MIT
Links
- Google Gemini API Docs
- Cloud Dashboard (Coming Soon)
- GitHub Issues