SaaSアプリ、AIチャットボット、コンテンツ生成ツール、および従量課金が必要なLLM搭載アプリに最適です。
クイックスタート
自動 LLM トークン追跡を 2 分で始めましょう:
Install the SDK
Dodo Payments Ingestion Blueprintsをインストールする:npm install @dodopayments/ingestion-blueprints
Get Your API Keys
2つのAPIキーが必要です:
- Dodo Payments API キー: Dodo Payments ダッシュボード から取得します。
- LLM プロバイダー API キー: AI SDK、OpenAI、Anthropic、Groq などから取得します。
APIキーは環境変数に安全に保存してください。バージョン管理にコミットしないでください。
Create a Meter in Dodo Payments
使用状況を追跡する前に、Dodo Paymentsダッシュボードでメーターを作成します:
- ログイン Dodo Payments Dashboard
- 移動 Products → Meters
- クリック “Create Meter”
- メーターを構成:
- Meter Name:わかりやすい名前を選択(例:「LLM Token Usage」)
- Event Name:ユニークなイベント識別子を設定(例:
llm.chat_completion)
- Aggregation Type:
sum を選びトークン数を合計
- Over Property:追跡内容を選択:
inputTokens - 入力/プロンプトトークンを追跡
outputTokens - 出力/完了トークンを追跡(該当する場合は推論トークンも含む)
totalTokens - 入力 + 出力トークンの合計を追跡
ここで設定したEvent Nameは、SDKに渡す値と完全に一致する必要があります(大文字小文字を区別)。
詳しい手順については、Usage-Based Billing Guideを参照してください。 Track Token Usage
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'
});
const response = await client.generateText({
model: google('gemini-2.0-flash'),
prompt: 'Hello!',
maxOutputTokens: 500
});
console.log('Usage:', response.usage);
以上です!これで各API呼び出しが自動的にトークン使用量を追跡し、請求のためDodo Paymentsにイベントを送信します。
トラッカー設定
アプリケーションの起動時に、次の必須パラメータでトラッカーを一度作成します:
Dodo PaymentsのAPIキー。API Keys pageから取得できます。apiKey: process.env.DODO_PAYMENTS_API_KEY
トラッカーの環境モード。
test_mode - 開発およびテストに使用
live_mode - 本番環境に使用
environment: 'test_mode' // or 'live_mode'
開発時には、プロダクション指標に影響を与えないよう常にtest_mode を使用してください。
メーターをトリガーするイベント名。Dodo Paymentsのメーターで設定した値と完全に一致させる必要があります(大文字小文字を区別)。eventName: 'llm.chat_completion'
このイベント名によって、追跡された使用量が請求計算用の正しいメーターに関連付けられます。
ラッパー設定
LLM クライアントをラップする際に、次のパラメータを提供します:
LLMクライアントインスタンス(OpenAI、Anthropic、Groqなど)。
課金対象のユニークな顧客識別子。Dodo Paymentsの顧客IDと一致させてください。customerId: 'customer_123'
正確な顧客単位の請求を行うため、アプリケーションのユーザーIDまたは顧客IDを使用してください。
トラッキングイベントに追加できるオプションのデータ。フィルタリングや分析に便利です。metadata: {
feature: 'chat',
userTier: 'premium',
sessionId: 'session_123',
modelVersion: 'gpt-4'
}
完全な設定例
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);
自動追跡: SDKがバックグラウンドでトークン使用量を自動的に追跡し、レスポンスの変更は必要ありません。コードは元のプロバイダーSDKとまったく同じままです。
サポートされているプロバイダー
LLM ブループリントは、すべての主要な LLM プロバイダーおよび集約者とシームレスに連携します:
ユニバーサルLLMサポートのためにVercel AI SDKで使用状況を追跡します。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);
追跡メトリクス:
inputTokens → inputTokens
outputTokens + reasoningTokens → outputTokens
totalTokens → totalTokens
- モデル名
AI SDK(たとえばGemini 2.5 Flashの思考モード)の推論対応モデルを使用する場合、推論トークンは正確な請求のために自動的にoutputTokensカウントに含まれます。
OpenRouterの統一APIで200以上のモデルのトークン使用量を追跡。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);
追跡メトリクス:
prompt_tokens → inputTokens
completion_tokens → outputTokens
total_tokens → totalTokens
- モデル名
OpenRouterはOpenAI、Anthropic、Google、Metaなど多くのプロバイダーのモデルに単一APIでアクセスできます。
OpenAIのGPTモデルからのトークン使用量を自動で追跡。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);
追跡メトリクス:
prompt_tokens → inputTokens
completion_tokens → outputTokens
total_tokens → totalTokens
- モデル名
AnthropicのClaudeモデルからのトークン使用量を追跡。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);
追跡メトリクス:
input_tokens → inputTokens
output_tokens → outputTokens
- 計算済み
totalTokens
- モデル名
Groqによる超高速LLM推論を追跡。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);
追跡メトリクス:
prompt_tokens → inputTokens
completion_tokens → outputTokens
total_tokens → totalTokens
- モデル名
Google GenAI SDK経由でGoogleのGeminiモデルのトークン使用量を追跡。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);
追跡メトリクス:
promptTokenCount → inputTokens
candidatesTokenCount + thoughtsTokenCount → outputTokens
totalTokenCount → totalTokens
- モデルバージョン
Gemini Thinking Mode: 思考/推論機能付きのGeminiモデル(例:Gemini 2.5 Pro)を使用する場合、SDKはthoughtsTokenCount(推論トークン)をoutputTokensに自動的に含め、総計算コストを正確に反映します。
高度な使用法
複数のプロバイダー
異なる LLM プロバイダー間で使用量を追跡するために、別々のトラッカーを使用します:
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({...});
プロバイダーごとに異なるイベント名を使用して、メーターごとに使用状況を個別に追跡してください。
Express.js API 統合
Express.js API に LLM トラッキングを統合する完全な例:
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');
});
追跡される内容
すべての LLM API 呼び出しは、自動的に Dodo Payments に使用イベントを送信し、次の構造を持ちます:
{
"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",
}
}
イベントフィールド
このイベント固有のユニーク識別子。SDKが自動生成します。Format: llm_[timestamp]_[random]
メーターをトリガーするイベント名。トラッカー構成と一致します。
イベントが発生したISO 8601タイムスタンプ。
トークン使用量および追加のトラッキングデータ:
inputTokens - 使用された入力/プロンプトトークンの数
outputTokens - 使用された出力/完了トークンの数(該当する場合は推論トークンを含む)
totalTokens - 合計トークン(入力 + 出力)
model - 使用されたLLMモデル(例:「gpt-4」)
provider - LLMプロバイダー(ラッパーメタデータに含まれる場合)
- クライアントをラップした際に提供したカスタムメタデータ
推論トークン: 推論機能付きモデルでは、outputTokensに完了トークンと推論トークンの両方が自動的に含まれます。
Dodo Paymentsのメーターはmetadataフィールド(特にinputTokens、outputTokens、totalTokens)を使用して使用量と課金を計算します。