Skip to navigation

WebSocket Streaming API

View as Markdown

The WebSocket API keeps one connection open for many text-to-speech conversions. You send a config message, then text, and the server returns audio chunks as they are generated. It suits voice agents that stream text from an LLM and play audio back immediately.

URLwss://api.sarvam.ai/text-to-speech/ws?model=bulbul:v4-flash
AuthApi-Subscription-Key: <your key> header, or Authorization: Bearer <key>. In a browser, use the subprotocol api-subscription-key.<key>. A query parameter is rejected.
Max text2,500 characters per text message
Default outputMP3, 128k bitrate, 22,050 Hz
Audio messagesJSON with base64-encoded audio

If you do not need a persistent connection, the HTTP Streaming API is simpler. See Which API to use to compare.

For the full message schema, see the Text-to-Speech API Reference.

Quickstart

Set your API key as the SARVAM_API_KEY environment variable. These examples synthesize one sentence into output.mp3 and stop when the server sends the final completion event.

import asyncio
import base64
import os
from sarvamai import AsyncSarvamAI, AudioOutput, EventResponse
async def main():
client = AsyncSarvamAI(api_subscription_key=os.environ["SARVAM_API_KEY"])
async with client.text_to_speech_streaming.connect(
model="bulbul:v4-flash", send_completion_event=True
) as ws:
# The SDK names this target_language_code. It is sent as language_code.
await ws.configure(
target_language_code="hi-IN",
speaker="simran_en_customer",
output_audio_codec="mp3",
)
await ws.convert("भारत की संस्कृति विश्व की सबसे प्राचीन संस्कृतियों में से एक है।")
await ws.flush()
with open("output.mp3", "wb") as f:
async for message in ws:
if isinstance(message, AudioOutput):
f.write(base64.b64decode(message.data.audio))
elif isinstance(message, EventResponse) and message.data.event_type == "final":
break
asyncio.run(main())

Always pass speaker in the config. The Python SDK’s default speaker (anushka) is rejected by both current models. The completion event is off unless you set send_completion_event. Without it, the server sends audio only and keeps the socket open, so your code must decide when to stop.

Message flow

  1. Open the connection with the model and, optionally, send_completion_event query parameters. The model is set only in the URL: a model field inside the config message is ignored.
  2. Send a config message first. It must include language_code and speaker.
  3. Send one or more text messages. Audio chunks start arriving as the buffered text is synthesized.
  4. Send flush to synthesize any text still in the buffer.
  5. Read audio messages until the event message with event_type final (if enabled).
  6. Reuse the connection for the next utterance, or close it.

Messages you send

Sets voice and output options. Send it first. You can send a new config later in the session. Text still in the buffer is flushed with the old settings before the new ones apply.

{
"type": "config",
"data": {
"language_code": "hi-IN",
"speaker": "simran_en_customer",
"pace": 1.1,
"output_audio_codec": "mp3",
"min_buffer_size": 50,
"max_chunk_length": 150
}
}
FieldRequiredDefaultDescription
language_codeYesnoneBCP-47 code: hi-IN, bn-IN, ta-IN, te-IN, gu-IN, kn-IN, ml-IN, mr-IN, pa-IN, od-IN, en-IN
speakerYesnoneVoice that is valid for the connection’s model. See Voices.
paceNo1.0Speech speed, 0.5–2.0
pitchNo0.0Pitch shift, -0.5–0.5
loudnessNo1.0Volume multiplier, 0.1–2.5
temperatureNo0.6Expressiveness, 0.01–1.0
speech_sample_rateNo220508000, 16000, 22050 or 24000 Hz. Higher rates are REST only.
output_audio_codecNomp3mp3, wav, aac, flac, linear16, mulaw, alaw, opus
output_audio_bitrateNo128k32k, 64k, 96k, 128k, 192k
enable_preprocessingNofalseNormalize English words and numbers before synthesis
dict_idNononePronunciation dictionary ID
min_buffer_sizeNo50Characters to buffer before synthesis starts, 30–200
max_chunk_lengthNo150Maximum length of each sentence chunk, 50–500

opus fails at the default 22,050 Hz. Set speech_sample_rate to 8000, 16000 or 24000 when you use it.

Messages you receive

typeWhenShape
audioFor each chunk of audio{"type": "audio", "data": {"request_id": "...", "content_type": "audio/mpeg", "audio": "<base64>"}}
eventWhen synthesis finishes, if send_completion_event is enabled{"type": "event", "data": {"event_type": "final"}}
errorWhen a message is rejected{"type": "error", "data": {"request_id": "...", "message": "...", "code": 422}}

Decode each audio value from base64 and append the bytes to your file or player. The bytes are in the codec you configured, and content_type tells you which one (audio/mpeg for mp3, audio/wav for wav, audio/pcm for linear16, and so on).

Errors

Rejected messages come back in-band as JSON. The connection stays open unless the server closes it.

CodeCause
422Invalid pace, text longer than 2,500 characters, or a speaker that does not belong to the model
400Unsupported speech_sample_rate (streaming allows 8000, 16000, 22050, 24000 only)
408The connection was idle for 60 seconds and the server closed it with a normal close. Send ping to keep it open.
500The message was not valid JSON

An invalid key or exceeded rate limit rejects the connection before it opens (HTTP 403 or 429 on the upgrade request). See Errors & Troubleshooting and Credits & Rate Limits.

Handle disconnects

Close codeMeaningWhat to do
1000Normal closureYou called close(). Nothing to do.
1001Going awayThe server or client is shutting down. Reconnect.
1006Abnormal closure, no close frameNetwork drop. Reconnect with backoff.
1011Server errorRetry with backoff. If it persists, check status.
4xxxApplication-specificRead the close reason, for example auth or quota, and fix the cause before reconnecting.

Reconnect with exponential backoff and a small random jitter, resend the config message, then resume sending text. Do not blindly retry on 4xxx closes.

attempt = 0
while not connected and attempt < MAX_ATTEMPTS:
try: open WebSocket, send config, resume sending text; attempt = 0
except (close 1006 / 1011 / network error):
sleep(min(BASE * 2 ** attempt, MAX_DELAY) + jitter); attempt += 1
on close 4xxx: stop and surface the error

Voice agent barge-in

The TTS WebSocket has no server-side cancel message. The only client messages are config, text, flush and ping. Handle an interruption on the client:

  1. Stop playback and clear your local audio buffer when your STT detects speech_start.
  2. Close the TTS socket so the server stops generating. In-flight chunks are discarded on your side.
  3. Open a fresh connection for the agent’s next reply.
# In your STT speech_start handler:
tts_player.stop() # 1. stop and clear local playback immediately
await tts_ws.close() # 2. close the TTS socket to stop generation
# 3. open a new client.text_to_speech_streaming.connect(...) for the next turn

Send replies as several shorter text messages so an interruption discards less generated audio. See the STT WebSocket barge-in recipe and the LiveKit and Pipecat voice-agent guides.