Pipecat Production Guide
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.
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
- The defaults that cost you
- Pipeline architecture
- STT reference: SarvamRealtimeSTTService
- VAD and barge-in
- Turn management
- TTS reference: bulbul:v4-flash and v3
- Latency: budget and measurement
- Capturing request IDs (SarvamRealtimeSTTService + TTS)
- Reliability and error handling
- Sarvam LLM
- Legacy: SarvamSTTService
- 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.
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 aTypeErrornaming the field.SarvamTTSService(api_key=..., voice=...)andSarvamSTTService(api_key=..., language=...)construct fine and silently ignore the argument, so the agent runs on the default voice or language. Everything in theSettingstables must go throughsettings=. ttfs_p99_latencyis the reverse: a constructor argument, not aSettingsfield. Spelledttfs_p99_latency(time to final segment), notp99_ttfs_latency.
2. Pipeline architecture
Frames flow through a chain of processors:
Recommended setup
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).
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:
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.
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
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:
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:
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:
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). Withshould_interrupt=True(the default), everyvad.speech_startinterrupts the bot: lowest-latency barge-in, with sensitivity governed entirely by the server-side parameters below.should_interrupt=Falsestarts the turn without interrupting. - Strategies passed explicitly, as in Section 2. They replace the recommended ones, so
should_interruptdoes nothing. SetExternalUserTurnStartStrategy(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:
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.
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:
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.
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:
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:
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.
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:
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.
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 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:
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.
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:
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.
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:
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.beginarrived; - 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:
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:
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_tokensis dropped without a warning. - Token usage still arrives. Sarvam sends a usage chunk at the end of the stream without
stream_options, soLLMUsageMetricsDataworks 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.
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:
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.
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.
- Turn on metrics.
PipelineParams(enable_metrics=True, enable_usage_metrics=True)plusMetricsLogObserver(). The biggest wins here are inaudible until you measure them. - Check the turn strategies. With
endpointing="vad"the service already selects the External strategies. Pass your own only to tune the stoptimeoutor gate on words (Section 2), and remember that yours replaceshould_interrupt. - 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 keepsttfs_p99_latencyinert. - 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). - Tune endpointing. Lower
silence_duration_msfirst: 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. Raisemin_speech_duration_msuntil coughs and clicks stop triggering turns, andthresholdagainst background noise. These three update live, so you can iterate mid-call. LowerExternalUserTurnStopStrategy.timeouttoward 0.2 as well; it’s fixed when the strategy is built. - Cut time-to-first-audio. Set TTS
model="bulbul:v4-flash"(or v3) explicitly, setmin_buffer_sizeno lower than 30 (the minimum Sarvam accepts), and align TTSsample_ratewith the transport on the constructor. Keep STTstream_type="fast". - Set the safety nets.
user_idle_timeout8 to 15 s with a re-prompt handler,user_turn_stop_timeout2.5 to 3.0, andkeepalive_timeoutif STT can sit muted or idle for long stretches. - Handle STT connection failures (Section 9) before launch, not after the first mid-call outage. Set
processor_unusable_policyon the worker, or fail over with aServiceSwitcher, so a dead STT ends the call instead of leaving it silent. - Cut LLM time-to-first-token (Section 10). Set
reasoning_effort="none"onsarvam-105b. Then prompt for speech: short, plain replies in the caller’s language.