Skip to content

voice213 is the official Voice213 SDK for Python 3.9 and later. It covers the whole developer API: voice-overs, KhasbhaSTT transcription, KhasbhaSTT LIVE sessions, the catalogue and your account. It has two clients with the same methods: Voice213, synchronous, and AsyncVoice213, for asyncio apps such as FastAPI.

pip install voice213
from voice213 import Voice213

client = Voice213()  # reads VOICE213_API_KEY

speech = client.text_to_speech.create("مرحبا بيكم في Voice213", voice="kenza", model="voice213-pro-2")
speech.save("welcome.mp3")
print(f"{speech.cost} {speech.currency}, {speech.remaining_credit} left")

transcript = client.speech_to_text.transcribe("call.mp3", language="ar", dialect="algerian")
print(transcript.text)

The names are the JavaScript SDK's, in snake_case: textToSpeech.create() is text_to_speech.create(), and remainingCredit is remaining_credit.

​Your API key

Voice213() reads your key from the VOICE213_API_KEY environment variable: see Get Your API Key to create one and set it. To take it from somewhere else, such as a secret manager, pass it: Voice213(api_key=...). The key is checked when a request needs it: without one, the request fails before it's sent, with the code MISSING_API_KEY. health() needs no key.

The key pays for every request from your API credit. Keep it on your server, never in an app or a web page you ship. To transcribe live in a browser or an app, your server hands it a single-use token instead: see Tokens for browsers and apps.

​Sync and async

Voice213 waits for each answer before it returns. AsyncVoice213 has the same methods as coroutines, so you can run requests side by side, or call Voice213 from an async web framework without blocking it:

import asyncio

from voice213 import AsyncVoice213


async def main():
    client = AsyncVoice213()  # reads VOICE213_API_KEY
    speech, transcript = await asyncio.gather(
        client.text_to_speech.create("مرحبا بيكم في Voice213", voice="kenza"),
        client.speech_to_text.transcribe("call.mp3"),
    )
    await speech.save("welcome.mp3")  # on AsyncVoice213, read() and save() are coroutines too
    print(speech.cost, transcript.text)


asyncio.run(main())

Create one client and reuse it for every request. Live sessions are asynchronous, so they're on AsyncVoice213 only: the synchronous client creates live tokens, and its live.connect() raises a Voice213Error with the code UNSUPPORTED.

​Voice-overs

text_to_speech.create() turns a script into a voice-over, with any of the five models and the 30 voices:

from voice213 import Voice213

client = Voice213()

speech = client.text_to_speech.create(
    "(نبرة حماسية) العرض راهو متوفر غير هاد السيمانة!",
    voice="ryad",  # one of the 30 voices: client.voices.list()
    model="voice213-pro-2",  # voice213-lite (the default), -lite-2, -pro, -pro-1.5 or -pro-2
    dialect="algerian",  # algerian (the default), tunisian or libyan
    target_duration_seconds=15,  # optional: about 15 seconds, to fit a video
)
speech.save("ad.mp3")
print(speech.audio_url, f"{speech.cost} DA", f"{speech.remaining_credit} DA left")

Tone directions in parentheses, such as (نبرة حماسية), are performed, not read, and aren't billed: see Tone Directions. Text to Speech describes every parameter, and what each one costs.

​The speech

create() returns a Speech, with the same attributes whichever format the API answered in:

AttributeValue
audio_urlA link to the MP3, also saved to your History in the web app. With inline=True, a data: URL carrying the WAV
format, content_typemp3 and audio/mpeg, or wav and audio/wav with inline=True
storedWhether the voice-over was saved to your History
model, voiceThe model and the voice that spoke
cost, currencyWhat it cost, in dinars (DZD)
chars, billable_charsThe characters counted, and the characters billed: 100 at least
wordsThe words spoken
remaining_creditYour API credit after the request
rawThe answer, as the API sent it
MethodWhat it does
save(path)Writes the audio to path, creating its folder if needed, and returns the path
read()The audio as bytes. It's downloaded once, then kept

On AsyncVoice213, read() and save() are coroutines: await speech.save("ad.mp3").

​Inline audio

Pass inline=True to get the audio inside the answer, as a WAV file. Nothing is stored, and target_duration_seconds doesn't apply:

from voice213 import Voice213

client = Voice213()

speech = client.text_to_speech.create("مرحبا بيكم في Voice213", voice="nariman", inline=True)
speech.save("speech.wav")  # speech.format is "wav"

​Price a script first

text_to_speech.estimate() tells you what a voice-over would cost on a model, without generating it, and whether your API credit covers it. It's free:

from voice213 import Voice213

client = Voice213()

quote = client.text_to_speech.estimate("مرحبا بيكم في Voice213", model="voice213-pro-2")
print(f"{quote.billable_chars} characters, {quote.cost} DA", "" if quote.enough else "(top up first)")

The quote has model, chars, billable_chars, price_per_1m_chars, cost, currency, balance and enough. See Estimate Cost.

​Speech to text

speech_to_text.transcribe() sends a recording to KhasbhaSTT and returns its transcript. Pass the file first, or the link to a recording that's already online as url:

from voice213 import Voice213

client = Voice213()

transcript = client.speech_to_text.transcribe(
    "interview.mp4",  # a path, bytes, or a file opened in binary mode
    language="ar",  # ar (the default), fr or en
    dialect="algerian",  # for Arabic: algerian (the default), tunisian or libyan
    speakers=True,  # "المتحدث 1:" before each speaker's lines
)
print(transcript.text)
print(f"{transcript.billable_seconds} s billed, {transcript.cost} DA")

# A recording that's already online: Voice213 downloads it
from_link = client.speech_to_text.transcribe(url="https://cdn.example.com/calls/2026-11-20-1432.mp3")
print(from_link.text)
  • The file can be a path (a str or a pathlib.Path), bytes, or a file object opened in binary mode, such as open("call.mp3", "rb"). Its name and type come from the path or the file object; for bytes, set them with filename= and content_type=.
  • The other fields of POST /stt are keyword arguments: model, language, dialect, speakers, punctuation and profanity, with booleans as True and False.
  • The transcript has text, model, language, dialect, duration_seconds, billable_seconds, cost, currency and remaining_credit.

A long recording can take a few minutes to upload and transcribe: the SDK waits up to 10 minutes for the answer. A file object is sent again on a retry only if it can seek back to where it started, as a file on disk can; a pipe or a network stream is sent once.

​Price a recording

speech_to_text.estimate() prices audio from its length in seconds, free, as a file or as a live session:

from voice213 import Voice213

client = Voice213()

# Ten minutes of audio, as a recording and as a live session
for model in ["khasbha-stt", "khasbha-stt-live"]:
    quote = client.speech_to_text.estimate(600, model=model)
    print(model, f"{quote.billable_seconds} s, {quote.cost} DA", quote.enough)

​Live transcription

KhasbhaSTT LIVE writes speech down while it's spoken. A session is a single-use token and one socket. On AsyncVoice213, speech_to_text.live.connect() creates both, and gives you a session that streams your audio and keeps the transcript. Use it with async with: leaving the block closes the socket. See KhasbhaSTT LIVE for how sessions work and what they cost.

​Stream a recording

import asyncio

from voice213 import AsyncVoice213


async def main():
    client = AsyncVoice213()  # reads VOICE213_API_KEY
    async with client.speech_to_text.live.connect(
        language="ar",
        dialect="algerian",
        vocabulary=["Yalidine", "Baridimob"],  # names to recognize
        max_seconds=900,  # your own cap on the session
    ) as session:
        # A WAV file at real-time pace, then `end`: the task's result is the summary
        sender = asyncio.create_task(session.send_file("call.wav"))
        async for event in session:  # every message from the server, until the socket closes
            if event.type == "transcript" and event.final:
                print(event.text)
            elif event.type == "warning":
                print(f"{event.seconds_left} s left")
        summary = await sender
        print(f"{summary.billable_seconds} s billed, {summary.cost} DA")
        print(session.text)  # every final sentence, one per line


asyncio.run(main())
  • connect() takes the token's fields, all optional: language, dialect, vocabulary, max_seconds, and origin. See Create a Live Token.
  • send_file() reads a WAV file at any sample rate and channel count, from a path or bytes, sends it as 16 kHz mono at real-time pace, then ends the session and returns the ended summary. With end=False, it leaves the session open. Convert other formats to WAV first, for example with ffmpeg -i call.mp3 -ar 16000 -ac 1 -c:a pcm_s16le call.wav.
  • Each event is a message from the server, with its fields as attributes in snake_case: event.type, then text, final and segment for a transcript, seconds_left for a warning, code and message for an error, reason, billable_seconds, cost and remaining_credit for the summary. event.raw is the message as a dict.

​Stream audio yourself

For audio that arrives as it's captured, such as a call, send 16 kHz, 16-bit mono PCM with await session.send(), at the pace it's recorded, and finish with await session.end(), which returns the summary. Here the audio comes from a file:

import asyncio
import wave

from voice213 import AsyncVoice213

FRAME = 3200  # 100 ms of 16 kHz, 16-bit mono audio


async def stream(session, pcm):
    # In your app, each chunk as it's captured; here, a file at the pace it was recorded
    for at in range(0, len(pcm), FRAME):
        await session.send(pcm[at : at + FRAME])
        await asyncio.sleep(0.1)
    return await session.end()


async def main():
    with wave.open("call.wav", "rb") as wav:  # 16 kHz, 16-bit, mono
        pcm = wav.readframes(wav.getnframes())

    client = AsyncVoice213()  # reads VOICE213_API_KEY
    async with client.speech_to_text.live.connect(language="ar", dialect="algerian") as session:
        sender = asyncio.create_task(stream(session, pcm))
        async for event in session:
            if event.type == "transcript" and event.final:
                print(event.text)
        summary = await sender
        print(f"{summary.reason}: {summary.billable_seconds} s billed, {summary.cost} DA")


asyncio.run(main())

A session that gets more than 10 seconds ahead of real time ends with TOO_FAST. await session.flush() finalizes the sentence being spoken, for example when a push-to-talk button is released. to_live_pcm() and the other audio helpers convert audio in other forms.

​Tokens for browsers and apps

A browser or a mobile app opens the session itself, with a token your server creates. Both clients create tokens:

from voice213 import Voice213

client = Voice213()  # reads VOICE213_API_KEY

# For a page on https://shop.example, for 10 minutes at most
token = client.speech_to_text.live.create_token(language="ar", max_seconds=600, origin="https://shop.example")
print(token.url, token.expires_in)  # hand token.url to the page: it opens one session, within two minutes

The token also has token, ws_url, model, language, dialect, max_seconds and the audio format. In a web page, LiveSession from the JavaScript SDK opens the url and streams the microphone: see KhasbhaSTT LIVE, and Create a Live Token for a FastAPI route.

​The session

AttributeValue
statusconnecting, starting (the socket is open, the session is starting), live, ending (after end()), then ended. Or failed, or closed after close()
textEvery final sentence so far, one per line
partialThe sentence being spoken, as heard so far: "" between sentences
session_id, max_secondsFrom ready: the session's id, and how long it can last
MethodWhat it does
await send(pcm)Sends 16 kHz, 16-bit mono PCM: bytes, bytearray or memoryview, a whole number of samples
await send_file(source, end=True)Streams a WAV file at real-time pace, then ends the session and returns the summary
await flush()Finalizes the sentence being spoken, without waiting for the silence after it
await ping()An application-level heartbeat: the server answers with a pong event
await end()Finishes: the last final sentences arrive, then the summary, which it returns
await close()Closes the socket without end. The audio received is billed, and no summary comes
await wait()Waits for the summary
await wait_ready()Waits for the ready message
async for event in sessionEvery message from the server, until the socket closes

end(), send_file() and wait() raise a LiveSessionError when the session fails instead. See Live Transcription Socket for what each message, end reason and error code means.

​The catalogue and your account

from voice213 import Voice213

client = Voice213()

voices = client.voices.list()  # the 30 voices, and default_voice
tones = client.tones.list()  # tone directions: categories, and tones by category id
models = client.models.list()  # voice models and their prices, and default_model
stt_models = client.speech_to_text.models.list()  # KhasbhaSTT and KhasbhaSTT LIVE
account = client.account.get()  # your API credit, and your account's limits

print(len(voices.voices), voices.default_voice, [stage.id for stage in tones.categories])
print([model.id for model in models.models], [model.id for model in stt_models.models])
print(account.credit, account.currency, account.key.rate_limit.rpd, client.health().ok)  # health() needs no key

They're free, and rarely change: read them once and keep the answer. The answers are the API's, without success, with the voices and the tones taken out of the data the API wraps them in, and account.get() flattens GET /me to credit, currency and key. Every name is in snake_case: a voice's name_en, a model's price_per_1m_chars, the limits' key.rate_limit.concurrent_requests.

​Errors

Every error the SDK raises is a Voice213Error, with a code to branch on and a message in English, even when the API's own is in Arabic. Answers from the API are APIErrors, one class per status:

from voice213 import InsufficientCreditError, RateLimitError, Voice213, Voice213Error

client = Voice213()

try:
    client.text_to_speech.create("مرحبا بيكم في Voice213")
except InsufficientCreditError as error:
    print(f"Top up: {error.required} DA needed, {error.balance} DA available")
except RateLimitError as error:
    print("Daily limit reached: try again tomorrow" if error.code == "RATE_LIMIT_DAY" else error.message)
except Voice213Error as error:
    print(error.code, error.message)
ClassStatusCodes include
BadRequestError400UNKNOWN_VOICE, UNKNOWN_MODEL, EMPTY_TEXT, TEXT_TOO_LONG, TOO_MANY_WORDS, INVALID_MEDIA, AUDIO_TOO_LONG…
AuthenticationError401INVALID_API_KEY, MISSING_API_KEY
InsufficientCreditError402INSUFFICIENT_CREDIT
PermissionDeniedError403API_ACCESS_BLOCKED, ACCOUNT_DEACTIVATED
NotFoundError, EndpointRemovedError, PayloadTooLargeError404, 410, 413NOT_FOUND, ENDPOINT_REMOVED, FILE_TOO_LARGE
RateLimitError429RATE_LIMIT_MINUTE, RATE_LIMIT_DAY, RATE_LIMIT_CONCURRENT, SESSION_LIMIT, RATE_LIMITED
InternalServerError500, 502, 504TRANSCRIPTION_FAILED, GENERATION_FAILED, INTERNAL_ERROR
ServiceUnavailableError503MODEL_DISABLED, TOOL_DISABLED, MAINTENANCE
APIConnectionError, APITimeoutError—CONNECTION_ERROR, TIMEOUT
LiveSessionError—The socket's codes (TOO_FAST, SESSION_LIMIT…), CONNECTION_FAILED, CONNECTION_LOST, CLOSED
  • Every APIError has the status_code, the answer's body and headers, and retry_after: the seconds of the Retry-After header, or None.
  • InsufficientCreditError adds required and balance, in dinars, and currency. RateLimitError adds limit. ServiceUnavailableError adds ends_at for maintenance, tool for TOOL_DISABLED and model for MODEL_DISABLED. LiveSessionError adds close_code, the socket's close code.
  • APITimeoutError means no answer came in time. A voice-over or a transcription may still finish and be charged: raise timeout rather than sending it again.
  • Problems caught before any request is sent are plain Voice213Errors, such as MISSING_API_KEY, INVALID_FILE (no file or url, or both) and UNSUPPORTED_AUDIO.

See Errors for what each code means and what to do about it.

​Retries and timeouts

The SDK retries what can succeed on a second attempt, twice by default, after the API's Retry-After when it sends one (a minute at most), and with exponential backoff otherwise:

  • 429, except your account's daily limit (RATE_LIMIT_DAY), which won't clear today;
  • 500, 502, 503 and 504, except a paused model (MODEL_DISABLED): use another model;
  • a connection that failed before the request reached Voice213, and, for the free requests, any connection error or timeout.

A voice-over or a transcription that may have reached Voice213, but whose answer never came, is never sent again: Voice213 finishes it and charges it even when your client stops waiting, so a second attempt could pay twice. Give long requests time instead:

from voice213 import Voice213

# Every request: up to 4 retries, and 15 minutes for an answer
client = Voice213(max_retries=4, timeout=15 * 60)

# One request: 20 minutes for an answer
transcript = client.speech_to_text.transcribe("meeting.mp3", timeout=20 * 60)
print(transcript.text)

Every method takes timeout= and max_retries= for that request only. See Handle errors and retry safely.

​Configuration

Voice213 and AsyncVoice213 take the same arguments:

ArgumentDefaultWhat it sets
api_keyVOICE213_API_KEYYour API key
base_urlVOICE213_BASE_URL, else https://api.voice213.comThe API's address
timeout600.0: 10 minutesHow long to wait for an answer, in seconds
max_retries2How many times to retry a failure that can succeed on a later attempt
default_headersNoneHeaders sent with every request
http_clientBuilt inYour own httpx.Client, or httpx.AsyncClient for AsyncVoice213, to go through a proxy for example

​Audio helpers

The functions the SDK uses for live audio are exported, for your own pipelines:

ExportWhat it does
LIVE_SAMPLE_RATE16000, the sample rate a live session takes
to_live_pcm(data)A WAV file or raw PCM, as 16 kHz 16-bit mono PCM, ready for send()
read_wav(data)A WAV file's sample_rate, channels and pcm, mixed down to mono
decode_mulaw(data), encode_mulaw(pcm)G.711 μ-law, the codec of phone lines, to 16-bit PCM, and back
resample_pcm16(pcm, from_rate, to_rate)Changes the sample rate of 16-bit PCM

The answers' classes are in voice213.types, for your type checker, and voice213.__version__ is the SDK's version.

​Next steps

Was this page helpful?