> ## 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.

# Python SDK

> Supertone Python SDKをインストールし、認証し、利用する方法 — 同期および非同期クライアント、ストリーミング、自動チャンク分割、エラー処理について。

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

公式のPython SDKは、PyPIで[`supertone`](https://pypi.org/project/supertone/)として公開されています。ソース：[supertone-inc/supertone-python](https://github.com/supertone-inc/supertone-python)。

## 早わかり

|                 |                                                                                     |
| --------------- | ----------------------------------------------------------------------------------- |
| **パッケージ**       | PyPIの[`supertone`](https://pypi.org/project/supertone/)                             |
| **リポジトリ**       | [supertone-inc/supertone-python](https://github.com/supertone-inc/supertone-python) |
| **言語**          | Python 3.9+                                                                         |
| **認証**          | `Supertone(api_key=...)`                                                            |
| **同期API**       | あり（デフォルト）                                                                           |
| **非同期API**      | `*_async`メソッド + `async with`                                                        |
| **ストリーミング**     | `iter_bytes()` / `aiter_bytes()`                                                    |
| **長文の自動チャンク分割** | ✅ 300文字、最大3ワーカーで並列                                                                  |
| **カスタムリトライ**    | ✅ `retry_config`経由                                                                  |
| **HTTPバックエンド**  | `httpx`                                                                             |

## インストール

<Tabs>
  <Tab title="pip">
    ```bash theme={"dark"}
    pip install supertone
    ```
  </Tab>

  <Tab title="uv">
    ```bash theme={"dark"}
    uv add supertone
    ```
  </Tab>

  <Tab title="poetry">
    ```bash theme={"dark"}
    poetry add supertone
    ```
  </Tab>
</Tabs>

Python 3.9以上が必要です。

## API Keyを設定する

SDKは環境変数を自動的に読み込みません。`api_key`を明示的に渡してください。慣例として`SUPERTONE_API_KEY`から読み込みます。

```bash theme={"dark"}
export SUPERTONE_API_KEY="Kp9mZ3xQ7v..."
```

```python theme={"dark"}
import os
from supertone import Supertone

client = Supertone(api_key=os.environ["SUPERTONE_API_KEY"])
```

ボイスIDは環境変数ではありません。用途ごとに変わるため、コード内のプレーンな文字列として保持するか（あるいはリクエストペイロードから渡してください）。

## 音声を生成する（同期）

推奨パターンでは、コンテキストマネージャを使用して内部のHTTP接続をクリーンにクローズします。

```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.create_speech(
        voice_id=VOICE_ID,
        text="Hello from the Python SDK.",
        language="en",
        output_format="wav",
    )

    with open("speech.wav", "wb") as f:
        f.write(response.result.read())
```

## 音声を生成する（非同期）

`_async`サフィックスと`async with`を使用します。

```python theme={"dark"}
import asyncio
import os
from supertone import Supertone

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

async def main():
    async with Supertone(api_key=os.environ["SUPERTONE_API_KEY"]) as client:
        response = await client.text_to_speech.create_speech_async(
            voice_id=VOICE_ID,
            text="Hello from the async Python SDK.",
            language="en",
        )

        with open("speech.wav", "wb") as f:
            f.write(response.result.read())

asyncio.run(main())
```

SDK上のすべてのリソースメソッドには両方の形式が用意されています：`create_speech` / `create_speech_async`、`stream_speech` / `stream_speech_async`、`list_voices` / `list_voices_async`などです。

## 音声をストリーミングする

ストリーミングはオーディオチャンクのイテレータ（または非同期イテレータ）を返します。

```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.stream_speech(
        voice_id=VOICE_ID,
        text="This response is streamed chunk by chunk.",
        language="en",
        model="sona_speech_1",
    )

    with open("streamed.wav", "wb") as f:
        for chunk in response.result.iter_bytes():
            f.write(chunk)
```

非同期版は`async for chunk in response.result.aiter_bytes()`を使用します。ストリーミングは現在`sona_speech_1`のみ対応しています。

## 長文の自動チャンク分割

`create_speech`、`create_speech_async`、`stream_speech`、`stream_speech_async`は、300文字を超えるテキストを自動的に分割します。`create_speech`は最大3セグメントを並列実行してオーディオを結合し、`stream_speech`はセグメントを逐次実行してチャンクをイテレータに転送します。

```python theme={"dark"}
LONG_TEXT = "..."  # any length, including thousands of characters

response = client.text_to_speech.create_speech(
    voice_id=VOICE_ID,
    text=LONG_TEXT,
    language="en",
)

with open("narration.wav", "wb") as f:
    f.write(response.result.read())   # single merged file
```

`predict_duration`は自動チャンク分割を**行いません**。入力を300文字以内に収め、長いスクリプトでは手動で時間を合計してください。

詳細とチューニングについては[長文](/ja/docs/text-to-speech/long-text)を参照してください。

## 一般的な操作

```python theme={"dark"}
# List voices with pagination
result = client.voices.list_voices(page_size=20)

# Search voices
result = client.voices.search_voices(language="ko,en", style="happy")

# Get a single voice
voice = client.voices.get_voice(voice_id=VOICE_ID)

# Predict duration (no credits deducted)
duration = client.text_to_speech.predict_duration(
    voice_id=VOICE_ID,
    text="How long will this be?",
    language="en",
)

# Get credit balance
balance = client.usage.get_credit_balance()
```

## 型安全なenum（任意）

型安全性を求める場合、SDKは`supertone.models`にenum定数を公開しています。

```python theme={"dark"}
from supertone import models

models.APIConvertTextToSpeechUsingCharacterRequestLanguage.EN       # "en"
models.APIConvertTextToSpeechUsingCharacterRequestModel.SONA_SPEECH_1  # "sona_speech_1"
```

プレーンな文字列（`"en"`、`"sona_speech_1"`）も動作します。お好みのスタイルをお使いください。

## エラー処理

エラーは`supertone.errors`に定義されており、すべて`SupertoneError`を継承しています。

```python theme={"dark"}
from supertone import Supertone, errors

try:
    response = client.text_to_speech.create_speech(...)
except errors.TooManyRequestsErrorResponse as e:
    # 429 — back off and retry
    print("Rate limited:", e.message)
except errors.UnauthorizedErrorResponse as e:
    # 401 — bad or missing API key
    print("Auth failed:", e.message)
except errors.PaymentRequiredErrorResponse as e:
    # 402 — out of credits
    print("Buy more credits:", e.message)
except errors.SupertoneError as e:
    # Any other API error
    print(f"HTTP {e.status_code}: {e.message}")
```

| エラークラス                              | HTTPステータス |
| ----------------------------------- | --------- |
| `BadRequestErrorResponse`           | 400       |
| `UnauthorizedErrorResponse`         | 401       |
| `PaymentRequiredErrorResponse`      | 402       |
| `ForbiddenErrorResponse`            | 403       |
| `NotFoundErrorResponse`             | 404       |
| `RequestTimeoutErrorResponse`       | 408       |
| `PayloadTooLargeErrorResponse`      | 413       |
| `UnsupportedMediaTypeErrorResponse` | 415       |
| `TooManyRequestsErrorResponse`      | 429       |
| `InternalServerErrorResponse`       | 500       |

ネットワークエラー（DNS失敗、パイプの破損など）は`httpx`から発生し、`SupertoneError`を継承していません。

## 設定

```python theme={"dark"}
from supertone import Supertone
from supertone.utils.retries import RetryConfig

client = Supertone(
    api_key=os.environ["SUPERTONE_API_KEY"],
    timeout_ms=30_000,
    retry_config=RetryConfig(
        strategy="backoff",
        backoff={"initial_interval": 500, "max_interval": 60_000},
        retry_connection_errors=True,
    ),
)
```

## 関連項目

<CardGroup cols={2}>
  <Card title="TypeScript SDK" icon="js" href="/ja/docs/developer-tools/typescript">
    NodeおよびBun向けの同等のSDK。
  </Card>

  <Card title="サンプル" icon="lightbulb" href="/ja/docs/examples/llm-streaming-tts">
    一般的なワークフローのレシピ。
  </Card>
</CardGroup>
