> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.bakbak.si/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.bakbak.si/_mcp/server.

# Python SDK

`bakbak-python` is the official Python client for the Bakbak text-to-speech API. It has
sync (`Bakbak`) and asyncio (`AsyncBakbak`) clients with identical methods, safe
automatic retries, typed errors, and a WebSocket client that streams many
requests over one connection.

#### [PyPI](https://pypi.org/project/bakbak-python/)

`pip install bakbak-python`

#### [Source and examples](https://github.com/raya-voice-ai/bakbak-python)

raya-voice-ai/bakbak-python

## Install

```bash
pip install --pre bakbak-python   # 1.0 is in release candidates
```

The package is `bakbak-python` on PyPI; you import it as `bakbak`. Python 3.10 or newer. Three dependencies: `httpx`, `websockets` and `typing-extensions`.

Set your API key:

```bash
export BAKBAK_API_KEY="raya_..."
```

## Quickstart

**`Sync`**

```python Sync
from bakbak import Bakbak

client = Bakbak()  # reads BAKBAK_API_KEY

audio = client.tts.generate(
    text="नमस्ते, आप कैसे हैं?",
    voice_id="009ae8b5-4a03-492d-af1c-3055989ac734",  # Anika M1
    language="hi",
    model="m1",
)
audio.save("hello.wav")
```

**`Async`**

```python Async
import asyncio
from bakbak import AsyncBakbak

async def main() -> None:
    async with AsyncBakbak() as client:
        audio = await client.tts.generate(
            text="नमस्ते, आप कैसे हैं?",
            voice_id="009ae8b5-4a03-492d-af1c-3055989ac734",
            language="hi",
            model="m1",
        )
        audio.save("hello.wav")

asyncio.run(main())
```

Request fields keep the API's names (`voice_id`, `output_format`), so code and the
[API reference](/api-reference/introduction) read the same.

## Whole files

```python
audio = client.tts.generate(
    text="आपका ऑर्डर कल पहुँचेगा।",
    voice_id=voice_id,
    language="hi",
    model="m1",
    output_format={"container": "wav", "encoding": "pcm_s16le", "sample_rate": 24000},
)
audio.data           # bytes, exactly as received
audio.request_id     # quote it to support
audio.encoding, audio.sample_rate  # e.g. "pcm_s16le", 24000; for mp3, "mp3", None
audio.to_wav()       # raw PCM, μ-law and A-law get a WAV header
audio.save("out.wav")
```

See [Output formats](/text-to-speech/output-formats) for every `output_format`.
Without one, the SDK reads `encoding` and `sample_rate` from the WAV file's own
header. MP3 can't be wrapped in WAV, so `to_wav()` raises `ValueError` for it:
decode it with an audio library, or ask for a `wav` container.

`speed` (0.5 to 1.5) changes `standard` voices only; `m1` voices accept it and
speak at their own pace.

## Streaming (SSE)

```python
with client.tts.stream(
    text="आपका पैकेज आज शाम तक पहुँच जाएगा।",
    voice_id=voice_id,
    language="hi",
    model="m1",
    output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 24000},
) as stream:
    for chunk in stream:
        player.write(chunk.audio)  # whole samples, decoded from base64
```

A stream also has `iter_audio()`, `read()` and `save(path)`.

## WebSocket for voice agents

The [WebSocket](/text-to-speech/websocket) carries many requests over one
connection, which makes it the fastest path to first audio. Requests on a
**context** play in order; different contexts run at the same time.

```python
from bakbak import AsyncBakbak

async with AsyncBakbak() as client:  # inside an async function
    async with client.tts.websocket(
        voice_id=voice_id,
        language="hi",
        model="m1",
        output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 16000},
    ) as ws:                   # opens the socket now, so the first request pays no handshake
        ctx = ws.context()
        await ctx.send(text="पहला वाक्य।")
        await ctx.send(text="दूसरा वाक्य।")
        ctx.end_input()
        async for audio in ctx.audio():
            player.write(audio)
```

The sync `Bakbak` client has the same WebSocket API without `await`.

### Speak an LLM's reply as it is written

`ctx.send_stream()` splits text that arrives token by token into sentences and
sends each one the moment it is complete. It accepts strings, or the stream
events of OpenAI-, Anthropic- and Gemini-style SDKs directly, including Gemini's
raw REST JSON. If the stream yields events it can't read and no text at all, it
raises `TypeError` instead of sending nothing; map such events to `str` first.

```python
tokens = await llm.chat.completions.create(model=model, messages=messages, stream=True)

ctx = ws.context()
sender = asyncio.create_task(ctx.send_stream(tokens))
async for audio in ctx.audio():
    player.write(audio)
await sender
```

### Interruptions

```python
await ctx.cancel()
```

stops the context at once: the running request stops, queued ones are dropped,
any audio not yet played is discarded, and a `send_stream` feeding the context
stops. The context stays usable for the next turn.

Reconnects are handled for you: when the service restarts, requests that had
not started are resent on a new connection, in order. A request whose audio had
already started fails with `StreamInterruptedError` rather than being played twice.

## Voices

```python
for voice in client.voices.list(model="m1", language="hi"):
    print(voice.id, voice.name)
```

## Errors

Every error is a `bakbak.BakbakError`. Errors from the service carry `status`,
`error_code`, `message`, `retryable` and `request_id` (see [Errors](/text-to-speech/errors)).

```python
import bakbak

try:
    audio = client.tts.generate(text=text, voice_id=voice_id, language="hi")
except bakbak.InsufficientCreditsError as e:
    print("Top up:", e.body["required_inr"])
except bakbak.APIStatusError as e:
    print(e.status, e.error_code, e.message, e.request_id)
except bakbak.APIConnectionError:
    print("Could not reach the API")
```

## Retries and timeouts

Failures **before any audio** are retried up to `max_retries` times (default 2),
honouring `Retry-After`. Once audio has been delivered, the SDK never retries:
the start would play twice and the request was already charged.

```python
from bakbak import Bakbak, Timeout

client = Bakbak(timeout=Timeout(connect=5, read=60), max_retries=2)
```

## Latency tips

* Reuse one client, and open the WebSocket before the first turn.
* Stream sentence by sentence with `send_stream`.
* Ask for the format you play: for phone calls,
  `{"container": "raw", "encoding": "pcm_mulaw", "sample_rate": 8000}`.

The [README](https://github.com/raya-voice-ai/bakbak-python#readme) covers every
option, the sync WebSocket client, raw responses and the sentence segmenter.