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

# コストと使用量

> クレジットコストの予測、残高確認、ボイスや時間帯別の使用量モニタリング、異常検知アラートの設定。

<Note>
  このドキュメントは英語の原文から自動翻訳されています。表現に不自然な箇所がある場合があります。正確な内容は[英語の原文](/en/docs/production/cost-and-usage)もあわせてご確認ください。
</Note>

Supertone APIは、[Supertone Play](https://play.supertone.ai)と共有される**クレジットベース**の課金モデルを採用しています。本ページでは、クレジットの仕組み、生成前のコスト予測方法、そしてオブザーバビリティスタックに統合すべきエンドポイントについて解説します。

## クレジットの仕組み

* クレジットは生成された音声の**秒数単位**で差し引かれます。
* クレジットは**Supertone Playと共有**されます — 同じ残高が両方に適用されます。Playで課金されたクレジットは即座にAPIで使用可能になり、その逆も同様です。
* プリセットボイスとカスタムボイスの両方が同じ残高から差し引かれます。
* **`predict_duration`は無料です。** クレジットは差し引かれません。コストのプレビューや事前確認に使用してください。

料金プランは[Play購読ページ](https://play.supertone.ai/subscription)に記載されています。より高い制限と専用容量については、[エンタープライズプラン](https://docs.google.com/forms/d/1YexQpjpK0ZEou12blTytkZLqvrV-Uv95GbhxoOQ54R8/edit)をご覧ください。

## 統合すべきエンドポイント

| Endpoint                               | Purpose                                                   |
| -------------------------------------- | --------------------------------------------------------- |
| `POST /v1/predict-duration/{voice_id}` | 生成前に音声の長さ（したがってクレジットコスト）を予測します。                           |
| `GET /v1/credits`                      | 現在のクレジット残高 — 低くなったらアラートを発します。                             |
| `GET /v1/voice-usage`                  | ボイス／スタイル／言語／モデル別の日次生成分数（最大30日）。                           |
| `GET /v1/usage`                        | `voice_id`、`voice_name`、`api_key`、`model`別の内訳を含むバケット集計分析。 |

## Predict duration

`predict_duration`は、指定されたテキストに対する生成音声の**予測される長さ**を、音声を生成せずに返します。次のような用途に使用してください。

* 生成前にユーザーに「これには約12秒かかります」といった見積もりを表示する。
* クレジットコストを予測する（このエンドポイントではクレジットは差し引かれません）。
* 文がUIのスロットや予算に収まるかを判断する。

<Note>
  `predict_duration`は自動チャンク分割を**行いません** — 同じ300文字の制限が適用されます。長いスクリプトの場合は、自分で分割して予測時間を合計してください。
</Note>

<Tabs>
  <Tab title="Python">
    ```python theme={"dark"}
    import os
    from supertone import Supertone

    VOICE_ID = "20160a4c5ba38967330c84"  # replace with your voice ID

    with Supertone(api_key=os.environ["SUPERTONE_API_KEY"]) as client:
        response = client.text_to_speech.predict_duration(
            voice_id=VOICE_ID,
            text="This is a sentence to estimate.",
            language="en",
        )

    print(f"Estimated duration: {response.duration:.2f}s")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={"dark"}
    import { Supertone } from "@supertone/supertone";

    const VOICE_ID = "20160a4c5ba38967330c84"; // replace with your voice ID

    const client = new Supertone({ apiKey: process.env.SUPERTONE_API_KEY });

    const response = await client.textToSpeech.predictDuration({
      voiceId: VOICE_ID,
      predictTTSDurationRequest: {
        text: "This is a sentence to estimate.",
        language: "en",
      },
    });

    console.log(`Estimated duration: ${response.duration?.toFixed(2)}s`);
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={"dark"}
    VOICE_ID="20160a4c5ba38967330c84"

    curl -X POST "https://supertoneapi.com/v1/predict-duration/$VOICE_ID" \
      -H "x-sup-api-key: $SUPERTONE_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "text": "This is a sentence to estimate.",
        "language": "en"
      }'
    ```

    Response:

    ```json theme={"dark"}
    { "duration": 2.18 }
    ```
  </Tab>
</Tabs>

リクエストボディは[Create speech](/ja/docs/text-to-speech/create-speech)と同じ形式です — `text`、`language`、`style`、`model`、`voice_settings`から、`output_format`、`include_phonemes`、`normalized_text`（いずれも予測される長さに影響しません）を除いたものです。

**正確な予測のためのヒント：**

* **速度は結果を変えます。** `voice_settings.speed`は長さに掛け算されます。ある速度でプレビューして別の速度で生成すると、実際の長さは異なります。両方の呼び出しで同じ速度を使用してください。
* **モデルを合わせる。** `predict_duration`は`create_speech`と同じ`model`フィールドを受け付けます。生成で特定のモデルを使用する場合は、それに対して予測してください。

**バッチジョブ**や**ユーザー単位の予算**を事前に確認するには、まず`predict_duration`を呼び出し、予測時間を合計して処理を進めるかを判断してください。

## 日次残高チェック

残高がしきい値を下回ったときに監視ツールに投稿するシンプルなcronジョブにより、`402 Payment Required`の障害が発生する数日前に警告を受けられます。

<Tabs>
  <Tab title="Python">
    ```python theme={"dark"}
    import os
    from supertone import Supertone

    LOW_THRESHOLD_USD = 50.0

    with Supertone(api_key=os.environ["SUPERTONE_API_KEY"]) as client:
        balance = client.usage.get_credit_balance()
        if balance.credit_balance < LOW_THRESHOLD_USD:
            notify_oncall(
                f"Supertone credit balance low: ${balance.credit_balance:.2f}"
            )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={"dark"}
    import { Supertone } from "@supertone/supertone";

    const LOW_THRESHOLD = 50;

    const client = new Supertone({ apiKey: process.env.SUPERTONE_API_KEY });
    const { creditBalance } = await client.usage.getCreditBalance();

    if (creditBalance !== undefined && creditBalance < LOW_THRESHOLD) {
      await notifyOncall(`Supertone credit balance low: $${creditBalance.toFixed(2)}`);
    }
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={"dark"}
    curl https://supertoneapi.com/v1/credits \
      -H "x-sup-api-key: $SUPERTONE_API_KEY"
    ```
  </Tab>
</Tabs>

ライブ残高は、コンソールのダッシュボードまたはPlay購読ページでも確認できます。

## 週次ボイス別レポート

最もコストを発生させているボイスを把握したい場合、または暴走している連携を検知したい場合に有用です。クエリの最大ウィンドウは30日で、日付はUTC+0です。

<Tabs>
  <Tab title="Python">
    ```python theme={"dark"}
    from supertone import Supertone

    with Supertone(api_key=API_KEY) as client:
        usage = client.usage.get_voice_usage(
            start_date="2025-05-01",
            end_date="2025-05-31",
        )

        by_voice = {}
        for row in usage.usages or []:
            by_voice[row.name] = by_voice.get(row.name, 0) + row.total_minutes_used

        for name, minutes in sorted(by_voice.items(), key=lambda x: -x[1]):
            print(f"{name:30s} {minutes:>8.2f} min")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={"dark"}
    const usage = await client.usage.getVoiceUsage({
      startDate: "2025-05-01",
      endDate: "2025-05-31",
    });

    const byVoice = new Map<string, number>();
    for (const row of usage.usages ?? []) {
      byVoice.set(row.name, (byVoice.get(row.name) ?? 0) + row.totalMinutesUsed);
    }

    for (const [name, minutes] of [...byVoice.entries()].sort((a, b) => b[1] - a[1])) {
      console.log(`${name.padEnd(30)} ${minutes.toFixed(2)} min`);
    }
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={"dark"}
    curl "https://supertoneapi.com/v1/voice-usage?start_date=2025-05-01&end_date=2025-05-31" \
      -H "x-sup-api-key: $SUPERTONE_API_KEY"
    ```
  </Tab>
</Tabs>

## ダッシュボード向けのバケット集計分析

`GET /v1/usage`は、複数の内訳を伴う時間単位または日単位のバケット集計をサポートします。ダッシュボードのパネルを埋めたり、メトリクスバックエンドに行を送信したりするのに使用してください。

<Tabs>
  <Tab title="Python">
    ```python theme={"dark"}
    from supertone import Supertone

    with Supertone(api_key=API_KEY) as client:
        page = client.usage.get_usage(
            start_time="2025-05-01T00:00:00+00:00",
            end_time="2025-05-31T23:59:59+00:00",
            bucket_width="day",
            breakdown_type=["api_key", "model"],
            page_size=20,
        )

        for row in page.items or []:
            emit_metric("supertone.minutes_generated", value=row.total_minutes_used, tags={
                "api_key": row.api_key,
                "model": row.model,
                "bucket_start": row.bucket_start,
            })
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={"dark"}
    import { Supertone } from "@supertone/supertone";

    const client = new Supertone({ apiKey: API_KEY });

    const page = await client.usage.getUsage({
      startTime: "2025-05-01T00:00:00+00:00",
      endTime: "2025-05-31T23:59:59+00:00",
      bucketWidth: "day",
      breakdownType: ["api_key", "model"],
      pageSize: 20,
    });

    for (const row of page.items ?? []) {
      emitMetric("supertone.minutes_generated", row.totalMinutesUsed, {
        api_key: row.apiKey,
        model: row.model,
        bucket_start: row.bucketStart,
      });
    }
    ```
  </Tab>
</Tabs>

制限事項：

* 同じ`breakdown_type`内で`voice_id`と`voice_name`を組み合わせることはできません。
* `start_time`と`end_time`のUTCオフセットが異なる場合、APIは`end_time`のオフセットを無視します。
* ページサイズは1〜20。`next_page_token`でページングしてください。

## 異常検知アラート

低コストで有用なアラートを2つ紹介します。

1. **使用量スパイク** — 当日の生成分数を直近7日の中央値と比較。当日が中央値の3倍（など）を超えたらアラート。
2. **本番に新しいボイスが出現** — `get_voice_usage`で想定外のボイスが見つかった場合にフラグを立てます。本番コードに誤って混入したハードコードのテストボイスを検出できます。

## ユーザー単位の帰属

Supertone API自体はエンドユーザーのアイデンティティを追跡しません — それはお客様のバックエンドの役割です。パターンは次のとおりです。

1. バックエンドで各TTS呼び出しを`user_id`、`voice_id`、予測/実際の所要時間、タイムスタンプとともに記録します。
2. 課金や不正利用対策のために内部でロールアップします。
3. 定期的に`get_voice_usage`と照合し、自社の記録がSupertoneのカウントと一致していることを確認します。

## 関連項目

<CardGroup cols={2}>
  <Card title="Create speech" icon="comment" href="/ja/docs/text-to-speech/create-speech">
    コストを予測した後に音声を生成します。
  </Card>

  <Card title="レート制限" icon="gauge" href="/ja/docs/production/rate-limits">
    ティア別の1分あたりのリクエスト制限。
  </Card>
</CardGroup>
