> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LLM ブループリント

> Dodo Payments への自動取り込みで、使用量に基づく請求のために LLM トークンの使用状況を簡単に追跡します。AI SDK、OpenAI、Anthropic、OpenRouter、Groq、Google Gemini と連携します。

<CardGroup cols={2}>
  <Card title="Quick Start" icon="rocket" href="#quick-start">
    自動トークン追跡で2分で開始できます。
  </Card>

  <Card title="API Reference - Events Ingestion" icon="code" href="/api-reference/usage-events/ingest-events">
    使用イベントを取り込むための完全なAPIドキュメント。
  </Card>

  <Card title="API Reference - Meters" icon="gauge" href="/api-reference/meters/create-meter">
    課金用メーターを作成・設定する方法を学びましょう。
  </Card>

  <Card title="Usage-Based Billing Guide" icon="arrow-trend-up" href="/developer-resources/usage-based-billing-guide">
    メーターを使った従量課金の包括的ガイド。
  </Card>
</CardGroup>

<Info>
  SaaSアプリ、AIチャットボット、コンテンツ生成ツール、および従量課金が必要なLLM搭載アプリに最適です。
</Info>

## クイックスタート

自動 LLM トークン追跡を 2 分で始めましょう：

<Steps>
  <Step title="Install the SDK">
    Dodo Payments Ingestion Blueprintsをインストールする：

    ```bash theme={null}
    npm install @dodopayments/ingestion-blueprints
    ```
  </Step>

  <Step title="Get Your API Keys">
    2つのAPIキーが必要です：

    * **Dodo Payments API キー**: [Dodo Payments ダッシュボード](https://app.dodopayments.com/developer/api-keys) から取得します。
    * **LLM プロバイダー API キー**: AI SDK、OpenAI、Anthropic、Groq などから取得します。

    <Tip>
      APIキーは環境変数に安全に保存してください。バージョン管理にコミットしないでください。
    </Tip>
  </Step>

  <Step title="Create a Meter in Dodo Payments">
    使用状況を追跡する前に、Dodo Paymentsダッシュボードでメーターを作成します：

    1. **ログイン** [Dodo Payments Dashboard](https://app.dodopayments.com/)
    2. **移動** Products → Meters
    3. **クリック** "Create Meter"
    4. **メーターを構成**：
       * **Meter Name**：わかりやすい名前を選択（例：「LLM Token Usage」）
       * **Event Name**：ユニークなイベント識別子を設定（例：`llm.chat_completion`）
       * **Aggregation Type**：`sum` を選びトークン数を合計
       * **Over Property**：追跡内容を選択：
         * `inputTokens` - 入力/プロンプトトークンを追跡
         * `outputTokens` - 出力/完了トークンを追跡（該当する場合は推論トークンも含む）
         * `totalTokens` - 入力 + 出力トークンの合計を追跡

    <Info>
      ここで設定した**Event Name**は、SDKに渡す値と完全に一致する必要があります（大文字小文字を区別）。
    </Info>

    詳しい手順については、[Usage-Based Billing Guide](/developer-resources/usage-based-billing-guide)を参照してください。
  </Step>

  <Step title="Track Token Usage">
    LLMクライアントをラップして自動で追跡を開始：

    <CodeGroup>
      ```javascript AI SDK theme={null}
      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);
      ```

      ```javascript OpenRouter theme={null}
      import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
      import OpenAI from 'openai';

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

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

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

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

      console.log('Response:', response.choices[0].message.content);
      console.log('Usage:', response.usage);
      ```

      ```javascript OpenAI theme={null}
      import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
      import OpenAI from 'openai';

      // 1. Create your LLM client (normal way)
      const openai = new OpenAI({ 
        apiKey: process.env.OPENAI_API_KEY 
      });

      // 2. Create tracker ONCE at startup
      const tracker = createLLMTracker({
        apiKey: process.env.DODO_PAYMENTS_API_KEY,
        environment: 'test_mode', // Use 'live_mode' for production
        eventName: 'llm.chat_completion' // Match your meter's event name
      });

      // 3. Wrap & use - automatic tracking!
      const client = tracker.wrap({ 
        client: openai, 
        customerId: 'customer_123' 
      });

      // Every API call is now automatically tracked
      const response = await client.chat.completions.create({
        model: 'gpt-4',
        messages: [{ role: 'user', content: 'Hello!' }]
      });

      // ✨ Usage automatically sent to Dodo Payments!
      console.log('Tokens used:', response.usage);
      ```

      ```javascript Anthropic theme={null}
      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: 'customer_123' 
      });

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

      console.log('Tokens used:', response.usage);
      ```

      ```javascript Groq theme={null}
      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: 'customer_123' 
      });

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

      console.log('Tokens:', response.usage);
      ```

      ```javascript Google Gemini theme={null}
      import { createLLMTracker } from '@dodopayments/ingestion-blueprints';
      import { GoogleGenAI } from '@google/genai';

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

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

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

      const response = await client.models.generateContent({
        model: 'gemini-2.5-flash',
        contents: 'Why is the sky blue?'
      });

      console.log('Response:', response.text);
      console.log('Usage:', response.usageMetadata);
      ```
    </CodeGroup>

    <Check>
      以上です！これで各API呼び出しが自動的にトークン使用量を追跡し、請求のためDodo Paymentsにイベントを送信します。
    </Check>
  </Step>
</Steps>

***

## 設定

### トラッカー設定

アプリケーションの起動時に、次の必須パラメータでトラッカーを一度作成します：

<ParamField path="apiKey" type="string" required>
  Dodo PaymentsのAPIキー。[API Keys page](https://app.dodopayments.com/developer/api-keys)から取得できます。

  ```javascript theme={null}
  apiKey: process.env.DODO_PAYMENTS_API_KEY
  ```
</ParamField>

<ParamField path="environment" type="string" required>
  トラッカーの環境モード。

  * `test_mode` - 開発およびテストに使用
  * `live_mode` - 本番環境に使用

  ```javascript theme={null}
  environment: 'test_mode' // or 'live_mode'
  ```

  <Warning>
    開発時には、プロダクション指標に影響を与えないよう常に`test_mode` を使用してください。
  </Warning>
</ParamField>

<ParamField path="eventName" type="string" required>
  メーターをトリガーするイベント名。Dodo Paymentsのメーターで設定した値と完全に一致させる必要があります（大文字小文字を区別）。

  ```javascript theme={null}
  eventName: 'llm.chat_completion'
  ```

  <Info>
    このイベント名によって、追跡された使用量が請求計算用の正しいメーターに関連付けられます。
  </Info>
</ParamField>

### ラッパー設定

LLM クライアントをラップする際に、次のパラメータを提供します：

<ParamField path="client" type="object" required>
  LLMクライアントインスタンス（OpenAI、Anthropic、Groqなど）。

  ```javascript theme={null}
  client: openai
  ```
</ParamField>

<ParamField path="customerId" type="string" required>
  課金対象のユニークな顧客識別子。Dodo Paymentsの顧客IDと一致させてください。

  ```javascript theme={null}
  customerId: 'customer_123'
  ```

  <Tip>
    正確な顧客単位の請求を行うため、アプリケーションのユーザーIDまたは顧客IDを使用してください。
  </Tip>
</ParamField>

<ParamField path="metadata" type="object">
  トラッキングイベントに追加できるオプションのデータ。フィルタリングや分析に便利です。

  ```javascript theme={null}
  metadata: {
    feature: 'chat',
    userTier: 'premium',
    sessionId: 'session_123',
    modelVersion: 'gpt-4'
  }
  ```
</ParamField>

### 完全な設定例

<CodeGroup>
  ```javascript Full Configuration theme={null}
  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);
  ```
</CodeGroup>

<Info>
  **自動追跡：** SDKがバックグラウンドでトークン使用量を自動的に追跡し、レスポンスの変更は必要ありません。コードは元のプロバイダーSDKとまったく同じままです。
</Info>

***

## サポートされているプロバイダー

LLM ブループリントは、すべての主要な LLM プロバイダーおよび集約者とシームレスに連携します：

<AccordionGroup>
  <Accordion title="AI SDK (Vercel)" icon="code">
    ユニバーサルLLMサポートのためにVercel AI SDKで使用状況を追跡します。

    <CodeGroup>
      ```javascript AI SDK Integration theme={null}
      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);
      ```
    </CodeGroup>

    **追跡メトリクス：**

    * `inputTokens` → `inputTokens`
    * `outputTokens` + `reasoningTokens` → `outputTokens`
    * `totalTokens` → `totalTokens`
    * モデル名

    <Note>
      AI SDK（たとえばGemini 2.5 Flashの思考モード）の推論対応モデルを使用する場合、推論トークンは正確な請求のために自動的に`outputTokens`カウントに含まれます。
    </Note>
  </Accordion>

  <Accordion title="OpenRouter" icon="route">
    OpenRouterの統一APIで200以上のモデルのトークン使用量を追跡。

    <CodeGroup>
      ```javascript OpenRouter Integration theme={null}
      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);
      ```
    </CodeGroup>

    **追跡メトリクス：**

    * `prompt_tokens` → `inputTokens`
    * `completion_tokens` → `outputTokens`
    * `total_tokens` → `totalTokens`
    * モデル名

    <Tip>
      OpenRouterはOpenAI、Anthropic、Google、Metaなど多くのプロバイダーのモデルに単一APIでアクセスできます。
    </Tip>
  </Accordion>

  <Accordion title="OpenAI" icon="robot">
    OpenAIのGPTモデルからのトークン使用量を自動で追跡。

    <CodeGroup>
      ```javascript OpenAI Integration theme={null}
      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);
      ```
    </CodeGroup>

    **追跡メトリクス：**

    * `prompt_tokens` → `inputTokens`
    * `completion_tokens` → `outputTokens`
    * `total_tokens` → `totalTokens`
    * モデル名
  </Accordion>

  <Accordion title="Anthropic Claude" icon="robot">
    AnthropicのClaudeモデルからのトークン使用量を追跡。

    <CodeGroup>
      ```javascript Anthropic Integration theme={null}
      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);
      ```
    </CodeGroup>

    **追跡メトリクス：**

    * `input_tokens` → `inputTokens`
    * `output_tokens` → `outputTokens`
    * 計算済み `totalTokens`
    * モデル名
  </Accordion>

  <Accordion title="Groq" icon="gauge-high">
    Groqによる超高速LLM推論を追跡。

    <CodeGroup>
      ```javascript Groq Integration theme={null}
      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);
      ```
    </CodeGroup>

    **追跡メトリクス：**

    * `prompt_tokens` → `inputTokens`
    * `completion_tokens` → `outputTokens`
    * `total_tokens` → `totalTokens`
    * モデル名
  </Accordion>

  <Accordion title="Google Gemini" icon="sparkles">
    Google GenAI SDK経由でGoogleのGeminiモデルのトークン使用量を追跡。

    <CodeGroup>
      ```javascript Google Gemini Integration theme={null}
      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);
      ```
    </CodeGroup>

    **追跡メトリクス：**

    * `promptTokenCount` → `inputTokens`
    * `candidatesTokenCount` + `thoughtsTokenCount` → `outputTokens`
    * `totalTokenCount` → `totalTokens`
    * モデルバージョン

    <Note>
      **Gemini Thinking Mode：** 思考/推論機能付きのGeminiモデル（例：Gemini 2.5 Pro）を使用する場合、SDKは`thoughtsTokenCount`（推論トークン）を`outputTokens`に自動的に含め、総計算コストを正確に反映します。
    </Note>
  </Accordion>
</AccordionGroup>

***

## 高度な使用法

### 複数のプロバイダー

異なる LLM プロバイダー間で使用量を追跡するために、別々のトラッカーを使用します：

<CodeGroup>
  ```javascript Multiple Provider Setup theme={null}
  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({...});
  ```
</CodeGroup>

<Tip>
  プロバイダーごとに異なるイベント名を使用して、メーターごとに使用状況を個別に追跡してください。
</Tip>

### Express.js API 統合

Express.js API に LLM トラッキングを統合する完全な例：

<CodeGroup>
  ```javascript Express.js Server theme={null}
  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');
  });
  ```
</CodeGroup>

***

## 追跡される内容

すべての LLM API 呼び出しは、自動的に Dodo Payments に使用イベントを送信し、次の構造を持ちます：

<CodeGroup>
  ```json Event Structure theme={null}
  {
    "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",
    }
  }
  ```
</CodeGroup>

### イベントフィールド

<ParamField path="event_id" type="string">
  このイベント固有のユニーク識別子。SDKが自動生成します。

  Format: `llm_[timestamp]_[random]`
</ParamField>

<ParamField path="customer_id" type="string">
  ラップ時に提供した顧客ID。請求に使用されます。
</ParamField>

<ParamField path="event_name" type="string">
  メーターをトリガーするイベント名。トラッカー構成と一致します。
</ParamField>

<ParamField path="timestamp" type="string">
  イベントが発生したISO 8601タイムスタンプ。
</ParamField>

<ParamField path="metadata" type="object">
  トークン使用量および追加のトラッキングデータ：

  * `inputTokens` - 使用された入力/プロンプトトークンの数
  * `outputTokens` - 使用された出力/完了トークンの数（該当する場合は推論トークンを含む）
  * `totalTokens` - 合計トークン（入力 + 出力）
  * `model` - 使用されたLLMモデル（例：「gpt-4」）
  * `provider` - LLMプロバイダー（ラッパーメタデータに含まれる場合）
  * クライアントをラップした際に提供したカスタムメタデータ

  <Note>
    **推論トークン：** 推論機能付きモデルでは、`outputTokens`に完了トークンと推論トークンの両方が自動的に含まれます。
  </Note>
</ParamField>

<Info>
  Dodo Paymentsのメーターは`metadata`フィールド（特に`inputTokens`、`outputTokens`、`totalTokens`）を使用して使用量と課金を計算します。
</Info>

***
