tts_service
Base classes for Text-to-speech services.
- class pipecat.services.tts_service.TextAggregationMode(*values)[source]
Bases:
StrEnumControls how incoming text is aggregated before TTS synthesis.
- Parameters:
SENTENCE – Buffer text until sentence boundaries are detected before synthesis. Produces more natural speech but adds latency (~200-300ms per sentence).
TOKEN – Stream text tokens directly to TTS as they arrive. Reduces latency but may affect speech quality depending on the TTS provider.
- SENTENCE = 'sentence'
- TOKEN = 'token'
- class pipecat.services.tts_service.TTSContext(append_to_context: bool = True, push_assistant_aggregation: bool = False, interruptible: bool = True, spoken_expression: SpokenExpression = <factory>)[source]
Bases:
objectContext information for a TTS request.
- Parameters:
append_to_context – Whether this TTS output should be appended to the conversation context after it is spoken.
push_assistant_aggregation – Whether to push an
LLMAssistantPushAggregationFrameafter the TTS has finished speaking, forcing the assistant aggregator to commit its current text buffer to the conversation context.interruptible – Whether an interruption may discard this synthesis.
spoken_expression – The delivery and sounds of the words the service reports speaking in this context. Part of expressive conversation (alpha).
- class pipecat.services.tts_service.TTSService(*, text_aggregation_mode: TextAggregationMode | None = None, aggregate_sentences: bool | None = None, push_text_frames: bool = True, push_stop_frames: bool = False, push_start_frame: bool = False, stop_frame_timeout_s: float = 3.0, push_silence_after_stop: bool = False, silence_time_s: float = 2.0, pause_frame_processing: bool = False, pause_watchdog_timeout_s: float | None = None, max_consecutive_zero_audio_contexts: int = 3, append_trailing_space: bool = False, sample_rate: int | None = None, skip_text_types: list[str] | None = None, skip_aggregator_types: list[str] | None = None, text_transforms: list[tuple[TextType | str, Callable[[str, str | TextType], Awaitable[str]]]] | None = None, text_filters: Sequence[BaseTextFilter] | None = None, transport_destination: str | None = None, settings: TTSSettings | None = None, reuse_context_id_within_turn: bool = True, **kwargs)[source]
Bases:
AIServiceBase class for text-to-speech services.
Provides common functionality for TTS services including text aggregation, filtering, audio generation, and frame management. Supports configurable sentence aggregation, silence insertion, and frame processing control.
- Event handlers:
on_connected: Called when connected to the TTS service. on_disconnected: Called when disconnected from the TTS service. on_connection_error: Called when a connection to the TTS service error occurs. on_tts_request: Called before a TTS request is made, with the context ID and text.
Example:
@tts.event_handler("on_connected") async def on_connected(tts: TTSService): logger.debug(f"TTS connected") @tts.event_handler("on_disconnected") async def on_disconnected(tts: TTSService): logger.debug(f"TTS disconnected") @tts.event_handler("on_connection_error") async def on_connection_error(tts: TTSService, error: str): logger.error(f"TTS connection error: {error}") @tts.event_handler("on_tts_request") async def on_tts_request(tts: TTSService, context_id: str, text: str): logger.debug(f"TTS request: {context_id} - {text}")
- expression_adapter_class
alias of
BaseExpressionAdapter
- __init__(*, text_aggregation_mode: TextAggregationMode | None = None, aggregate_sentences: bool | None = None, push_text_frames: bool = True, push_stop_frames: bool = False, push_start_frame: bool = False, stop_frame_timeout_s: float = 3.0, push_silence_after_stop: bool = False, silence_time_s: float = 2.0, pause_frame_processing: bool = False, pause_watchdog_timeout_s: float | None = None, max_consecutive_zero_audio_contexts: int = 3, append_trailing_space: bool = False, sample_rate: int | None = None, skip_text_types: list[str] | None = None, skip_aggregator_types: list[str] | None = None, text_transforms: list[tuple[TextType | str, Callable[[str, str | TextType], Awaitable[str]]]] | None = None, text_filters: Sequence[BaseTextFilter] | None = None, transport_destination: str | None = None, settings: TTSSettings | None = None, reuse_context_id_within_turn: bool = True, **kwargs)[source]
Initialize the TTS service.
- Parameters:
text_aggregation_mode – How to aggregate incoming text before synthesis. TextAggregationMode.SENTENCE (default) buffers until sentence boundaries, TextAggregationMode.TOKEN streams tokens directly for lower latency.
aggregate_sentences –
Whether to aggregate text into sentences before synthesis.
Deprecated since version 0.0.104: Use
text_aggregation_modeinstead. Set toTextAggregationMode.SENTENCEto aggregate text into sentences before synthesis, orTextAggregationMode.TOKENto stream tokens directly for lower latency. Will be removed in 2.0.0.push_text_frames – Whether to push TextFrames and LLMFullResponseEndFrames.
push_stop_frames – Whether to automatically push TTSStoppedFrames.
push_start_frame – Whether to automatically create audio contexts and push TTSStartedFrames. When True, the base class handles
create_audio_contextand yieldsTTSStartedFramebefore each synthesis call, sorun_ttsimplementations do not need to.stop_frame_timeout_s – Idle time before pushing TTSStoppedFrame when push_stop_frames is True.
push_silence_after_stop – Whether to push silence audio after TTSStoppedFrame.
silence_time_s – Duration of silence to push when push_silence_after_stop is True.
pause_frame_processing – Whether to hold incoming frames after a turn until its audio contexts end. Needed by services whose audio doesn’t carry its request’s context ID.
pause_watchdog_timeout_s –
Unused.
Deprecated since version 1.8.0: No replacement. Frame processing is now paused only while an audio context is open, and every context ends, so no timer is needed to break the pause. Will be removed in 2.0.0.
max_consecutive_zero_audio_contexts – How many consecutive TTS contexts may complete without producing any audio before the service is reported unable to do its job. Catches a provider that accepts requests and stays silent — an unknown voice ID, say — which no error ever surfaces. Every silent context reports an error the service can carry on from, whatever the limit is; on reaching the limit the service reports a permanent error instead, stops being given work, and the pipeline worker applies its
ProcessorUnusablePolicy. Set to 0 to report silent contexts without ever writing the service off.append_trailing_space – Whether to append a trailing space to text before sending to TTS. This helps prevent some TTS services from vocalizing trailing punctuation (e.g., “dot”). Only applied in sentence aggregation mode; when streaming tokens, the incoming text’s own whitespace is preserved.
sample_rate – Output sample rate for generated audio.
skip_text_types – List of text types that should not be spoken.
skip_aggregator_types –
List of text types that should not be spoken.
Deprecated since version 1.13.0: Use
skip_text_typesinstead. Will be removed in 2.0.0.text_transforms – A list of TextTransforms to transform text before just before sending it to TTS. Each TextTransform takes the aggregated text and its type, and returns the transformed text. To register, provide a list of tuples of (text_type | ‘*’, transform_function).
text_filters –
Text filters run before the transforms.
Deprecated since version 1.14.0: Use
text_transformsinstead, withstrip_markdownin place ofMarkdownTextFilter. Will be removed in 2.0.0.transport_destination – Destination for generated audio frames.
settings – The runtime-updatable settings for the TTS service.
reuse_context_id_within_turn – Whether the service should reuse context IDs within the same turn.
**kwargs – Additional arguments passed to the parent AIService.
- property sample_rate: int
Get the current sample rate for audio output.
- Returns:
The sample rate in Hz.
- property chunk_size: int
Get the recommended chunk size for audio streaming.
This property indicates how much audio we download (from TTS services that require chunking) before we start pushing the first audio frame. This will make sure we download the rest of the audio while audio is being played without causing audio glitches (specially at the beginning). Of course, this will also depend on how fast the TTS service generates bytes.
- Returns:
The recommended chunk size in bytes.
- property text_aggregation_language: str
Current sentence tokenizer language, derived from TTS settings.
- property supports_processing_metrics: bool
Whether this service has a meaningful processing-time metric.
Processing time is measured around
run_tts(), so it only means something when synthesis finishes beforerun_ttsreturns. Services that hand the text off and receive audio elsewhere — anything holding a persistent connection with its own receive task — return False, since the measurement would cover the send and nothing else. TTFB and TTFA carry the latency for those.
- get_expression_adapter() BaseExpressionAdapter[source]
The adapter that formats this service’s expression tags.
Part of expressive conversation (alpha). Its capabilities are what the service can perform: what it broadcasts at start, and what it reads and formats. A service whose expression depends on its settings, such as its model, overrides this to choose an adapter for them.
- Returns:
An instance of
expression_adapter_class.
- property expression_settings: dict[str, Any]
Settings to send with the request being synthesized.
Part of expressive conversation (alpha). Set before each request from the service’s expression adapter (
request_settings()), for a service that takes some of its expression as request settings rather than as markup in its text.- Returns:
The settings, empty for none.
- service_metadata_frame() TTSMetadataFrame | None[source]
Build the TTS metadata frame broadcast at start.
Overrides
AIService.service_metadata_frame(). With expressive conversation on, aTTSMetadataFramecarries its expression adapter’s capabilities; otherwise nothing is broadcast.- Returns:
The metadata frame, or None when expressive conversation is off.
- async start_tts_usage_metrics(text: str)[source]
Record TTS usage metrics.
When streaming tokens, usage metrics are aggregated and reported at flush time instead of per token, so individual calls are skipped.
- Parameters:
text – The text being processed by TTS.
- async start_text_aggregation_metrics()[source]
Start text aggregation metrics if not already started.
Only starts the metric once per LLM response. Skipped when streaming tokens since per-token aggregation time is not meaningful.
- async stop_text_aggregation_metrics()[source]
Stop text aggregation metrics and reset the started flag.
- async set_model(model: str)[source]
Set the TTS model to use.
Deprecated since version 0.0.104: Use
TTSUpdateSettingsFrame(model=...)instead. Will be removed in 2.0.0.- Parameters:
model – The name of the TTS model.
- async set_voice(voice: str)[source]
Set the voice for speech synthesis.
Deprecated since version 0.0.104: Use
TTSUpdateSettingsFrame(voice=...)instead. Will be removed in 2.0.0.- Parameters:
voice – The voice identifier or name.
- async setup(setup: FrameProcessorSetup)[source]
Set up the service.
- Parameters:
setup – Configuration object containing setup parameters.
- async start(frame: StartFrame)[source]
Start the TTS service.
- Parameters:
frame – The start frame containing initialization parameters.
- async cancel(frame: CancelFrame)[source]
Cancel the TTS service.
- Parameters:
frame – The cancel frame.
- async set_usable(is_usable: bool)[source]
Set whether this service can be given work.
- Parameters:
is_usable – Whether the service can be given work.
- add_text_transformer(transform_function: Callable[[str, str | TextType], Awaitable[str]], text_type: TextType | str = '*', *, aggregation_type: TextType | str | None = None)[source]
Transform text of a specific type.
- Parameters:
transform_function – The function to apply for transformation. This function should take the text and its type as input and return the transformed text. Ex.: async def my_transform(text: str, text_type: str) -> str:
text_type – The type of text to transform. This value defaults to “*” indicating the function should handle all text before sending to TTS.
aggregation_type –
The type of text to transform.
Deprecated since version 1.13.0: Use
text_typeinstead. Will be removed in 2.0.0.
- remove_text_transformer(transform_function: Callable[[str, str | TextType], Awaitable[str]], text_type: TextType | str = '*', *, aggregation_type: TextType | str | None = None)[source]
Remove a text transformer for a specific text type.
- Parameters:
transform_function – The function to remove.
text_type – The type of text to remove the transformer for.
aggregation_type –
The type of text to remove the transformer for.
Deprecated since version 1.13.0: Use
text_typeinstead. Will be removed in 2.0.0.
- classmethod format_pronunciation(word: str, ipa: str) str | None[source]
Render a word’s pronunciation in this service’s markup.
Services that support pronunciation hints override this. The base implementation supports none.
- Parameters:
word – The word as it appears in the text.
ipa – How to pronounce it, in IPA.
- Returns:
The text to send in place of
word, or None when this service cannot use the pronunciation.
- property supports_pronunciations: bool
Whether this service reads pronunciation markup with its current settings.
Pronunciation transforms are skipped while this is False, so their words are spoken as written. Services whose markup depends on the model or on a setting override this; it is checked for every text sent, so it follows settings updates.
- Returns:
True in the base implementation.
- classmethod pronunciation_transform_ipa(pronunciations: Mapping[str, str]) PronunciationTransform[source]
Create a text transform that makes this service say words as IPA describes.
Each word is replaced with
format_pronunciation()output, so the same IPA works with any service that supports it. Words the service cannot use are reported once and spoken as written. While the service cannot read pronunciation markup at all (seesupports_pronunciations), the transform is skipped.Register this transform last in
text_transforms. Transforms run in order, and one that runs after it (stripping markdown or symbols, replacing text) can rewrite the markup it inserts, such as Cartesia’s<<…>>blocks or an SSML<phoneme>tag, and break the hint.- Parameters:
pronunciations – Word to IPA, e.g.
{"Metformin": "mɛtˈfɔɹmɪn"}.- Returns:
A transform to register with
text_transforms.
Example:
pronounce = CartesiaTTSService.pronunciation_transform_ipa( {"Metformin": "mɛtˈfɔɹmɪn"} ) tts = CartesiaTTSService( text_transforms=[ ("*", strip_markdown), ("*", expand_currency), ("*", pronounce), # last, so nothing rewrites its markup ], )
- abstractmethod async run_tts(text: str, context_id: str) AsyncGenerator[Frame | None, None][source]
Run text-to-speech synthesis on the provided text.
This method must be implemented by subclasses to provide actual TTS functionality. The base class logs the synthesized text before invoking this method, so implementations should not log it again.
- Parameters:
text – The text to synthesize into speech.
context_id – Unique identifier for this TTS context.
- Yields:
Frame – Audio frames containing the synthesized speech.
- language_to_service_language(language: Language) str | None[source]
Convert a language to the service-specific language format.
- Parameters:
language – The language to convert.
- Returns:
The service-specific language identifier. Return
Noneto indicate an unsupported language. This optional return is an extension hook for future or third-party subclasses; as of 2026-04-28, first-party services return a string.
- create_context_id() str[source]
Generate or reuse a context ID based on concurrent TTS support.
- Returns:
A context ID string for the TTS request.
- async flush_audio(context_id: str | None = None)[source]
Flush any buffered audio data.
- Parameters:
context_id – The specific context to flush. If None, falls back to the currently active context (for non-concurrent services).
- async tts_process_generator(context_id: str, generator: AsyncGenerator[Frame | None, None])[source]
Process frames from an async generator, routing them through the audio context.
All non-None frames yielded by the generator are appended to the audio context identified by context_id. The audio context must be created by run_tts (via create_audio_context) before the first frame is yielded.
WebSocket services yield None to signal that audio will arrive via a separate receive loop; those services manage context lifetime themselves (via remove_audio_context in the receive loop on “done”). HTTP services never yield None and do NOT call remove_audio_context in run_tts — on_turn_context_completed closes the context once the turn’s remaining frames (e.g. TTSTextFrame) are queued.
- Parameters:
context_id – The audio context to route frames to.
generator – An async generator yielding Frame objects or None.
- async on_turn_context_created(context_id: str)[source]
Called when a new turn context ID has been created.
Override to perform provider-specific setup (e.g., eagerly opening a server-side context) before text starts flowing. This is called from
process_framewhen anLLMFullResponseStartFrameorTTSSpeakFramearrives.- Parameters:
context_id – The newly created turn context ID.
- async on_audio_context_interrupted(context_id: str)[source]
Called when an audio context is cancelled due to an interruption.
Override this in a subclass to perform provider-specific cleanup (e.g. sending a cancel/close message over the WebSocket) when the bot is interrupted mid-speech. The context is still registered when this hook runs. Uninterruptible contexts continue playing and do not call this hook.
- Parameters:
context_id – The ID of the audio context that was interrupted.
- async on_audio_context_completed(context_id: str)[source]
Called after an audio context has finished playing all of its audio.
Override this in a subclass to perform provider-specific cleanup (e.g. sending a close-context message to free server-side resources) once an audio context has been fully processed. The context entry has already been removed from the internal context map, and the active context has not yet been reset when this is called.
- Parameters:
context_id – The ID of the audio context that finished processing.
- async add_word_timestamps(word_times: list[tuple[str, float]], context_id: str | None = None, includes_inter_frame_spaces: bool | None = None, pre_merge_tokens: bool = False)[source]
Add word timestamps for processing.
When an audio context exists for this context_id, timestamps are routed into the per-context audio queue alongside audio frames so they are processed in strict playback order by _handle_audio_context. Otherwise they are processed immediately via _add_word_timestamps.
- Parameters:
word_times – List of (word, timestamp) tuples where timestamp is in seconds.
context_id – Unique identifier for the TTS context.
includes_inter_frame_spaces – When True, each emitted TTSTextFrame carries
includes_inter_frame_spaces=Trueso downstream consumers do not inject extra spaces between consecutive frames (e.g. ElevenLabs for CJK languages where word tokens already self-contain their spacing). None leaves the frame’s own default unchanged.pre_merge_tokens – When True, punctuation and space-only tokens are merged into the preceding word via
merge_punct_tokensbefore queuing (e.g. Inworld TTS, which emits spaces and punctuation as separate tokens). After merging the resulting tokens are clean word strings, soincludes_inter_frame_spacesshould be left False (its default).
- async create_audio_context(context_id: str)[source]
Create a new audio context for grouping related audio.
- Parameters:
context_id – Unique identifier for the audio context.
- async append_to_audio_context(context_id: str | None, frame: Frame | WordTimestamp | None)[source]
Append a frame or word-timestamp entry to an existing audio context queue.
Passing a
frameofNonesignals end-of-context (used by remove_audio_context to mark the queue for deletion). If the context no longer exists but the context_id matches the active turn, the context is transparently recreated before appending.- Parameters:
context_id – The context to append to.
Noneis accepted as a no-op (with a debug log) so callers can pass through values fromget_active_audio_context_id()without an explicit guard.frame – The frame, word-timestamp entry, or
None(end-of-context sentinel) to append.
- async remove_audio_context(context_id: str | None)[source]
Remove an existing audio context.
- Parameters:
context_id – The context to remove.
Noneis accepted as a no-op (logged) so callers can pass through values fromget_active_audio_context_id()without an explicit guard.
- audio_context_available(context_id: str) bool[source]
Check whether the given audio context is registered.
- Parameters:
context_id – The context ID to check.
- Returns:
True if the context exists and is available.
- has_active_audio_context() bool[source]
Check if there is an active audio context.
- Returns:
True if an active audio context exists, False otherwise.
- get_active_audio_context_id() str | None[source]
Get the active audio context ID.
Returns the playback cursor when set (during active playback), falling back to the current turn’s synthesis context_id. The fallback covers the gap between contexts and the start of a turn before the playback task has dequeued the just-created context — important for services whose wire protocol does not echo context_id back on incoming audio.
- Returns:
The active context ID, or None if neither cursor is set.
- async process_frame(frame: Frame, direction: FrameDirection)[source]
Process frames for text-to-speech conversion.
Handles TextFrames for synthesis, interruption frames, settings updates, and various control frames.
- Parameters:
frame – The frame to process.
direction – The direction of frame processing.
- async push_frame(frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM)[source]
Push a frame downstream with TTS-specific handling.
- Parameters:
frame – The frame to push.
direction – The direction to push the frame.
- class pipecat.services.tts_service.WordTTSService(**kwargs)[source]
Bases:
TTSServiceDeprecated. Use TTSService directly instead.
Deprecated since version 0.0.105: Word timestamp functionality is now always active in TTSService. Will be removed in 2.0.0.
- class pipecat.services.tts_service.WebsocketTTSService(*, reconnect_on_error: bool = True, **kwargs)[source]
Bases:
TTSService,WebsocketServiceBase class for websocket-based TTS services.
Combines TTS functionality with websocket connectivity, providing automatic error handling and reconnection capabilities.
Includes an optional keepalive for providers that close an idle connection. A subclass enables it by overriding
_send_keepalive()to send its provider’s keepalive message, and calling_create_keepalive_task(interval)/_cancel_keepalive_task()from its_connect()/_disconnect().- Event handlers:
on_connection_error: Called when a websocket connection error occurs.
Example:
@tts.event_handler("on_connection_error") async def on_connection_error(tts: TTSService, error: str): logger.error(f"TTS connection error: {error}")
- __init__(*, reconnect_on_error: bool = True, **kwargs)[source]
Initialize the Websocket TTS service.
- Parameters:
reconnect_on_error – Whether to automatically reconnect on websocket errors.
**kwargs – Additional arguments passed to parent classes.
- property supports_processing_metrics: bool
Whether this service has a meaningful processing-time metric.
False:
run_ttssends the text and returns, and audio arrives later on the receive task, so there is no synthesis inside the measured window. A subclass that instead waits for the server to signal the end of synthesis before returning can override this back to True.
- async stop(frame: EndFrame)[source]
Stop the websocket TTS service on a graceful end.
- Parameters:
frame – The end frame.
- async cancel(frame: CancelFrame)[source]
Cancel the websocket TTS service immediately.
Disconnecting here is the prompt teardown: the websocket receive loop runs independently of the audio-context task, so it keeps reading from the provider until the socket is closed. Stopping only the audio-context task (in
TTSService.cancel()) halts output but not reception.- Parameters:
frame – The cancel frame.
- class pipecat.services.tts_service.InterruptibleTTSService(**kwargs)[source]
Bases:
WebsocketTTSServiceWebsocket-based TTS service that handles interruptions without word timestamps.
Designed for TTS services that don’t support word timestamps. Handles interruptions by reconnecting the websocket when the bot is speaking and gets interrupted.
- __init__(**kwargs)[source]
Initialize the Interruptible TTS service.
- Parameters:
**kwargs – Additional arguments passed to the parent WebsocketTTSService.
- async push_frame(frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM)[source]
Push a frame downstream with TTS-specific handling.
- Parameters:
frame – The frame to push.
direction – The direction to push the frame.
- async process_frame(frame: Frame, direction: FrameDirection)[source]
Process frames, tracking whether an interruption needs a reconnect.
- Parameters:
frame – The frame to process.
direction – The direction of frame processing.
- class pipecat.services.tts_service.WebsocketWordTTSService(**kwargs)[source]
Bases:
WebsocketTTSServiceDeprecated. Use WebsocketTTSService directly instead.
Deprecated since version 0.0.105: Word timestamp functionality is now always active in TTSService. Will be removed in 2.0.0.
- class pipecat.services.tts_service.InterruptibleWordTTSService(**kwargs)[source]
Bases:
InterruptibleTTSServiceDeprecated. Use InterruptibleTTSService directly instead.
Deprecated since version 0.0.105: Word timestamp functionality is now always active in TTSService. Will be removed in 2.0.0.
- class pipecat.services.tts_service.AudioContextTTSService(**kwargs)[source]
Bases:
WebsocketTTSServiceDeprecated. Inherit from WebsocketTTSService directly instead.
Audio context management (previously the main purpose of this class) is now built into TTSService. This class is kept only for backwards compatibility.
Deprecated since version 0.0.105: Subclass
WebsocketTTSServicedirectly and passreuse_context_id_within_turnas keyword arguments to its__init__. Will be removed in 2.0.0.- __init__(*, reuse_context_id_within_turn: bool = True, reconnect_on_error: bool = True, **kwargs)[source]
Initialize the Audio Context TTS service.
- Parameters:
reuse_context_id_within_turn – Whether the service should reuse context IDs within the same turn.
reconnect_on_error – Whether to automatically reconnect on websocket errors.
**kwargs – Additional arguments passed to the parent WebsocketTTSService.
- class pipecat.services.tts_service.AudioContextWordTTSService(**kwargs)[source]
Bases:
AudioContextTTSServiceDeprecated. Use WebsocketTTSService directly instead.
Deprecated since version 0.0.105: Subclass
WebsocketTTSServicedirectly. Will be removed in 2.0.0.