Skip to navigation

JavaScript SDK

The official JavaScript and TypeScript client for Bakbak TTS, for Node, Bun, Deno, Workers and browsers.
View as Markdown

bakbak is the official JavaScript and TypeScript client for the Bakbak text-to-speech API. It has no runtime dependencies, is typed end to end, and runs on Node 20+, Bun, Deno, Cloudflare Workers and browsers.

Install

npm install bakbak
npm install ws # optional, for the WebSocket on Node (Node 22+ can do without it)
export BAKBAK_API_KEY="raya_..."

Quickstart

import { Bakbak } from 'bakbak';
const client = new Bakbak(); // reads BAKBAK_API_KEY
const audio = await client.tts.generate({
text: 'नमस्ते, आप कैसे हैं?',
voice_id: '009ae8b5-4a03-492d-af1c-3055989ac734', // Anika M1
language: 'hi',
model: 'm1',
});
await audio.save('hello.wav'); // Node, Bun and Deno

Request fields keep the API’s names (voice_id, output_format), so code, curl and the API reference read the same.

Whole files

const audio = await client.tts.generate({
text, voice_id, language: 'hi', model: 'm1',
output_format: { container: 'wav', encoding: 'pcm_s16le', sample_rate: 24000 },
});
audio.data; // Uint8Array
audio.requestId; // quote it to support
audio.toWav(); // raw audio gets a WAV header; mp3 throws (decode it instead)

Streaming (SSE)

const stream = client.tts.stream({
text, voice_id, language: 'hi', model: 'm1',
output_format: { container: 'raw', encoding: 'pcm_s16le', sample_rate: 24000 },
});
for await (const chunk of stream) play(chunk.audio); // Uint8Array, whole samples

An AudioStream can also become a ReadableStream (stream.toReadableStream()), for example to answer an HTTP request with audio as it is generated.

WebSocket for voice agents

The WebSocket carries many requests over one connection, the fastest path to first audio. Requests on a context play in order; different contexts run at the same time.

const ws = client.tts.websocket({ voice_id, language: 'hi', model: 'm1' });
await ws.connect(); // optional: open now so the first request pays no handshake
const ctx = ws.context();
await ctx.send({ text: 'नमस्ते!' });
await ctx.send({ text: 'मैं आपकी कैसे मदद कर सकती हूँ?' });
ctx.endInput();
for await (const audio of ctx.audio()) play(audio);

Speak an LLM’s reply as it is written

const llm = await openai.chat.completions.create({ model, messages, stream: true });
const ctx = ws.context();
const sending = ctx.sendStream(llm); // or any (async) iterable of strings
for await (const audio of ctx.audio()) play(audio);
await sending;

sendStream() splits the tokens into sentences and sends each one as soon as it is complete. It accepts strings and stream events from the OpenAI, Anthropic, Google Gemini and Vercel AI SDKs, and Gemini’s raw REST JSON. If the stream yields events it can’t read and no text at all, it throws instead of sending nothing; map such events to strings first.

Interruptions

await ctx.cancel();

stops the running request, drops queued ones, discards audio not yet played and stops a sendStream feeding the context. The context stays usable.

Voices

const { voices } = await client.voices.list({ model: 'm1', language: 'hi' });

Errors

Everything the SDK throws is a BakbakError. Errors from the service have status, errorCode, message, retryable and requestId (see Errors).

import { InsufficientCreditsError, StreamInterruptedError } from 'bakbak';
try {
await client.tts.generate(params);
} catch (err) {
if (err instanceof InsufficientCreditsError) console.log('top up:', err.body);
else if (err instanceof StreamInterruptedError) console.log(`cut off after ${err.audioBytes} bytes`);
else throw err;
}

Retries and timeouts

Failures before any audio are retried up to maxRetries times (default 2), honouring Retry-After. Once audio has been delivered the SDK never retries.

const client = new Bakbak({ timeout: 60_000, maxRetries: 2 });
await client.tts.generate(params, { signal: AbortSignal.timeout(10_000) });

Browsers

An API key in a web page is visible to anyone who uses the page. The SDK refuses to run in a browser with a key unless you pass dangerouslyAllowBrowser: true; call the API from your server instead.

The README covers every option, runtimes, telephony formats and the sentence segmenter.