Skip to main content

gnani-vachana

License: MIT

Official Python client by Gnani.ai. Build multilingual voice workflows with Speech-to-Text (STT), Text-to-Speech (TTS) and LLM chat completions across REST, SSE streaming, and real-time WebSockets.

Gnani.ai is a production-ready speech AI platform with high-accuracy STT and low-latency TTS for 10+ Indian languages, with Timbre voices across REST, SSE, and WebSocket APIs.

Installation

pip install gnani-vachana

Or with uv:

uv add gnani-vachana

The LLM chat completions client is built on the official openai package, which is installed only when you ask for it:

pip install "gnani-vachana[llm]"

STT and TTS need no extra. Requires Python 3.9+.

Quick Start

STT REST (file-based transcription)

from gnani.stt import GnaniSTTClient

client = GnaniSTTClient(api_key="your-api-key")

result = client.transcribe("audio.wav", language_code="hi-IN")
print(result["transcript"])

STT Batch (many or long files)

from gnani.stt import GnaniSTTBatchClient

client = GnaniSTTBatchClient()  # reads GNANI_API_KEY
result = client.transcribe(["call1.wav", "call2.wav"], language_code="hi-IN")

print(result[0].text)
result.save("./outputs")  # one JSON per file

See Batch STT usage for step-by-step control, diarization, and webhooks.

Realtime Streaming (WebSocket)

import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async def main():
    async with GnaniSTTStreamClient(api_key="your-api-key", language_code="hi-IN") as stream:
        # Send audio chunks (raw PCM, 16-bit LE, 16 kHz, mono)
        with open("audio.pcm", "rb") as f:
            while chunk := f.read(1024):
                await stream.send_audio(chunk)
                await asyncio.sleep(0.032)  # real-time pacing (32 ms per frame)

        # Iterate over events
        async for event in stream:
            if isinstance(event, StreamTranscriptEvent):
                print(event.text)

asyncio.run(main())

TTS REST (single response)

from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")

# timbre-v2.5 (default model)
audio = client.synthesize(
    "नमस्ते, आप कैसे हैं?",
    voice="Pranav",
    model="timbre-v2.5",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
)

# timbre-v3.0 — 34 voices, each speaks all ten languages
audio = client.synthesize(
    "नमस्ते, आप कैसे हैं?",
    voice="Shivani",
    model="timbre-v3.0",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
)

# timbre-v2.5 — language control + speed
audio = client.synthesize(
    "नमस्ते, यह एक परीक्षण है।",
    voice="Nalini",
    model="timbre-v2.5",
    language="hi-IN",
    speed=1.0,
    audio_config=AudioConfig(container="mp3", sample_rate=48000, bitrate="128k"),
)

with open("tts_output.mp3", "wb") as f:
    f.write(audio)

TTS SSE Streaming (lower latency)

from gnani.tts import GnaniTTSStreamClient, AudioConfig

client = GnaniTTSStreamClient(api_key="your-api-key")
audio = client.synthesize(
    "Hello from Gnani TTS",
    voice="Pranav",
    model="timbre-v2.5",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
    output_file="tts_sse.wav",
)

TTS Realtime WebSocket (lowest latency)

import asyncio
from gnani.tts import GnaniTTSRealtimeClient, AudioConfig

async def main():
    async with GnaniTTSRealtimeClient(api_key="your-api-key") as client:
        audio = await client.synthesize_and_collect(
            "Hello from Gnani TTS",
            voice="Pranav",
            model="timbre-v2.5",
            audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
            output_file="tts_realtime.wav",
        )

asyncio.run(main())

LLM Chat Completions

GnaniLLMClient and AsyncGnaniLLMClient call the chat completions API (POST /v1/chat/completions, default model evon-v3.5). They are the official openai client, set up for Gnani, so you use them exactly as you would use OpenAI and AsyncOpenAI: client.chat.completions.create(...). Install the extra first: pip install "gnani-vachana[llm]".

The API is stateless: send the whole conversation in messages on every call. The API key must have access to the LLM API (otherwise 403 SCOPE_NOT_ALLOWED).

from gnani.llm import GnaniLLMClient

client = GnaniLLMClient()  # reads GNANI_API_KEY

reply = client.chat.completions.create(
    messages=[
        {"role": "system", "content": "Be brief."},
        {"role": "user", "content": "Say hello in Hindi."},
    ],
)
print(reply.choices[0].message.content)
print(reply.usage.total_tokens)  # also prompt_tokens, completion_tokens

reply is the whole answer. model defaults to evon-v3.5, and stream to False.

Why stream=False? The Gnani API streams unless told not to, the opposite of OpenAI's, and the openai package leaves stream out when you do not set it. Used directly, a plain create() would come back as raw server-sent events. These clients send stream=False for you.

Streaming

Pass stream=True and read the chunks as they arrive. Each chunk is one small piece of the answer.

for chunk in client.chat.completions.create(
    messages=[{"role": "user", "content": "Count 1 to 3."}],
    stream=True,
    stream_options={"include_usage": True},  # adds a last chunk with token usage
):
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="", flush=True)
    else:
        print("\n", chunk.usage)

Async

AsyncGnaniLLMClient is the same, with await and async for:

import asyncio
from gnani.llm import AsyncGnaniLLMClient

async def main():
    async with AsyncGnaniLLMClient() as client:
        reply = await client.chat.completions.create(
            messages=[{"role": "user", "content": "Say hello in Hindi."}],
        )
        print(reply.choices[0].message.content)

        stream = await client.chat.completions.create(
            messages=[{"role": "user", "content": "Count 1 to 3."}],
            stream=True,
        )
        async for chunk in stream:
            if chunk.choices:
                print(chunk.choices[0].delta.content or "", end="", flush=True)

asyncio.run(main())

Reasoning

evon-v3.5 is a reasoning model. Its thinking comes back in message.reasoning (delta.reasoning when streaming), before the answer in content. Reasoning counts against max_tokens: with a small limit the reply can end (finish_reason == "length") before any answer, and content is None.

Tool calling and other options

reply = client.chat.completions.create(
    messages=[{"role": "user", "content": "What is the weather in Pune? Use the tool."}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Current weather for a city.",
            "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
        },
    }],
    max_tokens=600,
)
call = reply.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)  # get_weather {"city": "Pune"}

Also accepted: temperature, top_p, max_tokens, stop, seed, frequency_penalty, presence_penalty, tool_choice, response_format, and the per-call extra_headers, extra_query, extra_body and timeout. n > 1 is not supported by the API.

To tag a request for support, send your own ID; the API echoes it back and logs it: extra_headers={"X-API-Request-ID": "my-request-1"}.

Client options

The clients take every openai option on top of api_key and base_url. The useful ones:

Option Default Notes
api_key GNANI_API_KEY OPENAI_API_KEY is never read.
base_url https://api.vachana.ai /v1 is added when missing.
timeout 120 seconds Read timeout; it also applies between streamed chunks.
max_retries 2 Retries connection errors, 408, 409, 429 and 5xx with backoff. 0 turns them off.

LLM errors

Errors are the openai package's own:

import openai

try:
    client.chat.completions.create(messages=messages)
except openai.APIStatusError as e:
    print(e.status_code, e.code, e.message)
    # 400 content_filter       -> blocked by the prompt-injection guardrail
    # 400 model_rejected_request, 404 model_not_found
    # 401 INVALID_API_KEY, 403 SCOPE_NOT_ALLOWED, 429 RATE_LIMITED   (from the gateway)
except openai.APIConnectionError as e:
    print(f"Could not reach the API: {e}")

Subclasses such as openai.AuthenticationError, openai.RateLimitError and openai.BadRequestError are raised for the matching status codes. The API's gateway answers a bad key in its own shape ({"detail": {"error_code", "message"}}); the clients keep its message and put error_code in e.code, so a rejected key reads Error code: 401 - The API key is not valid. (INVALID_API_KEY).

A missing key raises openai.OpenAIError when the client is created. Phone numbers, PAN and email addresses in a prompt are masked by the API ([REDACTED_PHONE], [REDACTED_PAN], [REDACTED_EMAIL]), in the prompt and in the model's output.

The model server behind the API adds fields that are not part of the documented response (prompt_logprobs, kv_transfer_params, stop_reason, ...). They are not removed. They are available in reply.model_extra / reply.model_dump(); ignore them.

Authentication

All APIs (STT REST, STT Realtime, TTS, LLM) require a single API key:

Parameter Header Description
api_key X-API-Key-ID API key identifier for authentication

Obtaining Credentials

You need a Gnani API key. Gnani APIs have this.

Passing Credentials

Option 1 -- Constructor argument:

from gnani.stt import GnaniSTTClient, GnaniSTTStreamClient
from gnani.tts import GnaniTTSClient, GnaniTTSRealtimeClient, GnaniTTSStreamClient

client = GnaniSTTClient(api_key="your-api-key")
stream = GnaniSTTStreamClient(api_key="your-api-key")
tts_rest = GnaniTTSClient(api_key="your-api-key")
tts_stream = GnaniTTSStreamClient(api_key="your-api-key")
tts_realtime = GnaniTTSRealtimeClient(api_key="your-api-key")

Option 2 -- Environment variable:

export GNANI_API_KEY="your-api-key"
from gnani.stt import GnaniSTTClient, GnaniSTTStreamClient
from gnani.tts import GnaniTTSClient

client = GnaniSTTClient()           # picks up GNANI_API_KEY
stream = GnaniSTTStreamClient()     # picks up GNANI_API_KEY
tts = GnaniTTSClient()              # picks up GNANI_API_KEY

Supported Languages

STT Languages (Speech-to-Text)

STT uses BCP-47 locale codes (e.g. hi-IN). For the full list of supported languages, see:


TTS Voices & Models

TTS uses the Timbre engine. Two model IDs are supported:

Model Voices language / speed
timbre-v2.5 (default) 42 voices, one preferred language each Supported
timbre-v3.0 34 voices, each speaks all ten languages Supported

The two models have separate voice catalogs: a voice from one is refused with the other.

Migration: timbre-v2.0 (formerly vachana-voice-v3) is no longer accepted; the client raises ValueError for it. Use timbre-v2.5 (or omit model).

timbre-v2.5 voices

42 Timbre voices across Hindi, English, Tamil, Telugu, Kannada, Malayalam, Marathi, Bengali, Gujarati, Punjabi, and Hinglish. Examples: Nalini, Kaveri, Asmita, Suhana, Poorvi.

timbre-v3.0 voices

34 voices, each speaking all ten languages: Avinash, Shivani, Lakshmi, Kalpana, Shubham, Prakash, Devansh, Yashraj, Chetana, Vasudha, Riyaa, Tarika, Harshad, Anitasingh, Lakshmidevi, Priyasharm, Rahulmehta, Vikramdasu, Sohini, Arko, Sunaina, Rajeev, Rajni, Mahendra, Neelam, Rakesh, Shruthi, Manjunath, Rekha, Vinod, Santosh, Sneha, Nitin, Swathi. Voice names are case-sensitive.

List voices programmatically:

from gnani.tts import GnaniTTSClient

print(GnaniTTSClient.supported_voices())                    # timbre-v2.5 (default), 42 voices
print(GnaniTTSClient.supported_voices(model="timbre-v3.0")) # 34 voices

Optional controls (timbre-v2.5 and timbre-v3.0)

Both models accept the language and speed parameters:

Parameter Type Description
language str BCP-47 code: auto, hi-IN, en-IN, ta-IN, te-IN, kn-IN, ml-IN, mr-IN, bn-IN, gu-IN, pa-IN
speed float Speaking rate multiplier. The range depends on the model, see below.

Speed. The allowed range is per model (gnani.tts.SPEED_RANGES). A value outside it raises ValueError before anything is sent.

Model Range Left out Result
timbre-v2.5 0.85–1.15 1.0 is sent the speed you give
timbre-v3.0 0.8–1.2 nothing is sent the voice's own speed

timbre-v3.0 produces only three speeds, 0.8, 1.0 and 1.2. The service rounds what you give to the nearest of them (a value halfway between two, such as 0.9 or 1.1, goes to 1.0), so 0.85 and 0.89 give 0.8, and 1.11 and 1.15 give 1.2. The SDK sends your value as it is.

voice is required for all Timbre models unless speaker_embedding is provided.

TTS Languages (Text-to-Speech)

For the full list of supported languages, see TTS — Supported Languages.

REST Usage

Transcribe a file by path

result = client.transcribe("meeting.wav", language_code="en-IN")
print(result["transcript"])

Transcribe from a file object

with open("meeting.mp3", "rb") as f:
    result = client.transcribe(f, language_code="ta-IN")

Transcribe raw bytes

audio_bytes = download_audio_from_somewhere()
result = client.transcribe_bytes(
    audio_bytes, filename="clip.wav", language_code="kn-IN"
)

Custom request ID

result = client.transcribe(
    "call.flac", language_code="hi-IN", request_id="my-trace-123"
)

List supported languages

for code, name in GnaniSTTClient.supported_languages().items():
    print(f"{code}: {name}")

Prisma v3.0 (multilingual model)

prisma-v3.0 is one model for all ten languages. It is opt-in: pass model="prisma-v3.0"; without it nothing changes. It works on REST, streaming and batch.

from gnani.stt import GnaniSTTClient

client = GnaniSTTClient()

# Let the model identify the language
result = client.transcribe("clip.wav", language_code="indic-auto", model="prisma-v3.0")
print(result["transcript"], result.get("detected_language_code"))   # "...", "ta-IN"

# Hint the likely languages (2-4); one transcript comes back, in the language heard
result = client.transcribe(
    "clip.wav",
    language_code="indic-auto",
    model="prisma-v3.0",
    language_candidates=["hi-IN", "en-IN"],
)

# Force a language, with context and an output style
result = client.transcribe(
    "clip.wav",
    language_code="hi-IN",
    model="prisma-v3.0",
    format="codemix",                     # or "verbatim" / "transcribe" / "transliterate"
    topic="Loan collection calls for a retail credit card portfolio",
    keywords=["HDFC Bank", "EMI", "खाता"],
)
Option Where Notes
language_code="indic-auto" REST, streaming model identifies the language (batch: "auto")
language_candidates REST, streaming 2-4 languages, only with "indic-auto". A hint, not a limit. In batch, pass 2-4 comma-separated codes in language_code instead
format="codemix" REST, streaming, batch English stays in Latin, numbers as native words
format="transliterate" REST, streaming speech written in Latin letters. Not available in batch
keywords REST, streaming, batch words or short phrases to favour, up to 200
topic REST, batch what the audio is about: up to 1,600 characters on REST; batch needs 30-1,600
speaker_names REST, batch 1-4 names that may be spoken
previous_text REST transcript of the previous clip (the last 600 characters are used)

REST and streaming take any combination of the context options. Batch accepts only keywords, topic, topic + keywords, or speaker_names. These options raise ValueError with any other model. REST audio is limited to 30 s per request with this model.

Responses add detected_language_code (judged from the transcript's script) and, if the model had to cut the text short, truncated: true.

Streaming:

from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async with GnaniSTTStreamClient(
    language_code="indic-auto",
    model="prisma-v3.0",
    language_candidates=["hi-IN", "en-IN"],   # optional
    keywords=["Vachana", "UPI"],              # optional
) as stream:
    async for event in stream:
        if isinstance(event, StreamTranscriptEvent):
            print(event.detected_language_code, event.text)

Batch:

from gnani.stt import GnaniSTTBatchClient

result = GnaniSTTBatchClient().transcribe(
    "./calls/",
    language_code="hi-IN,en-IN",        # one code, "auto", or 2-4 codes
    model="prisma-v3.0",
    format="transcribe",
    keywords=["HDFC Bank", "EMI"],
    speakers=2,
)
for f in result:
    print(f.name, f.language)           # language covering the most speech
    for seg in f.segments:
        print(seg.language, seg.text)   # language of each segment

With prisma-v3.0 the language is decided per segment by the model, so there is no fallback language and order in language_code does not matter.

Batch STT Usage

Batch jobs run asynchronously: create, start, wait, fetch. transcribe() does all four. Limits: 100 files per job, 10 MB per file (ZIP: 50 MB). Larger files are not supported yet.

from gnani.stt import GnaniSTTBatchClient

client = GnaniSTTBatchClient()

# Files can be a path, a directory, a glob, a ZIP, bytes, a file object, or public URLs.
result = client.transcribe("./recordings/", language_code="hi-IN,en-IN", speakers=2)

for f in result:
    print(f.name, "OK" if f.ok else f"FAILED: {f.error}")
    if f.ok:
        for seg in f.segments:
            print(f"  [{seg.start:.1f}-{seg.end:.1f}] speaker {seg.speaker}: {seg.text}")

Step by step (long jobs, resuming later)

job = client.create_job("./recordings/*.wav", language_code="hi-IN")  # starts automatically
print(job.id)                      # keep this to resume
job.wait(timeout=3600, on_progress=lambda j: print(j.status, j.percent))

job = client.get_job("<job id>")   # e.g. after a restart
files = job.files()
job.save("./outputs", text_files=True)

language_code takes one code, several comma-separated (identified per speaker turn; the first is the fallback), or "auto". Other options: model, diarization, speakers (1-8), multi_channel, denoise, bias_words, bias_score, callback_url, start=False, and for model="prisma-v3.0" also format, keywords, topic and speaker_names (see Prisma v3.0).

Async

AsyncGnaniSTTBatchClient has the same methods, awaited. Transcripts are downloaded concurrently, so .text and .segments are plain attributes on what transcribe() returns (after job.files() call await f.load(), or pass load=True).

from gnani.stt import AsyncGnaniSTTBatchClient

client = AsyncGnaniSTTBatchClient()
result = await client.transcribe("./recordings/", language_code="hi-IN")
print(result[0].text)
await result.save("./outputs")

async for job in client.list_jobs(status="COMPLETED"):
    print(job.id)

wait() returns for COMPLETED and PARTIAL_FAILURE (check each BatchFile.ok) and raises BatchJobFailedError for FAILED, START_FAILED and CANCELLED, and BatchTimeoutError on timeout (the job keeps running). It polls every 10 s, the documented minimum.

Realtime Streaming Usage

Connection Flow

  1. Client opens a WebSocket connection to wss://api.vachana.ai/stt/v3/stream with auth headers.
  2. Server sends a connected event with the active configuration.
  3. Client sends binary PCM audio frames (1024 bytes each = 512 samples at 16-bit).
  4. Server detects speech via VAD and responds with processing and transcript events.
  5. Either side may close the connection at any time.

PCM Specification

All audio must be sent as raw PCM binary frames. No container format (WAV, MP3, etc.) is accepted mid-stream.

Property 16 kHz 8 kHz
Encoding PCM signed 16-bit little-endian PCM signed 16-bit little-endian
Sample Rate 16,000 Hz 8,000 Hz
Channels 1 (mono) 1 (mono)
Samples per chunk 512 512
Bytes per frame 1,024 bytes (512 samples × 2 bytes) 1,024 bytes (512 samples × 2 bytes)
Frame duration 32 ms 64 ms
  • Each binary frame must be exactly 1,024 bytes.
  • Frames must be sent at real-time cadence — one frame every 32 ms (16 kHz) or 64 ms (8 kHz). Do not buffer and burst; this degrades VAD accuracy.
  • For 44100 and 48000 Hz sources, the server resamples internally — still send 1,024-byte frames at the appropriate cadence.

For the full WebSocket protocol reference, see STT Realtime — PCM Specification.

Using the async context manager

import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async def main():
    async with GnaniSTTStreamClient(
        api_key="your-api-key",
        language_code="hi-IN",
        sample_rate=16000,
    ) as stream:
        print(f"Connected! Sample rate: {stream.connected_config.sample_rate}")

        with open("audio.pcm", "rb") as f:
            while chunk := f.read(1024):
                await stream.send_audio(chunk)
                await asyncio.sleep(0.032)

        async for event in stream:
            if isinstance(event, StreamTranscriptEvent):
                print(f"[{event.segment_index}] {event.text}")
                print(f"  Duration: {event.audio_duration_ms}ms, Latency: {event.latency}ms")

asyncio.run(main())

Manual connect / close

import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async def main():
    stream = GnaniSTTStreamClient(api_key="your-api-key")
    config = await stream.connect()
    print(f"Server ready: {config.message}")

    await stream.send_audio(audio_chunk)
    transcripts = await stream.close()

    for t in transcripts:
        print(t.text)

asyncio.run(main())

High-level stream_audio helper with callbacks

import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent, StreamProcessingEvent

async def main():
    async with GnaniSTTStreamClient(api_key="your-api-key") as stream:
        with open("audio.pcm", "rb") as f:
            transcripts = await stream.stream_audio(
                f,
                on_transcript=lambda t: print(f"Transcript: {t.text}"),
                on_processing=lambda p: print(f"Processing at {p.timestamp}..."),
                realtime_pace=True,
            )

    print(f"Total segments: {len(transcripts)}")

asyncio.run(main())

Number formatting (ITN) on streaming

format is sent as x-format. Leave it out for the server default (ITN on for hi-IN and en-IN, off for other languages), pass "verbatim" to switch ITN off, or "transcribe" to switch it on. enable_itn=True (x-enable-itn) turns ITN on without choosing a format, and itn_native_numerals=True (x-itn-native-numerals) writes digits in the native script whenever ITN runs — it does not turn ITN on by itself.

GnaniSTTStreamClient(language_code="hi-IN", format="verbatim")    # Hindi, ITN off
GnaniSTTStreamClient(language_code="ta-IN", enable_itn=True,      # Tamil, ITN on,
                     itn_native_numerals=True)                    # native digits

Tuning voice-activity detection (VAD)

The server cuts the audio into speech segments with VAD. Six options tune it. Each is sent as a connection header and is fixed for the life of the connection (to change one, reconnect). Leave an option out to keep the server default. Values outside the range raise ValueError when the client is created, before anything is sent.

Option Header Default Range What it does
vad_threshold x-vad-threshold 0.7 0.0–1.0 Speech-probability threshold. Higher rejects more noise but may miss soft speech.
min_silence_ms x-min-silence-ms 500 100–2000 Silence after speech before a segment is closed and transcribed. The main latency knob.
min_speech_ms x-min-speech-ms 100 (200 at 8 kHz) 50–2000 Speech needed before a segment opens. Raise it in noisy rooms.
min_segment_ms x-min-segment-ms 120 100–1000 Shorter segments are dropped without a transcript.
max_speech_s x-max-speech-s no limit 5.0–120.0 Longest a segment may run before it is cut.
idle_timeout_sec x-idle-timeout-sec 60 5–900 Seconds without speech before the server ends the session.
# Faster final transcripts on a clean line (may split a sentence at a pause)
GnaniSTTStreamClient(language_code="hi-IN", vad_threshold=0.5, min_silence_ms=300)

# Noisy call: stricter detection, longer pauses allowed, one-minute segment cap
GnaniSTTStreamClient(language_code="en-IN", sample_rate=8000,
                     vad_threshold=0.75, min_speech_ms=300, max_speech_s=60.0)

The ranges are available as gnani.stt.STREAM_TUNING_OPTIONS, and gnani.stt.validate_stream_tuning(name, value) checks one value.

Using 8 kHz audio

stream = GnaniSTTStreamClient(
    api_key="your-api-key",
    language_code="en-IN",
    sample_rate=8000,
)

Event Types

All events are typed dataclasses:

Event Fields Description
StreamConnectedEvent message, timestamp, sample_rate, chunk_size, raw Handshake confirmation with server config
StreamProcessingEvent timestamp, raw VAD detected end-of-speech, transcribing
StreamTranscriptEvent text, audio_duration_ms, segment_id, segment_index, latency, timestamp, raw, detected_language_code (prisma-v3.0 only) Completed transcription for a speech segment
StreamErrorEvent message, timestamp, raw Server-side error

Accessing the raw JSON payload

Every event includes a raw field with the full server JSON:

async for event in stream:
    print(event.raw)  # dict with the complete server response

Text-to-Speech Usage

Input text is normalized server-side; see the Text Normalization Guide for symbols, numbers, and abbreviations.

TTS Models

from gnani.tts import DEFAULT_MODEL, SUPPORTED_MODELS

print(DEFAULT_MODEL)              # timbre-v2.5
print(sorted(SUPPORTED_MODELS))   # timbre-v2.5, timbre-v3.0

TTS REST

from gnani.tts import GnaniTTSClient

client = GnaniTTSClient(api_key="your-api-key")
# Default audio_config uses sample_rate=48000
audio = client.synthesize("यह एक टेस्ट है", voice="Pranav", model="timbre-v2.5")
with open("tts_rest.wav", "wb") as f:
    f.write(audio)

TTS Streaming (SSE)

Lower latency than REST — audio is streamed via Server-Sent Events.

from gnani.tts import GnaniTTSStreamClient, AudioConfig

client = GnaniTTSStreamClient(api_key="your-api-key")

# synthesize() collects all chunks and returns audio matching audio_config
audio = client.synthesize(
    "Streaming TTS response",
    voice="Pranav",
    model="timbre-v2.5",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
    output_file="tts_sse.wav",
)

For chunk-by-chunk streaming (e.g. real-time playback), use synthesize_stream():

for audio_chunk in client.synthesize_stream("Hello!", voice="Pranav", model="timbre-v2.5"):
    play_audio(audio_chunk)  # format depends on audio_config (PCM, OGG, MP3, etc.)

TTS Realtime (WebSocket)

Lowest latency — audio is streamed over a persistent WebSocket connection.

import asyncio
from gnani.tts import GnaniTTSRealtimeClient, AudioConfig

async def main():
    async with GnaniTTSRealtimeClient(api_key="your-api-key") as client:
        # synthesize_and_collect() returns audio matching audio_config
        audio = await client.synthesize_and_collect(
            "Realtime TTS response",
            voice="Kaveri",
            model="timbre-v2.5",
            audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
            output_file="tts_realtime.wav",
        )

asyncio.run(main())

For chunk-by-chunk streaming (e.g. real-time playback):

async with GnaniTTSRealtimeClient(api_key="your-api-key") as client:
    async for audio_chunk in client.synthesize("Hello!", voice="Pranav", model="timbre-v2.5"):
        play_audio(audio_chunk)  # format depends on audio_config (PCM, OGG, MP3, etc.)

TTS language and speed (timbre-v2.5, timbre-v3.0)

from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")
audio = client.synthesize(
    "Hello, this is a Timbre test.",
    voice="Avinash",
    model="timbre-v3.0",
    language="en-IN",
    speed=1.2,                # timbre-v3.0: 0.8-1.2; omit to use the voice's own speed
    audio_config=AudioConfig(container="mp3", sample_rate=48000, bitrate="128k"),
)

The same model, language and speed parameters work on GnaniTTSStreamClient (SSE) and GnaniTTSRealtimeClient (WebSocket).

TTS Telephony Formats

For telephony integrations (IVR, SIP), use 8 kHz A-law or μ-law:

from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")

# A-law (G.711a) — common in European/Indian telephony
alaw_audio = client.synthesize(
    "Hello from Gnani",
    voice="Pranav",
    audio_config=AudioConfig(container="alaw", sample_rate=8000),
)

# μ-law (G.711u) — common in North American telephony
mulaw_audio = client.synthesize(
    "Hello from Gnani",
    voice="Pranav",
    audio_config=AudioConfig(container="mulaw", sample_rate=8000),
)

TTS OGG/Opus

Returns a playable OGG Opus file (OggS header). Use either form:

  • container="ogg" (encoding defaults to oggopus)
  • container="raw", encoding="oggopus"

Supported at all standard sample rates (8000–48000).

from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")

# Using container="ogg"
ogg_audio = client.synthesize(
    "Hello from Gnani",
    voice="Pranav",
    audio_config=AudioConfig(container="ogg", encoding="oggopus", sample_rate=48000),
)

with open("output.ogg", "wb") as f:
    f.write(ogg_audio)

SSE / WebSocket: OGG is delivered as one complete file in a single chunk (not streamable frame-by-frame). For chunk iteration, use synthesize_stream() (SSE) or async synthesize() (WebSocket) — the buffered synthesize() and synthesize_and_collect() methods correctly return the raw OGG bytes without WAV wrapping when using non-PCM encodings.

TTS Audio Format Matrix

Supported combinations of container, encoding, sample_rate, and bitrate:

Container Encoding Sample Rates Bitrate Notes
wav linear_pcm 8000, 16000, 22050, 24000, 44100, 48000 — Standard WAV (RIFF header)
mp3 linear_pcm 8000, 16000, 22050, 24000, 44100, 48000 32k, 64k, 96k, 128k, 192k All 5 bitrates supported
raw linear_pcm 8000, 16000, 22050, 24000, 44100, 48000 — Raw PCM, no header
ogg oggopus 8000, 16000, 22050, 24000, 44100, 48000 — Playable OGG Opus file
raw oggopus 8000, 16000, 22050, 24000, 44100, 48000 — Equivalent to ogg
mulaw linear_pcm 8000 — G.711μ telephony
alaw linear_pcm 8000 — G.711A telephony

Notes:

  • bitrate is only applicable to container="mp3". It is ignored for all other containers.
  • mulaw and alaw containers are telephony-only — they require sample_rate=8000.
  • For telephony, prefer container="alaw" / container="mulaw" over encoding="pcm_alaw" / encoding="pcm_mulaw".
  • container="ogg" and container="raw" with encoding="oggopus" are equivalent — both return a playable OGG Opus file.

File extensions: Match the output file extension to your audio_config.container — use .wav for WAV, .mp3 for MP3, .ogg for OGG/Opus, .raw for raw PCM, .alaw / .ulaw for telephony.

TTS Supported Constants

from gnani.tts import (
    SUPPORTED_ENCODINGS,     # {"linear_pcm", "oggopus", "pcm_mulaw", "pcm_alaw"}
    SUPPORTED_CONTAINERS,    # {"raw", "mp3", "wav", "ogg", "mulaw", "alaw"}
    SUPPORTED_BITRATES,      # {"32k", "64k", "96k", "128k", "192k"}
    SUPPORTED_SAMPLE_RATES,  # (8000, 16000, 22050, 24000, 44100, 48000)
    DEFAULT_SPEED,           # 1.0
    MIN_SPEED,               # 0.85  (the timbre-v2.5 range, kept for compatibility)
    MAX_SPEED,               # 1.15
    SPEED_RANGES,            # {"timbre-v2.5": (0.85, 1.15), "timbre-v3.0": (0.8, 1.2)}
)

TTS Voices

List voices for a specific model:

from gnani.tts import GnaniTTSClient, TIMBRE_V25_VOICES, TIMBRE_V30_VOICES

print(GnaniTTSClient.supported_voices())                    # 42 voices (timbre-v2.5, the default)
print(GnaniTTSClient.supported_voices(model="timbre-v3.0")) # 34 voices
print(len(TIMBRE_V25_VOICES), len(TIMBRE_V30_VOICES))       # 42 34

Each voice is valid for its own model only.

Audio Requirements

STT REST

Constraint Value
Formats WAV, MP3, FLAC, OGG, M4A
Max duration 60 seconds
Channels Mono or stereo
Sample rate Automatically converted to 16 kHz mono

STT Streaming (WebSocket)

Constraint Value
Encoding Raw PCM, signed 16-bit little-endian
Sample rate 16,000 Hz or 8,000 Hz
Channels 1 (mono)
Frame size 1,024 bytes (512 samples)
Pacing Send frames at real-time cadence for best VAD accuracy

See PCM Specification for full details.

Response Format

REST

{
  "success": true,
  "request_id": "req_abc123",
  "timestamp": "20251226_143052.123",
  "transcript": "नमस्ते, आप कैसे हैं?"
}

Realtime Streaming

Connected:

{
  "type": "connected",
  "message": "STT service ready — VAD service connected",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "config": { "sample_rate": 16000, "chunk_size": 512 }
}

Transcript:

{
  "type": "transcript",
  "timestamp": "2024-01-15T10:30:05.987Z",
  "text": "Hello, how are you today?",
  "audio_duration_ms": 2340,
  "segment_id": "<segment_id>",
  "segment_index": "<segment_index>",
  "latency": 320
}

Error Handling

from gnani.stt import (
    AuthenticationError,
    InvalidAudioError,
    APIError,
    StreamConnectionError,
    StreamClosedError,
    StreamError,
)

# REST errors
try:
    result = client.transcribe("audio.wav", language_code="hi-IN")
except AuthenticationError:
    print("Check your credentials")
except InvalidAudioError as e:
    print(f"Bad audio file: {e}")
except APIError as e:
    print(f"API error {e.status_code}: {e}")

# Streaming errors
try:
    async with GnaniSTTStreamClient(api_key="key") as stream:
        await stream.send_audio(chunk)
except StreamConnectionError as e:
    print(f"Connection failed: {e}")
except StreamClosedError as e:
    print(f"Stream already closed: {e}")
except StreamError as e:
    print(f"Server error: {e} (at {e.timestamp})")

TTS Errors

from gnani.tts import (
    GnaniTTSClient,
    GnaniTTSRealtimeClient,
    AuthenticationError,
    APIError,
    StreamConnectionError,
    StreamError,
)

# REST / SSE errors
try:
    audio = GnaniTTSClient(api_key="key").synthesize("Hello", voice="Pranav")
except AuthenticationError:
    print("Check your API key")
except APIError as e:
    print(f"TTS API error {e.status_code}: {e}")

# WebSocket errors
try:
    async with GnaniTTSRealtimeClient(api_key="key") as client:
        audio = await client.synthesize_and_collect("Hello", voice="Pranav")
except StreamConnectionError as e:
    print(f"WebSocket connection failed: {e}")
except StreamError as e:
    print(f"TTS stream error: {e}")

Documentation

Full API reference and guides are available at docs.gnani.ai.

License

This project is licensed under the MIT License -- see the LICENSE file for details.

Metadata

Release files for gnani-vachana 0.11.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gnani-vachana 0.11.0
File Size Uploaded Provenance Actions
gnani_vachana-0.11.0.tar.gz 63.3 kB With provenance Details for gnani_vachana-0.11.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gnani-vachana 0.11.0
File Interpreter ABI Platform Actions
gnani_vachana-0.11.0-py3-none-any.whl Python 3 none any Details for gnani_vachana-0.11.0-py3-none-any.whl

Total release size: 122.1 kB

Release files / gnani_vachana-0.11.0.tar.gz

Download URL gnani_vachana-0.11.0.tar.gz
Size 63.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b0f870724e3b0d5a506bb4b32c040a56b955151e228a6be7e24e9fd1825ade8e
BLAKE2b-256 checksum
How to use checksums
ff0dd89527e2765cb78f494077706df24d22d1ff6e0e9a4b90a8f4bd8389c27a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Release files / gnani_vachana-0.11.0-py3-none-any.whl

Download URL gnani_vachana-0.11.0-py3-none-any.whl
Size 58.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6ec7fea4dc08620534c5a4750afd97999b28c716633300cec5ea5afb5faf18db
BLAKE2b-256 checksum
How to use checksums
9ddf4f389ddc16fac8e3edb2e6c063fa52774a4cff51f2c6e5164d5b9eadb0c4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Security for gnani-vachana 0.11.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for gnani_vachana-0.11.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.11.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page