Skip to navigation

Pipecat Production Guide

View as Markdown

Pipecat Production Guide

A reference and tuning playbook for the Sarvam STT, TTS, and LLM plugins in Pipecat.

This page assumes you are writing Pipecat code. Every parameter, default, and code snippet was verified against source. Where a default is likely to hurt you in production, it is called out explicitly. New to Pipecat and Sarvam? Start with Build Your First Voice Agent using Pipecat first.

pip install "pipecat-ai[sarvam]>=1.14"

Scope. This guide covers SarvamRealtimeSTTService for STT (saaras:v3-realtime, the default, or saaras:v4) and bulbul:v4-flash (latest) / bulbul:v3 for TTS. Both ship in pipecat-ai[sarvam] (realtime STT since Pipecat 1.8.0, bulbul:v4-flash since 1.13.0). The older SarvamSTTService (saaras:v3 / saaras:v4) is documented in Section 11 for existing deployments.


Contents

  1. The defaults that cost you
  2. Pipeline architecture
  3. STT reference: SarvamRealtimeSTTService
  4. VAD and barge-in
  5. Turn management
  6. TTS reference: bulbul:v4-flash and v3
  7. Latency: budget and measurement
  8. Capturing request IDs (SarvamRealtimeSTTService + TTS)
  9. Reliability and error handling
  10. Sarvam LLM
  11. Legacy: SarvamSTTService
  12. Production tuning playbook

1. The defaults that cost you

Ranked by impact, except the last row: the LLM default can cost more than any of the others. Each is explained in full later.

#ParameterOwnerDefaultWhy it hurts
1user_turn_strategiesLLMUserAggregatorParamsNone: a local ML smart-turn modelNot a simple timeout. You get TurnAnalyzerUserTurnStopStrategy(LocalSmartTurnAnalyzerV3()), an ML model running inference locally every turn, keyed to Pipecat VAD frames. SarvamRealtimeSTTService with endpointing="vad" replaces this default with External strategies, and so does the legacy SarvamSTTService with vad_signals=True (Section 11)
2modelSarvamTTSService.Settingsbulbul:v3Set bulbul:v4-flash (latest) explicitly. Pipecat defaults to bulbul:v3, so without it you don’t get v4 Flash persona voices, pitch or loudness
3min_buffer_sizeSarvamTTSService.Settings50Sarvam buffers 50 characters server-side after Pipecat already aggregated a sentence: double buffering before the first audio byte
4stream_typeSarvamRealtimeSTTService.Settings"balanced"Picks Sarvam’s server-side flush profile; fast is the low-latency choice for conversational agents. The client always sends 50 ms chunks whatever you pick, so this setting does not change client-side buffering
5user_idle_timeoutLLMUserAggregatorParams0 (disabled)No dead-air recovery. A silent caller is never re-engaged
6user_turn_stop_timeoutLLMUserAggregatorParams5.0If no stop strategy fires, the turn hangs a full 5 s
7sample_rateSarvamTTSService(...)24000 for bulbul:v3 and bulbul:v4-flashMismatch forces per-chunk resampling. PipelineParams.audio_out_sample_rate does not fix this, see Section 6
8keepalive_timeoutSTT constructor argNone (disabled)A socket that gets no audio at all (STT muted, or on standby behind a ServiceSwitcher) can be dropped. Silence is still audio, so pauses in conversation don’t need it (Section 9)
9modelSarvamLLMService.Settingssarvam-105b, reasoning onGenerates reasoning tokens before every reply, often seconds before the first spoken word, and they count against max_tokens. reasoning_effort=None doesn’t turn it off; "none" does (Section 10)

Two things that look like configuration but are not:

  • Settings belong in settings=, and the services react differently when you get it wrong. SarvamRealtimeSTTService(api_key=..., stream_type="fast") raises a TypeError naming the field. SarvamTTSService(api_key=..., voice=...) and SarvamSTTService(api_key=..., language=...) construct fine and silently ignore the argument, so the agent runs on the default voice or language. Everything in the Settings tables must go through settings=.
  • ttfs_p99_latency is the reverse: a constructor argument, not a Settings field. Spelled ttfs_p99_latency (time to final segment), not p99_ttfs_latency.

2. Pipeline architecture

Frames flow through a chain of processors:

transport.input STT user aggregator LLM TTS transport.output assistant aggregator

With endpointing="vad" (the default), Sarvam’s realtime STT detects speech server-side and proposes the turn boundaries itself, as ProposedUserStartedSpeakingFrame and ProposedUserStoppedSpeakingFrame. The External turn strategies are the correct pairing, and the service asks the user aggregator for them automatically unless you pass your own user_turn_strategies. Passing them explicitly, as below, lets you tune the stop timeout. Barge-in is then set on the start strategy, because your strategies replace the ones should_interrupt configures (Section 4). There is no Pipecat VAD analyzer: Sarvam’s server-side VAD is enough (Section 4).

import os
from pipecat.observers.loggers.metrics_log_observer import MetricsLogObserver
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineParams, PipelineWorker, ProcessorUnusablePolicy
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import (
LLMContextAggregatorPair,
LLMUserAggregatorParams,
)
from pipecat.services.sarvam.llm import SarvamLLMService
from pipecat.services.sarvam.stt import SarvamRealtimeSTTService
from pipecat.services.sarvam.tts import SarvamTTSService
from pipecat.turns.user_start import ExternalUserTurnStartStrategy
from pipecat.turns.user_stop import ExternalUserTurnStopStrategy
from pipecat.turns.user_turn_strategies import UserTurnStrategies
from pipecat.workers.runner import WorkerRunner
async def run_bot(transport):
stt = SarvamRealtimeSTTService(
api_key=os.environ["SARVAM_API_KEY"],
endpointing="vad", # constructor argument: Sarvam's server-side VAD drives turns
sample_rate=16000, # 8000 or 16000; None adopts the pipeline's input rate
settings=SarvamRealtimeSTTService.Settings(
language="hi-IN", # None = detect per utterance
mode="transcribe",
stream_type="fast", # Sarvam's low-latency flush profile (default "balanced")
),
)
tts = SarvamTTSService(
api_key=os.environ["SARVAM_API_KEY"],
settings=SarvamTTSService.Settings(
model="bulbul:v4-flash", # must be set explicitly
voice="ishita_hi_devotional", # v4 persona; use v3 short names only with model="bulbul:v3"
language="hi-IN",
pace=1.0,
min_buffer_size=30, # default 50; 30 is the minimum Sarvam accepts
),
)
llm = SarvamLLMService(
api_key=os.environ["SARVAM_API_KEY"],
settings=SarvamLLMService.Settings(
model="sarvam-105b",
reasoning_effort="none", # no reasoning step, so replies start quickly (Section 10)
system_instruction="You are a helpful voice assistant. Keep replies short.",
),
)
context = LLMContext()
user_aggregator, assistant_aggregator = LLMContextAggregatorPair(
context,
user_params=LLMUserAggregatorParams(
user_turn_strategies=UserTurnStrategies(
# interrupts the bot on speech start; enable_interruptions=False turns that off
start=[ExternalUserTurnStartStrategy()],
stop=[ExternalUserTurnStopStrategy(timeout=0.2, wait_for_transcript=True)],
),
user_idle_timeout=12.0, # default 0, disabled
user_turn_stop_timeout=3.0,
),
)
pipeline = Pipeline([
transport.input(), stt, user_aggregator, llm, tts,
transport.output(), assistant_aggregator,
])
worker = PipelineWorker(
pipeline,
params=PipelineParams(enable_metrics=True, enable_usage_metrics=True),
observers=[MetricsLogObserver()],
processor_unusable_policy=ProcessorUnusablePolicy.END, # end the call if any service gives up, e.g. STT (Section 9)
)
runner = WorkerRunner()
await runner.add_workers(worker)
await runner.run()

transport is whichever Pipecat transport you use, for example from create_transport() in Pipecat’s runner.

Use the current API

Pipecat 1.3.0 renamed the top-level runnable unit from “pipeline task” to worker:

Deprecated (since 1.3.0)Use instead
from pipecat.pipeline.task import ...from pipecat.pipeline.worker import ...
PipelineTask(...)PipelineWorker(...)
PipelineRunner(...)WorkerRunner(...)

PipelineParams itself is not deprecated, only its old import path and PipelineTask.

allow_interruptions was removed from PipelineParams in Pipecat 1.0.0. PipelineParams ignores unknown fields, so passing it does nothing and raises no error. Interruption behavior comes from your turn-start strategy (Section 4).


3. STT reference: SarvamRealtimeSTTService

Streams raw audio to wss://api.sarvam.ai/speech-to-text-realtime/ws and maps Sarvam’s server-side VAD and transcript events into Pipecat frames. It serves two models, chosen with Settings(model=...): saaras:v3-realtime (the default, matching Sarvam’s own) and saaras:v4, which uses the same connection parameters and events. The v4 name has no -realtime suffix: saaras:v4-realtime, the legacy saaras:v3 and any other value raise ValueError at construction. The model is part of the connect query string, so set it when you build the service; changing it later does not switch the open connection.

Constructor arguments

All keyword-only.

ArgumentDefaultNotes
api_keyrequiredSent as the API-SUBSCRIPTION-KEY header
base_urlwss://api.sarvam.ai/speech-to-text-realtime/wsMust not already carry a query string
endpointing"vad"vad (Sarvam decides turn boundaries) or manual (the pipeline does). Fixed for the life of the service
sample_rateNone8000 or 16000 only. None adopts the pipeline’s input rate. Pipecat doesn’t resample STT input, so an explicit value must equal PipelineParams.audio_in_sample_rate
return_timestampsFalseAdds segment offsets to final transcripts
keytermsNoneRecognition hints for saaras:v4: up to 50 terms of 64 characters each, one phrase per item. Connection-time only
prefix_padding_msNoneAudio kept before detected onset. Used only with endpointing="vad"
settingsNoneCanonical config surface
should_interruptTrueSets enable_interruptions on the External strategies the service recommends. Has no effect if you pass your own user_turn_strategies (Section 4)
ttfs_p99_latency1.0 (SARVAM_REALTIME_TTFS_P99)Section 7

Inherited via **kwargs: reconnect_on_error (default True, with backoff: see Section 9), audio_passthrough (default True), stt_ttfb_timeout (default 2.0), keepalive_timeout (default None), keepalive_interval.

Setting sample_rate, endpointing, encoding or any other constructor-only value inside Settings(...) raises a TypeError. The audio encoding is fixed at linear16.

Settings fields

FieldDefaultAllowed valuesLive-updatable
model"saaras:v3-realtime"saaras:v3-realtime, saaras:v4No
languageLanguage.EN_INA Sarvam code such as "hi-IN" or a Language member; None detects per utteranceYes
stream_type"balanced"fast, balanced, simulatedYes
mode"transcribe"transcribe, translate, verbatim, translit, codemixYes
promptNonedecoding promptYes
thresholdNoneVAD sensitivity (endpointing="vad" only)Yes
silence_duration_msNoneend-of-speech silence (endpointing="vad" only)Yes
min_speech_duration_msNoneminimum speech to count (endpointing="vad" only)Yes

language_code is deprecated since Pipecat 1.13.0 and removed in 2.0.0: use language, with None in place of "auto".

Every field except model updates live. _update_settings sends a Sarvam config.update message over the open socket: no reconnect, no dropped audio. This is a real operational advantage over the legacy service, where changing the language tears down the WebSocket. Notably mode is in this set, so you can switch between transcribe and codemix mid-call. language, stream_type, mode and prompt take effect at the next utterance boundary. The constructor-only values (endpointing, sample_rate, return_timestamps, keyterms, prefix_padding_ms) are fixed for the life of the service. There is also a public update_config(**fields) method if you want to push a config change directly. Optional parameters are sent on the connect query string only when not None; leaving one unset means the Sarvam server default applies.

Modes:

ModeOutput
transcribeTranscription in the spoken language (default)
translateTranslated to English
verbatimIncludes fillers and disfluencies
translitRoman-script output
codemixOptimized for code-mixed / Hinglish speech

Language. language takes a Sarvam code such as "hi-IN" or "or-IN" (Odia is or-IN here, not od-IN as on the legacy service and TTS), or a Language member for an Indian locale. The realtime endpoint covers 23 languages plus detection. With language=None, each transcript frame’s language is the language Sarvam detected for that message (the raw code is also on result["language"]); it is None only if Sarvam reports none. A value Sarvam rejects (an unknown language or model) is a permanent invalid-request error, not a retry.

Frames it emits:

Sarvam eventPipecat result
session.begincaptures request_id (logged at INFO)
vad.speech_start (endpointing="vad")ProposedUserStartedSpeakingFrame broadcast; the External start strategy turns it into the turn start and the interruption if should_interrupt
vad.speech_end (endpointing="vad")ProposedUserStoppedSpeakingFrame broadcast
transcript.partialInterimTranscriptionFrame
transcript.finalTranscriptionFrame(finalized=True), preceded by an STT usage metric for the audio since the last final
session.endcloses any utterance still open
errornon-fatal ErrorFrame (Section 9)

Two of these matter most for turn-taking, and both improve on the legacy service: interim transcripts exist, so use_interim on turn strategies genuinely works, and finals carry finalized=True, which short-circuits Pipecat’s STT safety-net timer. The service emits Proposed* frames rather than the VADUser* variants, so strategies keyed to VADUser* frames never see Sarvam’s boundaries. That is why Section 2 uses the External strategies. With endpointing="manual" the direction reverses: the service sends speech_start and speech_end to Sarvam when the pipeline’s VADUserStartedSpeakingFrame and VADUserStoppedSpeakingFrame arrive, so you need a VAD analyzer on the user aggregator.

Audio always goes out as linear16, in 50 ms chunks, so mulaw or alaw telephony audio has to be decoded to PCM before it reaches this service.


4. VAD and barge-in

Sarvam runs its own VAD server-side, exposed through endpointing and four tuning parameters. With endpointing="vad" (the default) that VAD alone decides turn boundaries, so do not let a Pipecat VAD drive turns as well: two independent VADs disagreeing about the same audio is the failure to avoid, and Silero is not tuned for Indian acoustic conditions: background fans, traffic, and short acknowledgements like “haan” or “achha”. Keep the External turn strategies from Section 2 and tune the server-side parameters instead.

Don’t add a Pipecat VAD analyzer such as Silero under vad. Sarvam’s VAD already detects speech, and an analyzer can only get in the way. While it reports the user as speaking, Pipecat’s turn controller won’t end the turn, so noise, a breath or echo of the bot after Sarvam’s speech_end holds the turn open. In a simulated noisy run that cost about 0.8 s, and Pipecat 1.15 also lets an analyzer’s speech start clear a stop decision already made. On clean audio, turns end at the same time with or without one. The only thing you give up is the STT TTFB metric, which Pipecat times from the analyzer’s VADUserStoppedSpeakingFrame. Pipecat’s docstring calls an analyzer required in both modes, but under vad that metric is all it does. Under manual you do need one: its frames are the turn boundaries.

If you add an analyzer anyway, the turn strategies decide whether it drives turns:

External strategies (recommended)VAD-keyed strategies (VADUserTurnStart, SpeechTimeout, TurnAnalyzer)
Who detects speechSarvam, tuned for Indian audioSilero, general-purpose
ttfs_p99_latencyinertadds up to ttfs_p99_latency minus stop_secs per turn
Barge-in controlthe start strategy plus Sarvam’s server parametersthe start strategy plus Silero’s parameters

endpointing="manual" means the pipeline signals turn boundaries itself, through VADUserStartedSpeakingFrame and VADUserStoppedSpeakingFrame from a VAD analyzer; without a turn strategy that emits them, Sarvam never gets a boundary and never produces a final transcript. Do not choose it unless you are driving turns externally.

Barge-in

The STT service never interrupts the bot itself. On vad.speech_start it only broadcasts ProposedUserStartedSpeakingFrame; the turn-start strategy that accepts it is what cuts the bot’s audio. So barge-in is set on the start strategy:

  • Strategies left unset. The service recommends ExternalUserTurnStrategies(enable_interruptions=should_interrupt). With should_interrupt=True (the default), every vad.speech_start interrupts the bot: lowest-latency barge-in, with sensitivity governed entirely by the server-side parameters below. should_interrupt=False starts the turn without interrupting.
  • Strategies passed explicitly, as in Section 2. They replace the recommended ones, so should_interrupt does nothing. Set ExternalUserTurnStartStrategy(enable_interruptions=False) instead, or use a start strategy that waits for words.

To require several words before the bot yields, make MinWordsUserTurnStartStrategy the start strategy:

user_params = LLMUserAggregatorParams(
user_turn_strategies=UserTurnStrategies(
start=[MinWordsUserTurnStartStrategy(min_words=3, use_interim=True)],
stop=[ExternalUserTurnStopStrategy(timeout=0.2)],
),
)

Because the realtime service emits interim transcripts, use_interim=True lets that decision land early rather than waiting for the final transcript. This is the configuration to reach for when false interruptions from “haan” or “achha” are the main complaint. should_interrupt is a constructor argument and cannot be changed at runtime.

Server-side VAD parameters. All default to None (use the Sarvam server default) and are sent only when set.

ParameterControlsTuning for noisy Indian environmentsLive-updatable
thresholdVAD sensitivity: probability above which audio counts as speechRaise to reject fans, traffic, TVYes
silence_duration_msSilence needed to declare end of speechLower for snappier turns, raise for speakers who pause mid-sentenceYes
min_speech_duration_msMinimum speech duration to count as a turnRaise to reject clicks, coughs, door slams: the main dial against false barge-inYes
prefix_padding_msAudio retained before detected onsetRaise if first syllables are clippedNo

Because threshold, silence_duration_ms, and min_speech_duration_ms all update live, you can tune them mid-call without dropping the connection.


5. Turn management

The default is an ML model, not a timeout

If you pass no user_turn_strategies, you get:

start = [VADUserTurnStartStrategy(), TranscriptionUserTurnStartStrategy()]
stop = [TurnAnalyzerUserTurnStopStrategy(turn_analyzer=LocalSmartTurnAnalyzerV3())]

That is a local ML smart-turn model running inference on every turn, and both defaults key off VADUser* frames, not the Proposed* frames Sarvam’s server-side VAD produces. SarvamRealtimeSTTService with endpointing="vad" asks for External strategies itself, so leaving user_turn_strategies unset is safe. Pass strategies explicitly to make the choice, and the stop timeout, visible in your code. When you do, set barge-in on the start strategy, not with should_interrupt (Section 4).

With Sarvam, the strategies that matter are ExternalUserTurnStartStrategy and ExternalUserTurnStopStrategy (in pipecat.turns.user_start and pipecat.turns.user_stop), and MinWordsUserTurnStartStrategy for word-gated barge-in. Pipecat has others, but the VAD-keyed ones work against Sarvam’s server-side VAD. One container is worth knowing: FilterIncompleteUserTurnStrategies makes the LLM the end-of-turn gate, for users who pause mid-sentence a lot. It starts from Pipecat’s VAD-keyed defaults and replaces the External strategies the service recommends, so pass start=[ExternalUserTurnStartStrategy()] and stop=[ExternalUserTurnStopStrategy()] to it explicitly.

ExternalUserTurnStopStrategy, the recommended stop strategy, takes timeout (default 0.5, a short delay to coalesce consecutive speech segments) and wait_for_transcript (default True, require a transcript before ending the turn). Drop timeout to 0.2 to 0.3 for snappier turns, since Sarvam’s server-side endpointing has already decided speech ended.

Strategy order matters: first match wins. The controller iterates start strategies and stops at the first one that claims the turn; once a turn is open, later strategies are no-ops. This is the default. Pipecat 1.15 adds UserTurnStrategiesParams, whose start_mode and merge modes can change it; with those changed, first-match and “your strategies replace should_interrupt” no longer hold.

# WRONG: min_words is dead code. External claims the turn on speech-start,
# before any transcript exists.
start=[ExternalUserTurnStartStrategy(), MinWordsUserTurnStartStrategy(min_words=3)]
# RIGHT: pick one. External for lowest latency, or MinWords alone to gate on words.
start=[MinWordsUserTurnStartStrategy(min_words=3, use_interim=True)]

This is a silent failure: the pipeline looks configured for backchannel suppression and provides none.

MinWordsUserTurnStartStrategy. min_words is required with no default; use_interim defaults True and works here because the realtime service emits interim transcripts. The threshold is asymmetric, and that is the point:

min_words = self._min_words if self._bot_speaking else 1

While the bot is speaking, the user needs min_words words to take the turn (“haan”, “okay”, “achha” do not); while the bot is silent, a single word takes the turn immediately, so the agent stays responsive. Transcripts below the threshold call trigger_reset_aggregation(), discarding accumulated text. Use it as the only start strategy (Section 4). An ExternalUserTurnStartStrategy ahead of it would claim the turn, and interrupt the bot, on speech start, before any words are counted.

Idle and safety timeouts:

ParameterDefaultRecommendation
user_idle_timeout0 (disabled)8 to 15 s
user_turn_stop_timeout5.02.5 to 3.0, fires on_user_turn_stop_timeout
audio_idle_timeout1.0Forces speech-stop when audio stops arriving mid-speech. Only applies with a vad_analyzer on the user aggregator; leave as is

user_idle_timeout is narrower than the name suggests: the timer is anchored to BotStoppedSpeakingFrame, fires once per bot turn, is cancelled by function calls in progress, and only emits an on_user_turn_idle event. It does not re-prompt the LLM; your handler must. Adjustable at runtime with UserIdleTimeoutUpdateFrame(timeout=...); 0 cancels.

Do not set audio_passthrough=False on the STT service. Anything downstream that needs raw audio, a smart-turn analyzer or an aggregator VAD, only receives it because the STT passes it through.


6. TTS reference: bulbul:v4-flash and v3

Two services: SarvamTTSService streams over WebSocket, so audio flows before the sentence finishes synthesizing; use this for conversational agents. SarvamHttpTTSService does one HTTP round trip per utterance with the whole audio at once, so time to first audio is the full synthesis time; fine for batch or fixed IVR prompts, too slow for live conversation.

bulbul:v4-flash (latest) and bulbul:v3 properties: Pipecat always sends a concrete speech_sample_rate: 24000 Hz for both models unless you pass sample_rate= on the constructor. pace is 0.5 to 2.0, and preprocessing is always enabled. Pipecat enforces both only when the service is built: a runtime Settings(pace=3.0) update is sent as 3.0, and a runtime enable_preprocessing=False is sent as-is. bulbul:v4-flash needs pipecat-ai 1.13.0 or later.

bulbul:v4-flashbulbul:v3
Voicespersona IDs such as simran_en_customershort names such as shubh, priya
Default voice when omittedshubh_en_narration_gentleshubh
pitch (-0.5 to 0.5) and loudness (0.1 to 2.5)sent when setnot sent by Pipecat
temperature (0.01 to 1.0; Sarvam’s default 0.6)ignored by the model, so Pipecat never sends itsent only when you set it

At construction Pipecat clamps pace but not pitch or loudness: an out-of-range value reaches the API and comes back as an error.

bulbul:v4-flash: 200+ persona IDs such as simran_en_customer, ishita_hi_devotional, gokul_ta_narration: full list in the Voices guide.

bulbul:v3: short names such as shubh, priya, anand (30+ speakers).

Set model="bulbul:v4-flash" explicitly for new agents. Pipecat’s service default is bulbul:v3, which changes the voice set and supported parameters.

Pipecat doesn’t validate voices against the model. A v3 short name with bulbul:v4-flash (or the reverse) is accepted locally and fails on the Sarvam API with a 400 that lists the valid speakers. get_speakers_for_model("bulbul:v3") returns Pipecat’s own v3 enum, which isn’t Sarvam’s list: it lacks anand and includes amelia and sophia. It returns an empty list for bulbul:v4-flash, because Pipecat doesn’t bundle that model’s speakers. Pick v4 IDs from the Voices guide.

pace outside 0.5 to 2.0 is clamped, with a warning, when the service is built. Runtime updates aren’t clamped.

Latency-relevant settings:

FieldDefaultEffect
min_buffer_size50Characters Sarvam buffers server-side before emitting audio. Stacks on Pipecat’s own sentence aggregation. The minimum is 30: Sarvam rejects smaller values with a validation error and synthesizes nothing
max_chunk_length150Max characters per synthesis chunk
pace1.0Speaking rate
temperatureNone (Sarvam applies 0.6)bulbul:v3 only (ignored by bulbul:v4-flash). Voice variation; lower is more consistent. SarvamHttpTTSService always sends it, as 0.6 when unset, and likewise sends pitch 0.0 and loudness 1.0 on the models that take them

Because Pipecat aggregates a sentence and then Sarvam waits for min_buffer_size characters, the default double-buffers before the first audio byte; on short replies (“Ji, bilkul”) the server-side buffer dominates. The service requests send_completion_event=true, so TTSStoppedFrame fires as soon as synthesis finishes rather than waiting on an idle timer. A keepalive ping is sent every 20 s.

from pipecat.frames.frames import TTSUpdateSettingsFrame
await worker.queue_frame(
TTSUpdateSettingsFrame(delta=SarvamTTSService.Settings(voice="simran_en_customer"))
)

Always use delta= with a typed Settings object. The dict form is deprecated since 0.0.104. Up to pipecat-ai 1.15, {"voice_id": ...} and {"speaker": ...} on SarvamTTSService don’t change the voice, even though Pipecat logs the field as updated; a fix is merged for the next release.

Any settings change resends the config message to Sarvam. Changing model at runtime also works: SarvamTTSService reconnects, because the model is pinned in the WebSocket URL, and the voice resets to the new model’s default unless the same delta sets voice. Send a voice in the same update, or you get the new model’s default voice.

PipelineParams.audio_out_sample_rate does not affect Sarvam TTS. The service always passes a concrete sample rate from the constructor (or its plugin default), so the pipeline value is never consulted. To change output rate, pass sample_rate= on SarvamTTSService(...). Align it with your transport (8000 for telephony, 16000/24000 for WebRTC).

Set it to match your transport, or every chunk is resampled in-process (CPU and jitter cost). Telephony is typically 8000 Hz.

Pipecat can’t request mu-law from Sarvam TTS. SarvamTTSService asks for linear16 PCM, and output_audio_codec is neither a constructor argument nor a Settings field. The deprecated params=InputParams(output_audio_codec=...) only applies when you don’t pass settings, and Pipecat still treats the audio as PCM, so don’t use it. Request sample_rate=8000 and let your telephony serializer encode mu-law. STT is the same: the realtime service sends linear16 only (Section 3).


7. Latency: budget and measurement

Where the time goes:

stream_type ExternalUserTurnStopStrategy.timeout,silence_duration_ms model, prompt size,context length text_aggregation_mode min_buffer_size, model sample_rate alignment,transport Speech First byte on the wire Speech end / turn end First LLM token Text handed to TTS First audio byte User hears it

stream_type is a server-side flush profile. It selects how Sarvam flushes audio into transcripts: fast (lowest-latency partials), balanced (the default) or simulated (no partials, only the final transcript per utterance). The client sends audio in fixed 50 ms chunks whatever you choose, so it adds no client-side hold of its own. Use fast for conversational agents.

Enabling metrics:

PipelineParams(enable_metrics=True, enable_usage_metrics=True)

Metrics arrive as MetricsFrame carrying typed objects: TTFBMetricsData (value, seconds), TTFAMetricsData (ttfa, leading_silence, time to first audio), ProcessingMetricsData (value), LLMUsageMetricsData (value: LLMTokenUsage, prompt/completion/total/cache/reasoning), STTUsageMetricsData (value, audio seconds), TTSUsageMetricsData (value, characters), TextAggregationMetricsData (the “text handed to TTS” step in the diagram above), and TurnMetricsData (is_complete, probability, e2e_processing_time_ms, from turn analyzers only, so not on the External setup in Section 2). STT TTFB is timed from a Pipecat VAD analyzer’s VADUserStoppedSpeakingFrame, so the Section 2 setup, which has no analyzer, doesn’t report it.

from pipecat.observers.loggers.metrics_log_observer import MetricsLogObserver
from pipecat.observers.loggers.transcription_log_observer import TranscriptionLogObserver
observers=[MetricsLogObserver(), TranscriptionLogObserver()]

Narrow it with MetricsLogObserver(include_metrics={TTFBMetricsData, LLMUsageMetricsData}). Realtime STT usage is counted locally from the audio sent and reported once per final transcript, with a last flush when the service stops, so reconcile it against Sarvam’s billing rather than treating it as authoritative. It counts every audio frame the service receives, including audio dropped while the socket is down, so it over-counts during outages.

ttfs_p99_latency. This value tells turn-stop strategies how long to wait for a final transcript. The SpeechTimeout and TurnAnalyzer stop strategies read it after a VADUserStoppedSpeakingFrame from a Pipecat VAD analyzer. TurnAnalyzer, the default stop strategy, also reads it with no VAD at all: it waits that long after each transcript before ending the turn (Section 11). Pipecat 1.15’s ClassifierUserTurnStopStrategy reads it too. The External strategies in Section 2 ignore it, so it is inert there whether or not you add an analyzer. With a VAD-keyed strategy and an analyzer, it costs up to max(0, ttfs_p99_latency - stop_secs) per turn. A finalized transcript arriving sooner ends the wait early.

The default is SARVAM_REALTIME_TTFS_P99 = 1.0, which Pipecat marks as provisional until it is benchmarked against the realtime endpoint. The legacy SarvamSTTService uses SARVAM_TTFS_P99 = 1.17, measured with VAD stop_secs=0.2.

If you use those strategies, don’t trust the shipped default as-is: measure your own value against your traffic with the stt-benchmark tool, and treat Sarvam’s mode choice (transcribe, codemix, verbatim, and so on) as one of the variables worth benchmarking, since they are not equally fast. Pass whatever you measure at construction:

SarvamRealtimeSTTService(api_key=..., ttfs_p99_latency=...)

Do not pass ttfs_p99_latency=None to “disable” it; that selects DEFAULT_TTFS_P99 = 1.0.

stt_ttfb_timeout (default 2.0) is easy to confuse with this. It only affects what gets reported as STT TTFB, not how long turn-taking waits.


8. Capturing STT and TTS request IDs

Every Sarvam session has a request_id. Capture it alongside your own turn identifier for debugging and for raising issues with Sarvam support.

The STT observer in this section is for SarvamRealtimeSTTService only. It filters on that class, so on SarvamSTTService it logs nothing. The legacy service nests the ID: see Section 11.

STT: on every frame (SarvamRealtimeSTTService)

SarvamRealtimeSTTService captures request_id from Sarvam’s session.begin event and attaches it to every interim and final transcript frame’s result (the shape is flat: frame.result["request_id"]), and logs it once per session at INFO. On SarvamSTTService the ID is at frame.result["data"]["request_id"] instead (Section 11), so change both the isinstance filter and the lookup.

Because the ID comes from session.begin, it identifies the WebSocket session, not an individual utterance; after a reconnect you get a new one, which makes it a useful correlation key for diagnosing mid-call reconnections.

On realtime frames only, result.get("language") is the language Sarvam reported, and final transcripts additionally carry speech_end_audio_position_s for aligning against a recording. Neither field exists on legacy SarvamSTTService frames; language there is frame.language (Section 11). Filter isinstance(data.source, SarvamRealtimeSTTService) so you do not scrape Daily/DTMF TranscriptionFrames from other processors.

from loguru import logger
from pipecat.frames.frames import TranscriptionFrame
from pipecat.observers.base_observer import BaseObserver, FramePushed
from pipecat.services.sarvam.stt import SarvamRealtimeSTTService
class SarvamRequestIdObserver(BaseObserver):
async def on_push_frame(self, data: FramePushed):
if not isinstance(data.source, SarvamRealtimeSTTService):
return
frame = data.frame
if not isinstance(frame, TranscriptionFrame):
return
result = frame.result or {}
logger.info("sarvam.stt request_id={} lang={} text={!r}",
result.get("request_id"), result.get("language"), frame.text)

Add it to observers=[...] on your worker and ship those lines to your log store.

TTS: only in a trace log

SarvamTTSService reads a per-request request_id off each audio message but only writes it to a TRACE-level log line (TTS request_id=<id>, context_id=<id>); it is not attached to any frame, so an observer cannot see it. To capture it, add a loguru sink scoped to that module, since a process-wide TRACE level would be unusably verbose:

import re
from loguru import logger
_TTS_ID = re.compile(r"TTS request_id=(?P<request_id>\S+?), context_id=(?P<context_id>\S+)")
def capture_tts_request_id(message):
match = _TTS_ID.search(message.record["message"])
if match:
logger.bind(sarvam_tts=True).info("sarvam.tts {}", match.groupdict())
logger.add(capture_tts_request_id, level="TRACE", filter="pipecat.services.sarvam.tts")

The trace line is written once per audio chunk, not once per request, so expect repeats; deduplicate on request_id. context_id is Pipecat’s audio-context id, one per LLM response rather than per sentence, also carried on TTSAudioRawFrame.context_id. That gives you a join key: observe TTSAudioRawFrame to map a context_id to a conversation turn, then use the sink to map the same context_id to Sarvam’s request_id.


9. Reliability and error handling

The realtime service is materially more robust than the legacy one, but a few behaviors need handling.

Reconnection. With the default reconnect_on_error=True, a dropped socket is reopened in the background with backoff. Audio that arrives while the socket is down is not transcribed, and an utterance cut off by the drop ends with its last partial transcript; speech that continues on the new connection is transcribed as a new utterance.

The service stops and is no longer usable when any of these happens:

  • three connections in a row each close within 5 s of opening, whether or not session.begin arrived;
  • three reconnect attempts in one cycle fail;
  • a permanent error: a close rejecting its settings, or a 401/403 at the handshake. This stops it at once, with no retries;
  • the first drop, if you pass reconnect_on_error=False.

By default the pipeline keeps running without STT, so decide what happens next: end the call with PipelineWorker(processor_unusable_policy=ProcessorUnusablePolicy.END) (as in Section 2), or fail over with a ServiceSwitcher.

In-flight audio is not replayed on the new connection. Expect a gap in the transcript, not a silent hang.

A new request_id is issued on a reconnected session (Section 8), which is how you detect this happened in your logs.

Rejected settings are permanent. When Sarvam closes the connection because it rejects a connection parameter (an unknown model or language, or a VAD value it won’t accept), the service reports a permanent invalid-request error rather than retrying, since a retry would fail the same way. An error event from Sarvam is pushed as a non-fatal ErrorFrame.

on_connection_error fires when a reconnect attempt fails at the handshake, and again when the service gives up, so one outage can fire it several times. Don’t end the call there. Log it, and act on on_usable_changed, which fires once the service gives up:

@stt.event_handler("on_connection_error")
async def on_stt_connection_error(service, error):
logger.warning("Sarvam realtime STT connection error: {}", error)
@stt.event_handler("on_usable_changed")
async def on_stt_usable_changed(service, usable):
if not usable:
logger.error("Sarvam realtime STT gave up reconnecting")
# Escalate: end the call, fail over, or hand off to a human.

Invalid API key. The WebSocket handshake succeeds. Sarvam then sends an error event ("code": "invalid_subscription_key", "status_code": 401), which Pipecat pushes as a non-fatal ErrorFrame, and closes the socket with code 1003. Pipecat treats the close as a dropped connection and retries. After three connections that fail straight away, the service becomes unusable. Check ErrorFrame text for invalid_subscription_key to tell a bad key from a network problem. Sarvam also uses 1003 for rate and quota limits.

Keepalive. keepalive_timeout is None (disabled) by default. It matters only when no audio reaches STT at all, for example while STT is muted or on standby behind a ServiceSwitcher. Silence from the transport is still audio, so a long pause in the conversation doesn’t need it. The realtime service answers it with Sarvam’s ping event rather than silent audio, so it does not depend on the audio format.


10. Sarvam LLM

SarvamLLMService is OpenAI-compatible. It defaults to sarvam-105b and calls Sarvam’s /v2 chat API for it. The endpoint is chosen from the model when the service is built, and so is the check that rejects retired model names: a runtime model switch keeps the original endpoint and isn’t checked.

Turn off reasoning for voice

sarvam-105b has thinking mode on by default, so it generates reasoning tokens before the first word of the reply. In a voice agent the caller hears nothing until reasoning finishes. The reasoning also counts against max_tokens, so a low limit can leave the spoken reply empty. In testing, the default sarvam-105b with max_tokens=200 returned an empty reply: 199 of the 200 tokens went to reasoning.

The default Settings(reasoning_effort=None) doesn’t turn it off. In Pipecat, None means “don’t send the field”, so Sarvam’s default applies. Send the string "none" instead:

import os
from pipecat.services.sarvam.llm import SarvamLLMService
llm = SarvamLLMService(
api_key=os.environ["SARVAM_API_KEY"],
settings=SarvamLLMService.Settings(
model="sarvam-105b",
reasoning_effort="none", # turns thinking off
),
)

Through pipecat-ai 1.14 with a short Hinglish question, this took the first spoken token from 8.9 s to 0.3 s, with 0 reasoning tokens. Pipecat’s type hint for reasoning_effort lists only "low", "medium" and "high", so a type checker flags "none", but the service sends the value as-is. "none" is accepted on /v2, which is where Pipecat sends sarvam-105b; Sarvam’s /v1 API rejects it.

To check the change worked, look at reasoning_tokens in LLMUsageMetricsData (Section 7). It should read 0.

Model names. For voice, use sarvam-105b with reasoning_effort="none". SarvamLLMService rejects retired names (sarvam-30b, sarvam-30b-16k, sarvam-105b-32k, sarvam-m) with a ValueError, so update older configs that use them.

Request fields

The service removes stream_options, max_completion_tokens, and service_tier from every request. It does this after merging extra, so extra can’t put them back. extra is passed to the OpenAI client as keyword arguments, so it only takes parameters the OpenAI SDK knows: any other key fails every request with AsyncCompletions.create() got an unexpected keyword argument. Put Sarvam-only fields under extra={"extra_body": {...}}. In practice:

  • Set the reply length with max_tokens. max_completion_tokens is dropped without a warning.
  • Token usage still arrives. Sarvam sends a usage chunk at the end of the stream without stream_options, so LLMUsageMetricsData works as usual.

Prompt for speech

For voice, the system prompt is a latency parameter as much as a quality one: long replies delay first audio and give users more to interrupt.

system_instruction=(
"Respond in natural spoken language. Never use markdown, bullet points, or emoji. "
"Keep replies to one or two sentences. "
"Reply in the same language the user speaks, including Hinglish."
)

Three things this buys you: markdown and emoji sound terrible read aloud, language matching makes code-mixed conversation feel natural, and short replies cut perceived latency directly.


11. Legacy: SarvamSTTService

SarvamSTTService (saaras:v3 / saaras:v4) is the previous generation. It remains in pipecat-ai[sarvam] for existing deployments. New work should target SarvamRealtimeSTTService (saaras:v3-realtime or saaras:v4, Section 3).

Why migrate:

SarvamSTTService (legacy)SarvamRealtimeSTTService
Reconnect on errorNone, see below (silent failure)Automatic, with backoff (Section 9)
Interim transcriptsNeverYes
finalized=True on finalsYes (one transcript per utterance)Yes
Barge-in controlTurn-start strategy onlyTurn-start strategy, or should_interrupt on the recommended strategies
Runtime config changesReconnect requiredLive config.update for every field except model
mode changesInit-onlyRuntime-updatable
Input encodingwavlinear16
Rejected settingsReported non-fatallyPermanent invalid-request error, no retry

The failure mode that ends calls silently. SarvamSTTService has no automatic recovery from a WebSocket failure. _connect() catches connection errors, reports them non-fatally, and leaves the socket None; run_stt() then begins with if not self._socket_client: return, so every audio frame is discarded from that point on. Nothing retries: STTService’s _do_reconnect() hook is a no-op by default and this service does not override it. The result: the call stays up, the user keeps talking, and the agent never hears another word. If the connect failed, nothing more is reported. If the socket drops mid-call, the SDK swallows the error and the socket client stays set, so every audio chunk then produces an Error sending audio to Sarvam: … ErrorFrame. This service never fires on_connection_error, so a handler for it never runs. Handle on_error instead. It fires for every error the service reports, so match the connect and send failures, act once, and rebuild or end the call. If STT can go without audio for long stretches (muted, or on standby), set keepalive_timeout so the idle socket isn’t dropped in the first place.

STT_DEAD = ("Failed to connect to Sarvam", "Sarvam API error", "Error sending audio to Sarvam")
@stt.event_handler("on_error")
async def on_stt_error(service, error):
logger.error("Sarvam STT error: {}", error.error)
if error.error.startswith(STT_DEAD):
... # once per call: rebuild the service, end the call, or hand off to a human

Configuration. vad_signals is a Settings field, not a constructor argument; passing it to the constructor is silently ignored. Set vad_signals=True to use Sarvam’s server-side VAD, and add no Pipecat VAD.

With vad_signals unset and no VAD analyzer, Pipecat sends flush_signal=true at connect and never calls flush(), because nothing produces the VADUserStoppedSpeakingFrame that triggers it. Sarvam still returns a transcript at the end of each utterance, but Pipecat gets no speaking frames and the service doesn’t recommend External strategies, so the default strategies apply. Nothing starts the turn until the final transcript arrives, so barge-in waits for it too. The default TurnAnalyzer stop strategy then falls back to waiting ttfs_p99_latency (1.17 s) after the transcript before it ends the turn. In a live test with a Hindi clip, the turn started 7.1 s in, against 2.2 s with vad_signals=True, and ended about 1.2 s after the final transcript. Set vad_signals=True.

With vad_signals=True the service broadcasts ProposedUserStartedSpeakingFrame and ProposedUserStoppedSpeakingFrame on Sarvam’s speech events and recommends ExternalUserTurnStrategies, as the realtime service does. The turn-start strategy decides barge-in: the recommended External strategies interrupt on every speech-start, and a MinWordsUserTurnStartStrategy you pass yourself can gate it on words (Section 4). Server-side sensitivity is set by ten fine-grained VAD parameters (positive_speech_threshold, negative_speech_threshold, min_speech_frames, first_turn_min_speech_frames, negative_frames_count, negative_frames_window, start_speech_volume_threshold, interrupt_min_speech_frames, pre_speech_pad_frames, num_initial_ignored_frames). Of these, interrupt_min_speech_frames is the barge-in dial. All are None by default, sent only when set, and changing any one reconnects the socket.

mode is a constructor argument and init-only. SarvamSTTService has no should_interrupt; passing it is silently ignored, like any other unknown keyword argument.

The turn-end wait. SarvamSTTService emits one transcript per utterance and marks it finalized=True, so the STT safety net in SpeechTimeoutUserTurnStopStrategy short-circuits as soon as it arrives. Its ttfs_p99_latency default of 1.17 is the upper bound on how long a Pipecat-VAD-armed strategy waits for it (1.17 - 0.2 = 0.97 s after a stop_secs=0.2 VAD stop). With vad_signals=True and the External strategies, that wait does not arise.

Language. Auto-detect is the string "unknown", which is also the default for both saaras:v3 and saaras:v4. When Sarvam returns no language_code, returns "unknown", or returns a code Pipecat has no Language mapping for, frame.language is None (an unmapped code logs a warning once). Pin language if you branch on TranscriptionFrame.language. Language on the frame is frame.language, not result.get("language").

Request IDs. The service sets result=message.dict() on each transcript frame, and that dict carries Sarvam’s response under data. The ID is at frame.result["data"]["request_id"], next to language_probability and the server-side metrics. Language on the frame is frame.language (None when unset or unmapped).

Do not mix the two shapes in one snippet. Realtime (SarvamRealtimeSTTService, Section 8) is flat result["request_id"] (the session id from session.begin). Legacy is nested: result["data"]["request_id"].


12. Production tuning playbook

Work in this order. Fixing them out of order produces misleading measurements.

  1. Turn on metrics. PipelineParams(enable_metrics=True, enable_usage_metrics=True) plus MetricsLogObserver(). The biggest wins here are inaudible until you measure them.
  2. Check the turn strategies. With endpointing="vad" the service already selects the External strategies. Pass your own only to tune the stop timeout or gate on words (Section 2), and remember that yours replace should_interrupt.
  3. Keep Sarvam in charge of turns. Keep endpointing="vad" and the External strategies, and don’t add a Pipecat VAD analyzer (Section 4). This also keeps ttfs_p99_latency inert.
  4. Decide the barge-in model. Interrupt on speech start for lowest-latency barge-in (the default), or make MinWordsUserTurnStartStrategy(min_words=2..3, use_interim=True) the start strategy when false interruptions from acknowledgements are the complaint (Section 4).
  5. Tune endpointing. Lower silence_duration_ms first: it was the biggest lever in testing, where 500 ms cut end-of-turn from 1.85 s to 1.31 s after speech end. Raise min_speech_duration_ms until coughs and clicks stop triggering turns, and threshold against background noise. These three update live, so you can iterate mid-call. Lower ExternalUserTurnStopStrategy.timeout toward 0.2 as well; it’s fixed when the strategy is built.
  6. Cut time-to-first-audio. Set TTS model="bulbul:v4-flash" (or v3) explicitly, set min_buffer_size no lower than 30 (the minimum Sarvam accepts), and align TTS sample_rate with the transport on the constructor. Keep STT stream_type="fast".
  7. Set the safety nets. user_idle_timeout 8 to 15 s with a re-prompt handler, user_turn_stop_timeout 2.5 to 3.0, and keepalive_timeout if STT can sit muted or idle for long stretches.
  8. Handle STT connection failures (Section 9) before launch, not after the first mid-call outage. Set processor_unusable_policy on the worker, or fail over with a ServiceSwitcher, so a dead STT ends the call instead of leaving it silent.
  9. Cut LLM time-to-first-token (Section 10). Set reasoning_effort="none" on sarvam-105b. Then prompt for speech: short, plain replies in the caller’s language.