Vai al contenuto principale
Perfetto per app SaaS, chatbot AI, strumenti di generazione di contenuti e qualsiasi applicazione alimentata da LLM che necessita di fatturazione basata sull’uso.

Inizio Veloce

Inizia con il monitoraggio automatico dei token LLM in soli 2 minuti:
1

Installa l'SDK

Installa i Blueprint di Ingestione di Dodo Payments:
npm install @dodopayments/ingestion-blueprints
2

Ottieni le tue Chiavi API

Avrai bisogno di due chiavi API:
  • Chiave API di Dodo Payments: Ottienila dal Dashboard di Dodo Payments
  • Chiave API del Fornitore LLM: Da AI SDK, OpenAI, Anthropic, Groq, ecc.
Conserva le tue chiavi API in modo sicuro nelle variabili d’ambiente. Non commetterle mai nel controllo di versione.
3

Crea un Misuratore in Dodo Payments

Prima di monitorare l’uso, crea un misuratore nel tuo dashboard di Dodo Payments:
  1. Accedi al Dashboard di Dodo Payments
  2. Naviga a Prodotti → Misuratori
  3. Clicca su “Crea Misuratore”
  4. Configura il tuo misuratore:
    • Nome Misuratore: Scegli un nome descrittivo (es. “Uso Token LLM”)
    • Nome Evento: Imposta un identificatore evento unico (es. llm.chat_completion)
    • Tipo di Aggregazione: Seleziona sum per sommare i conteggi dei token
    • Su Proprietà: Scegli cosa monitorare:
      • inputTokens - Monitora i token di input/prompt
      • outputTokens - Monitora i token di output/completamento (inclusi i token di ragionamento quando applicabile)
      • totalTokens - Monitora i token combinati di input + output
Il Nome Evento che imposti qui deve corrispondere esattamente a ciò che passi all’SDK (case-sensitive).
Per istruzioni dettagliate, consulta la Guida alla Fatturazione Basata sull’Uso.
4

Monitora l'Uso dei Token

Avvolgi il tuo client LLM e inizia a monitorare automaticamente:
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import { generateText } from 'ai';
import { google } from '@ai-sdk/google';

const llmTracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
  eventName: 'aisdk.usage',
});

const client = llmTracker.wrap({
  client: { generateText },
  customerId: 'customer_123'
});

const response = await client.generateText({
  model: google('gemini-2.0-flash'),
  prompt: 'Hello!',
  maxOutputTokens: 500
});

console.log('Usage:', response.usage);
Ecco fatto! Ogni chiamata API ora monitora automaticamente l’uso dei token e invia eventi a Dodo Payments per la fatturazione.

Configurazione

Configurazione del Tracker

Crea un tracker una sola volta all’avvio dell’applicazione con questi parametri richiesti:
apiKey
string
obbligatorio
La tua chiave API di Dodo Payments. Ottienila dalla pagina delle Chiavi API.
apiKey: process.env.DODO_PAYMENTS_API_KEY
environment
string
obbligatorio
La modalità ambiente per il tracker.
  • test_mode - Usa per sviluppo e test
  • live_mode - Usa per produzione
environment: 'test_mode' // or 'live_mode'
Usa sempre test_mode durante lo sviluppo per evitare di influenzare le metriche di produzione.
eventName
string
obbligatorio
Il nome dell’evento che attiva il tuo misuratore. Deve corrispondere esattamente a ciò che hai configurato nel tuo misuratore di Dodo Payments (case-sensitive).
eventName: 'llm.chat_completion'
Questo nome evento collega il tuo utilizzo monitorato al misuratore corretto per i calcoli di fatturazione.

Configurazione del Wrapper

Quando avvolgi il tuo client LLM, fornisci questi parametri:
client
object
obbligatorio
La tua istanza del client LLM (OpenAI, Anthropic, Groq, ecc.).
client: openai
customerId
string
obbligatorio
L’identificatore cliente unico per la fatturazione. Questo dovrebbe corrispondere al tuo ID cliente in Dodo Payments.
customerId: 'customer_123'
Usa l’ID utente della tua applicazione o l’ID cliente per garantire una fatturazione accurata per cliente.
metadata
object
Dati aggiuntivi opzionali da allegare all’evento di monitoraggio. Utile per filtrare e analizzare.
metadata: {
  feature: 'chat',
  userTier: 'premium',
  sessionId: 'session_123',
  modelVersion: 'gpt-4'
}

Esempio Completo di Configurazione

import { createLLMTracker } from "@dodopayments/ingestion-blueprints";
import { generateText } from "ai";
import { google } from "@ai-sdk/google";
import "dotenv/config";

async function aiSdkExample() {
  console.log("🤖 AI SDK Simple Usage Example\n");

  try {
    // 1. Create tracker
    const llmTracker = createLLMTracker({
      apiKey: process.env.DODO_PAYMENTS_API_KEY!,
      environment: "test_mode",
      eventName: "your_meter_event_name",
    });

    // 2. Wrap the ai-sdk methods
    const client = llmTracker.wrap({
      client: { generateText },
      customerId: "customer_123",
      metadata: {
        provider: "ai-sdk",
      },
    });

    // 3. Use the wrapped function
    const response = await client.generateText({
      model: google("gemini-2.5-flash"),
      prompt: "Hello, I am a cool guy! Tell me a fun fact.",
      maxOutputTokens: 500,
    });

    console.log(response);
    console.log(response.usage);
    console.log("✅ Automatically tracked for customer\n");
  } catch (error) {
    console.error(error);
  }
}

aiSdkExample().catch(console.error);
Monitoraggio Automatico: L’SDK monitora automaticamente l’uso dei token in background senza modificare la risposta. Il tuo codice rimane pulito e identico a quello che utilizza gli SDK del fornitore originale.

Fornitori Supportati

Il LLM Blueprint funziona senza problemi con tutti i principali fornitori e aggregatori di LLM:
Monitora l’uso con l’AI SDK di Vercel per supporto universale LLM.
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import { generateText } from 'ai';
import { google } from '@ai-sdk/google';

const llmTracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
  eventName: 'aisdk.usage',
});

const client = llmTracker.wrap({
  client: { generateText },
  customerId: 'customer_123',
  metadata: {
    model: 'gemini-2.0-flash',
    feature: 'chat'
  }
});

const response = await client.generateText({
  model: google('gemini-2.0-flash'),
  prompt: 'Explain neural networks',
  maxOutputTokens: 500
});

console.log('Usage:', response.usage);
Metriche Monitorate:
  • inputTokensinputTokens
  • outputTokens + reasoningTokensoutputTokens
  • totalTokenstotalTokens
  • Nome del modello
Quando si utilizzano modelli capaci di ragionamento tramite AI SDK (come Google Gemini 2.5 Flash con modalità di pensiero), i token di ragionamento sono automaticamente inclusi nel conteggio dei outputTokens per una fatturazione accurata.
Monitora l’uso dei token su oltre 200 modelli tramite l’API unificata di OpenRouter.
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import OpenAI from 'openai';

// OpenRouter uses OpenAI-compatible API
const openrouter = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: process.env.OPENROUTER_API_KEY
});

const tracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
  eventName: 'openrouter.usage'
});

const client = tracker.wrap({ 
  client: openrouter, 
  customerId: 'user_123',
  metadata: { provider: 'openrouter' }
});

const response = await client.chat.completions.create({
  model: 'qwen/qwen3-max',
  messages: [{ role: 'user', content: 'What is machine learning?' }],
  max_tokens: 500
});

console.log('Response:', response.choices[0].message.content);
console.log('Usage:', response.usage);
Metriche Monitorate:
  • prompt_tokensinputTokens
  • completion_tokensoutputTokens
  • total_tokenstotalTokens
  • Nome del modello
OpenRouter fornisce accesso a modelli di OpenAI, Anthropic, Google, Meta e molti altri fornitori tramite una singola API.
Monitora automaticamente l’uso dei token dai modelli GPT di OpenAI.
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const tracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
  eventName: 'openai.usage'
});

const client = tracker.wrap({ 
  client: openai, 
  customerId: 'user_123' 
});

// All OpenAI methods work automatically
const response = await client.chat.completions.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Explain quantum computing' }]
});

console.log('Total tokens:', response.usage.total_tokens);
Metriche Monitorate:
  • prompt_tokensinputTokens
  • completion_tokensoutputTokens
  • total_tokenstotalTokens
  • Nome del modello
Monitora l’uso dei token dai modelli Claude di Anthropic.
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

const tracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
  eventName: 'anthropic.usage'
});

const client = tracker.wrap({ 
  client: anthropic, 
  customerId: 'user_123' 
});

const response = await client.messages.create({
  model: 'claude-sonnet-4-0',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Explain machine learning' }]
});

console.log('Input tokens:', response.usage.input_tokens);
console.log('Output tokens:', response.usage.output_tokens);
Metriche Monitorate:
  • input_tokensinputTokens
  • output_tokensoutputTokens
  • Calcolato totalTokens
  • Nome del modello
Monitora l’inferenza LLM ultra-veloce con Groq.
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import Groq from 'groq-sdk';

const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });

const tracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
  eventName: 'groq.usage'
});

const client = tracker.wrap({ 
  client: groq, 
  customerId: 'user_123' 
});

const response = await client.chat.completions.create({
  model: 'llama-3.1-8b-instant',
  messages: [{ role: 'user', content: 'What is AI?' }]
});

console.log('Tokens:', response.usage);
Metriche Monitorate:
  • prompt_tokensinputTokens
  • completion_tokensoutputTokens
  • total_tokenstotalTokens
  • Nome del modello
Monitora l’uso dei token dai modelli Gemini di Google tramite l’AI SDK di Google GenAI.
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import { GoogleGenAI } from '@google/genai';

const googleGenai = new GoogleGenAI({ 
  apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY 
});

const tracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'test_mode',
  eventName: 'gemini.usage'
});

const client = tracker.wrap({ 
  client: googleGenai, 
  customerId: 'user_123' 
});

const response = await client.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Explain quantum computing'
});

console.log('Response:', response.text);
console.log('Usage:', response.usageMetadata);
Metriche Monitorate:
  • promptTokenCountinputTokens
  • candidatesTokenCount + thoughtsTokenCountoutputTokens
  • totalTokenCounttotalTokens
  • Versione del modello
Modalità di Pensiero di Gemini: Quando si utilizzano modelli Gemini con capacità di pensiero/razionamento (come Gemini 2.5 Pro), l’SDK include automaticamente thoughtsTokenCount (token di ragionamento) in outputTokens per riflettere accuratamente il costo computazionale totale.

Utilizzo Avanzato

Molteplici Fornitori

Monitora l’uso tra diversi fornitori LLM con tracker separati:
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import OpenAI from 'openai';
import Groq from 'groq-sdk';
import Anthropic from '@anthropic-ai/sdk';
import { GoogleGenAI } from '@google/genai';

// Create separate trackers for different providers
const openaiTracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'live_mode',
  eventName: 'openai.usage'
});

const groqTracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'live_mode',
  eventName: 'groq.usage'
});

const anthropicTracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'live_mode',
  eventName: 'anthropic.usage'
});

const geminiTracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'live_mode',
  eventName: 'gemini.usage'
});

const openrouterTracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: 'live_mode',
  eventName: 'openrouter.usage'
});

// Initialize clients
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const googleGenai = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY });
const openrouter = new OpenAI({ 
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: process.env.OPENROUTER_API_KEY 
});

// Wrap clients
const trackedOpenAI = openaiTracker.wrap({ client: openai, customerId: 'user_123' });
const trackedGroq = groqTracker.wrap({ client: groq, customerId: 'user_123' });
const trackedAnthropic = anthropicTracker.wrap({ client: anthropic, customerId: 'user_123' });
const trackedGemini = geminiTracker.wrap({ client: googleGenai, customerId: 'user_123' });
const trackedOpenRouter = openrouterTracker.wrap({ client: openrouter, customerId: 'user_123' });

// Use whichever provider you need
const response = await trackedOpenAI.chat.completions.create({...});
// or
const geminiResponse = await trackedGemini.models.generateContent({...});
// or
const openrouterResponse = await trackedOpenRouter.chat.completions.create({...});
Usa nomi di eventi diversi per fornitori diversi per monitorare l’uso separatamente nei tuoi misuratori.

Integrazione API Express.js

Esempio completo di integrazione del monitoraggio LLM in un’API Express.js:
import express from 'express';
import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
import OpenAI from 'openai';

const app = express();
app.use(express.json());

// Initialize OpenAI client
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

// Create tracker once at startup
const tracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: process.env.NODE_ENV === 'production' ? 'live_mode' : 'test_mode',
  eventName: 'api.chat_completion'
});

// Chat endpoint with automatic tracking
app.post('/api/chat', async (req, res) => {
  try {
    const { message, userId } = req.body;
    
    // Validate input
    if (!message || !userId) {
      return res.status(400).json({ error: 'Missing message or userId' });
    }
    
    // Wrap client for this specific user
    const trackedClient = tracker.wrap({
      client: openai,
      customerId: userId,
      metadata: { 
        endpoint: '/api/chat',
        timestamp: new Date().toISOString()
      }
    });
    
    // Make LLM request - automatically tracked
    const response = await trackedClient.chat.completions.create({
      model: 'gpt-4',
      messages: [{ role: 'user', content: message }],
      temperature: 0.7
    });
    
    const completion = response.choices[0].message.content;
    
    res.json({ 
      message: completion,
      usage: response.usage
    });
  } catch (error) {
    console.error('Chat error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Cosa Viene Monitorato

Ogni chiamata API LLM invia automaticamente un evento di utilizzo a Dodo Payments con la seguente struttura:
{
  "event_id": "llm_1673123456_abc123",
  "customer_id": "customer_123",
  "event_name": "llm.chat_completion",
  "timestamp": "2024-01-08T10:30:00Z",
  "metadata": {
    "inputTokens": 10,
    "outputTokens": 25,
    "totalTokens": 35,
    "model": "gpt-4",
  }
}

Campi Evento

event_id
string
Identificatore unico per questo specifico evento. Generato automaticamente dall’SDK.Formato: llm_[timestamp]_[random]
customer_id
string
L’ID cliente fornito quando si avvolge il client. Usato per la fatturazione.
event_name
string
Il nome dell’evento che attiva il tuo misuratore. Corrisponde alla configurazione del tuo tracker.
timestamp
string
Timestamp ISO 8601 quando si è verificato l’evento.
metadata
object
Utilizzo dei token e dati di monitoraggio aggiuntivi:
  • inputTokens - Numero di token di input/prompt utilizzati
  • outputTokens - Numero di token di output/completamento utilizzati (inclusi i token di ragionamento quando applicabile)
  • totalTokens - Token totali (input + output)
  • model - Il modello LLM utilizzato (es. “gpt-4”)
  • provider - Il fornitore LLM (se incluso nei metadati del wrapper)
  • Qualsiasi metadato personalizzato fornito quando si avvolge il client
Token di Ragionamento: Per i modelli con capacità di ragionamento, outputTokens include automaticamente sia i token di completamento che i token di ragionamento.
Il tuo misuratore di Dodo Payments utilizza i campi metadata (soprattutto inputTokens, outputTokens o totalTokens) per calcolare l’uso e la fatturazione.