Node.js - Automatic Tracking

Automatic tracking uses wrapper classes that handle token counting and tracking for you.

📖 Real-World Scenario

You're building a chatbot and making dozens of OpenAI API calls. Manually extracting usage data and calling sendUsage() for each one is tedious and error-prone. You just want the tracking to happen automatically.

💡 Solution

Use Paygent's automatic wrappers. Just wrap your API client and add 3 tracking parameters:

automatic-openai.ts
1
2import { PaygentClient, PaygentOpenAI } from '@paygent_org/paygent-sdk-node';
3import OpenAI from 'openai';
4
5// Initialize Paygent client
6const paygentClient = PaygentClient.newClient(process.env.PAYGENT_API_KEY);
7
8// Initialize OpenAI client
9const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
10
11// Create PaygentOpenAI wrapper for automatic tracking
12const paygentOpenai = new PaygentOpenAI(openai, paygentClient);
13
14// Make OpenAI call with automatic tracking
15// Just add 3 tracking parameters to your normal OpenAI call!
16const response = await paygentOpenai.chat.completions.create({
17  indicator: 'message-sent',
18  external_agent_id: 'chatbot-agent',
19  external_customer_id: 'customer-123',
20  
21  model: 'gpt-4o',
22  messages: [{ role: 'user', content: 'Hello!' }]
23});
24
25
26// Usage automatically tracked! No manual code needed!

✅ Result

Zero manual tracking code. Every OpenAI call is automatically tracked with accurate token counts and costs. 60% less code!

Pro-Tip: Auto-Onboarding

Before your first AI call, use createOrGetCustomer with your user's ID. This allows Paygent to automatically handle data isolation and billing attribution for new users.

Manual vs Automatic

FeatureManual TrackingAutomatic Tracking
Code Lines~40 lines~15 lines
Token CountingManual extractionAutomatic
Error RiskCan forget to trackImpossible to miss
MaintenanceHighLow
RecommendedFor custom use cases✓ For most users

Was this page helpful?

Need help? Contact us at support@withpaygent.com