Module livekit.agents.inference.tts

Classes

class AssemblyaiOptions (*args, **kwargs)
Expand source code
class AssemblyaiOptions(TypedDict, total=False):
    """AssemblyAI TTS options passed through to LiveKit Inference."""

    word_timestamps: bool  # default True; word timings are forwarded as an aligned transcript

AssemblyAI TTS options passed through to LiveKit Inference.

Ancestors

  • builtins.dict

Class variables

var word_timestamps : bool
class CartesiaOptions (*args, **kwargs)
Expand source code
class CartesiaOptions(TypedDict, total=False):
    emotion: str
    speed: Literal["slow", "normal", "fast"] | float
    volume: float
    duration: float
    max_buffer_delay_ms: int
    add_timestamps: bool
    add_phoneme_timestamps: bool
    use_normalized_timestamps: bool

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Ancestors

  • builtins.dict

Class variables

var add_phoneme_timestamps : bool
var add_timestamps : bool
var duration : float
var emotion : str
var max_buffer_delay_ms : int
var speed : Literal['slow', 'normal', 'fast'] | float
var use_normalized_timestamps : bool
var volume : float
class DeepgramOptions (*args, **kwargs)
Expand source code
class DeepgramOptions(TypedDict, total=False):
    mip_opt_out: bool  # always True for LiveKit Inference; the passed value is ignored

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Ancestors

  • builtins.dict

Class variables

var mip_opt_out : bool
class FallbackActivatedEvent (**data: Any)
Expand source code
class FallbackActivatedEvent(BaseModel):
    """A fallback model produced content-bearing synthesis output."""

    session_id: str
    fallback_type: FallbackType
    provider: str
    model: str
    voice: str
    cause: FallbackCause

A fallback model produced content-bearing synthesis output.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Ancestors

  • pydantic.main.BaseModel

Class variables

var cause : Literal['unknown', 'timeout', 'provider_error', 'quota_exceeded']
var fallback_type : Literal['unknown', 'fallback', 'system_default']
var model : str
var model_config
var provider : str
var session_id : str
var voice : str
class FallbackModel (*args, **kwargs)
Expand source code
class FallbackModel(TypedDict):
    """Inference Fallback Adapter: configuration for a fallback TTS model that runs server-side in LiveKit Inference, providing automatic fallback between providers.

    Options in ``extra_kwargs`` are passed through to the provider.

    Example:
        >>> FallbackModel(model="cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc")
    """

    model: str
    """Model name (e.g. "cartesia/sonic-3", "inworld/inworld-tts-2", "rime/coda")."""

    voice: str
    """Voice to use for the model. An empty string selects the model's default voice."""

    extra_kwargs: NotRequired[dict[str, Any]]
    """Extra configuration for the model."""

Inference Fallback Adapter: configuration for a fallback TTS model that runs server-side in LiveKit Inference, providing automatic fallback between providers.

Options in extra_kwargs are passed through to the provider.

Example

>>> FallbackModel(model="cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc")

Ancestors

  • builtins.dict

Class variables

var extra_kwargs : dict[str, typing.Any]

Extra configuration for the model.

var model : str

Model name (e.g. "cartesia/sonic-3", "inworld/inworld-tts-2", "rime/coda").

var voice : str

Voice to use for the model. An empty string selects the model's default voice.

class FishAudioOptions (*args, **kwargs)
Expand source code
class FishAudioOptions(TypedDict, total=False):
    """See https://docs.fish.audio/api-reference/endpoint/websocket/tts-live"""

    speed: float  # prosody speaking-rate multiplier, 1.0 is natural
    volume: float  # prosody loudness adjustment in dB, 0 is natural
    normalize_loudness: bool  # consistent output loudness; S2-Pro family only
    temperature: float  # range 0-1, higher is more varied/expressive
    top_p: float  # nucleus sampling probability mass, range 0-1
    normalize: bool  # normalize numbers/dates/abbreviations before synthesis
    latency: Literal["normal", "balanced", "low"]  # streaming latency mode
    chunk_length: int  # characters buffered before auto-synthesis, range 100-300
    max_new_tokens: int  # max audio tokens per text chunk, default 1024
    min_chunk_length: int  # min characters before splitting a new chunk, range 0-100
    condition_on_previous_chunks: bool  # use prior audio as context for consistency
    early_stop_threshold: float  # early-stopping threshold for batching, range 0-1

Ancestors

  • builtins.dict

Class variables

var chunk_length : int
var condition_on_previous_chunks : bool
var early_stop_threshold : float
var latency : Literal['normal', 'balanced', 'low']
var max_new_tokens : int
var min_chunk_length : int
var normalize : bool
var normalize_loudness : bool
var speed : float
var temperature : float
var top_p : float
var volume : float
class GoogleOptions (*args, **kwargs)
Expand source code
class GoogleOptions(TypedDict, total=False):
    """See https://ai.google.dev/gemini-api/docs/speech-generation#controllable"""

    style: str  # natural-language delivery direction, e.g. "calm and warm"; up to 1000 chars

Ancestors

  • builtins.dict

Class variables

var style : str
class InworldOptions (*args, **kwargs)
Expand source code
class InworldOptions(TypedDict, total=False):
    speaking_rate: float  # range >0.5, <=1.5
    temperature: float  # range 0-2
    # inworld-tts-2 only; temperature is ignored on that model, use this to steer variation
    delivery_mode: Literal["DELIVERY_MODE_UNSPECIFIED", "STABLE", "BALANCED", "CREATIVE"]
    timestamp_type: Literal["TIMESTAMP_TYPE_UNSPECIFIED", "WORD", "CHARACTER"]
    apply_text_normalization: Literal["APPLY_TEXT_NORMALIZATION_UNSPECIFIED", "ON", "OFF"]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Ancestors

  • builtins.dict

Class variables

var apply_text_normalization : Literal['APPLY_TEXT_NORMALIZATION_UNSPECIFIED', 'ON', 'OFF']
var delivery_mode : Literal['DELIVERY_MODE_UNSPECIFIED', 'STABLE', 'BALANCED', 'CREATIVE']
var speaking_rate : float
var temperature : float
var timestamp_type : Literal['TIMESTAMP_TYPE_UNSPECIFIED', 'WORD', 'CHARACTER']
class RimeOptions (*args, **kwargs)
Expand source code
class RimeOptions(TypedDict, total=False):
    """Rime-specific WebSocket JSON query parameters.
    See: https://docs.rime.ai/api-reference/endpoint/websockets-json
    """

    speed_alpha: float  # default 1.0, <1 = faster, >1 = slower
    pause_between_brackets: bool  # default False
    phonemize_between_brackets: bool  # default False
    inline_speed_alpha: str  # comma-separated speed factors for [bracketed] words
    no_text_normalization: bool  # default False

Rime-specific WebSocket JSON query parameters. See: https://docs.rime.ai/api-reference/endpoint/websockets-json

Ancestors

  • builtins.dict

Class variables

var inline_speed_alpha : str
var no_text_normalization : bool
var pause_between_brackets : bool
var phonemize_between_brackets : bool
var speed_alpha : float
class SynthesizeStream (*,
tts: TTS,
conn_options: APIConnectOptions)
Expand source code
class SynthesizeStream(tts.SynthesizeStream):
    """Streamed API using websockets"""

    def __init__(self, *, tts: TTS, conn_options: APIConnectOptions):
        super().__init__(tts=tts, conn_options=conn_options)
        self._tts: TTS = tts

        self._opts = replace(tts._opts)
        # Snapshot whether expressive is active now, while the framework holds it
        # fixed for this synthesis (set synchronously before stream()). Reading it
        # lazily in _run would race with the next turn/session mutating the shared
        # TTS instance.
        self._expressive = tts._expressive
        # alignment arrives finer-grained than a cue, so drop_bracket_cues parks the tail
        # of an unclosed span here between messages
        self._held_tokens: list[TimedString] = []
        # lower for the model this stream sends, not whatever update_options picks
        # mid-utterance (fishaudio s2.1-pro and drama-3 lower differently)
        self._markup_key = tts.markup._provider_key()

    async def _run(self, output_emitter: tts.AudioEmitter) -> None:
        request_id = ""

        from .. import tokenize
        from ..tts._provider_format import convert_markup, normalize_markup, sentence_tokenizer

        provider = self._opts.model.split("/")[0]
        text_stream: tokenize.WordStream | tokenize.SentenceStream
        if provider == "gradium" and not self._expressive:
            text_stream = tokenize.BufferedWordStream(
                tokenizer=_split_plain_words, min_token_len=1, min_ctx_len=1
            )
        else:
            text_stream = sentence_tokenizer(provider, expressive=self._expressive).stream()
        input_sent_event = asyncio.Event()

        async def _input_task() -> None:
            async for data in self._input_ch:
                if isinstance(data, self._FlushSentinel):
                    text_stream.flush()
                    continue
                text_stream.push_text(normalize_markup(self._markup_key, data))

            text_stream.end_input()

        async def _send_text_task(ws: aiohttp.ClientWebSocketResponse) -> None:
            base_pkt: dict[str, Any] = {}
            base_pkt["type"] = "input_transcript"
            async for ev in text_stream:
                # Re-normalize the emitted text: tags split across input chunks
                # aren't caught by the per-chunk normalize in _input_task
                normalized = normalize_markup(self._markup_key, ev.token)
                converted = convert_markup(self._markup_key, normalized)
                extra = self._opts.extra_kwargs if self._opts.extra_kwargs else {}
                packets = (
                    _gemini_packets(converted, extra)
                    if self._markup_key == "gemini"
                    else [(converted, extra)]
                )
                for transcript, packet_extra in packets:
                    token_pkt = base_pkt.copy()
                    token_pkt["transcript"] = transcript + " "
                    generation_config: dict[str, Any] = {}
                    if self._opts.voice:
                        generation_config["voice"] = self._opts.voice
                    if self._opts.model:
                        generation_config["model"] = self._opts.model
                    if self._opts.language:
                        generation_config["language"] = self._opts.language
                    token_pkt["generation_config"] = generation_config
                    token_pkt["extra"] = packet_extra
                    self._mark_started()
                    payload = json.dumps(token_pkt)
                    await ws.send_str(payload)
                    input_sent_event.set()

            end_pkt = {
                "type": "session.flush",
            }
            flush_payload = json.dumps(end_pkt)
            await ws.send_str(flush_payload)
            # needed in case empty input is sent
            input_sent_event.set()

        async def _recv_task(connection: _TTSConnection) -> None:
            current_session_id: str | None = None
            await input_sent_event.wait()

            while True:
                msg = await connection.receive(timeout=self._conn_options.timeout)
                if msg.type in (
                    aiohttp.WSMsgType.CLOSED,
                    aiohttp.WSMsgType.CLOSE,
                    aiohttp.WSMsgType.CLOSING,
                ):
                    raise APIStatusError(
                        "Gateway connection closed unexpectedly", request_id=request_id
                    )

                if msg.type == aiohttp.WSMsgType.ERROR:
                    raise APIConnectionError("Gateway connection lost") from (
                        msg.data if isinstance(msg.data, BaseException) else None
                    )

                if msg.type != aiohttp.WSMsgType.TEXT:
                    logger.warning("unexpected Gateway message type %s", msg.type)
                    continue

                data: dict[str, Any] = json.loads(msg.data)
                session_id = data.get("session_id")
                if current_session_id is None and session_id is not None:
                    current_session_id = session_id
                    output_emitter.start_segment(segment_id=session_id)

                msg_type = data.get("type")
                if msg_type == "session.created":
                    pass
                elif msg_type == "fallback_activated":
                    try:
                        event = FallbackActivatedEvent(
                            session_id=data.get("session_id"),
                            fallback_type=_normalize_fallback_type(data.get("fallback_type")),
                            provider=data.get("provider"),
                            model=data.get("model"),
                            voice=data.get("voice"),
                            cause=_normalize_fallback_cause(data.get("cause")),
                        )
                    except (ValidationError, ValueError) as e:
                        logger.warning(
                            "ignoring invalid fallback activation notice",
                            extra={
                                "session_id": data.get("session_id"),
                                "lk.pii.error": str(e),
                            },
                        )
                        continue
                    self._tts.emit(
                        "fallback_activated",
                        event,
                    )
                elif msg_type == "output_audio":
                    b64data = base64.b64decode(data["audio"])
                    output_emitter.push(b64data)
                elif msg_type == "output_alignment":
                    aligned: list[TimedString] = []
                    if words := data.get("words"):
                        aligned = [
                            TimedString(
                                f"{w['word']} " if provider == "cartesia" else w["word"],
                                start_time=w["start"],
                                end_time=w["end"],
                            )
                            for w in words
                        ]
                    elif chars := data.get("chars"):
                        aligned = [
                            TimedString(c["char"], start_time=c["start"], end_time=c["end"])
                            for c in chars
                        ]
                    if aligned:
                        # the provider aligned the *converted* text, so under expressive it
                        # carries native cues that were never spoken
                        output_emitter.push_timed_transcript(
                            drop_bracket_cues(aligned, self._held_tokens)
                            if self._expressive
                            else aligned
                        )
                elif msg_type == "done":
                    if self._held_tokens:  # release an unclosed span, cue unresolved
                        output_emitter.push_timed_transcript(
                            drop_bracket_cues([], self._held_tokens, final=True)
                        )
                    output_emitter.end_input()
                    break
                elif msg_type == "error":
                    raise APIError(f"LiveKit Inference TTS returned error: {msg.data}")

        try:
            async with self._tts._pool.connection(timeout=self._conn_options.timeout) as connection:
                self._acquire_time = self._tts._pool.last_acquire_time
                self._connection_reused = self._tts._pool.last_connection_reused
                request_id = create_inference_request_id(connection.session_id, "tts")
                output_emitter.initialize(
                    request_id=request_id,
                    sample_rate=self._opts.sample_rate,
                    num_channels=1,
                    stream=True,
                    mime_type="audio/pcm",
                )
                ws = connection.ws
                connection.in_use = True
                tasks = [
                    asyncio.create_task(_input_task()),
                    asyncio.create_task(_send_text_task(ws)),
                    asyncio.create_task(_recv_task(connection)),
                ]

                try:
                    await asyncio.gather(*tasks)
                finally:
                    connection.in_use = False
                    input_sent_event.set()
                    await text_stream.aclose()
                    await utils.aio.gracefully_cancel(*tasks)
                if connection.handoff_id is not None:
                    await self._tts._retire(connection)

        except asyncio.TimeoutError:
            raise APITimeoutError() from None

        except aiohttp.ClientResponseError as e:
            raise create_api_error_from_response(e) from None

        except APIError:
            raise

        except Exception as e:
            raise APIConnectionError() from e

Streamed API using websockets

Ancestors

  • livekit.agents.tts.tts.SynthesizeStream
  • abc.ABC
class TTS (model: TTSModels | str,
*,
voice: NotGivenOr[str] = NOT_GIVEN,
language: NotGivenOr[str] = NOT_GIVEN,
encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
sample_rate: NotGivenOr[int] = NOT_GIVEN,
base_url: NotGivenOr[str] = NOT_GIVEN,
api_key: NotGivenOr[str] = NOT_GIVEN,
api_secret: NotGivenOr[str] = NOT_GIVEN,
http_session: aiohttp.ClientSession | None = None,
extra_kwargs: NotGivenOr[dict[str, Any] | CartesiaOptions | DeepgramOptions | RimeOptions | InworldOptions | XaiOptions | FishAudioOptions | AssemblyaiOptions | GoogleOptions] = NOT_GIVEN,
fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
disable_system_default_fallback: bool = False,
conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN)
Expand source code
class TTS(tts.TTS[Literal["fallback_activated"]]):
    @overload
    def __init__(
        self,
        model: CartesiaModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[CartesiaOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: DeepgramModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[DeepgramOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: RimeModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[RimeOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: InworldModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[InworldOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: XaiModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[XaiOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: FishAudioModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[FishAudioOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: AssemblyAIModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[AssemblyaiOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: GoogleModels,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[GoogleOptions] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    @overload
    def __init__(
        self,
        model: str,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        pass

    def __init__(
        self,
        model: TTSModels | str,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        encoding: NotGivenOr[TTSEncoding] = NOT_GIVEN,
        sample_rate: NotGivenOr[int] = NOT_GIVEN,
        base_url: NotGivenOr[str] = NOT_GIVEN,
        api_key: NotGivenOr[str] = NOT_GIVEN,
        api_secret: NotGivenOr[str] = NOT_GIVEN,
        http_session: aiohttp.ClientSession | None = None,
        extra_kwargs: NotGivenOr[
            dict[str, Any]
            | CartesiaOptions
            | DeepgramOptions
            | RimeOptions
            | InworldOptions
            | XaiOptions
            | FishAudioOptions
            | AssemblyaiOptions
            | GoogleOptions
        ] = NOT_GIVEN,
        fallback: NotGivenOr[list[FallbackModelType] | FallbackModelType] = NOT_GIVEN,
        disable_system_default_fallback: bool = False,
        conn_options: NotGivenOr[APIConnectOptions] = NOT_GIVEN,
    ) -> None:
        """Livekit Cloud Inference TTS

        Args:
            model (TTSModels | str): TTS model to use, in "provider/model[:voice]" format
            voice (str, optional): Voice to use, use a default one if not provided
            language (str, optional): Language of the TTS model.
            encoding (TTSEncoding, optional): Encoding of the TTS model.
            sample_rate (int, optional): Sample rate of the TTS model.
            base_url (str, optional): LIVEKIT_URL, if not provided, read from environment variable.
            api_key (str, optional): LIVEKIT_API_KEY, if not provided, read from environment variable.
            api_secret (str, optional): LIVEKIT_API_SECRET, if not provided, read from environment variable.
            http_session (aiohttp.ClientSession, optional): HTTP session to use.
            extra_kwargs (dict, optional): Extra kwargs to pass to the TTS model.
            fallback (FallbackModelType | list[FallbackModelType], optional): Fallback models that
                LiveKit Inference tries in order if the primary model fails. Pass a single entry
                or a list. Each entry is a "provider/model[:voice]" string or a FallbackModel.
            disable_system_default_fallback (bool, optional): Opt out of LiveKit Inference's
                system-default fallback models. Models in ``fallback`` still apply.
            conn_options (APIConnectOptions, optional): Connection options for request attempts.
        """
        sample_rate = sample_rate if is_given(sample_rate) else DEFAULT_SAMPLE_RATE

        # Parse voice from model string if provided: "provider/model:voice"
        if isinstance(model, str):
            parsed_model, parsed_voice = _parse_model_string(model)
            model = parsed_model
            if parsed_voice is not None and not is_given(voice):
                voice = parsed_voice

        resolved_extra_kwargs = dict(extra_kwargs) if is_given(extra_kwargs) else {}
        super().__init__(
            capabilities=tts.TTSCapabilities(
                streaming=True,
                aligned_transcript=_has_aligned_transcript(model, resolved_extra_kwargs),
            ),
            sample_rate=sample_rate,
            num_channels=1,
        )

        lk_base_url = base_url if is_given(base_url) else get_default_inference_url()

        lk_api_key = (
            api_key
            if is_given(api_key)
            else os.getenv("LIVEKIT_INFERENCE_API_KEY", os.getenv("LIVEKIT_API_KEY", ""))
        )
        if not lk_api_key and token_mode_token() is None:
            raise ValueError(
                "api_key is required, either as argument or set LIVEKIT_API_KEY environmental variable"
            )

        lk_api_secret = (
            api_secret
            if is_given(api_secret)
            else os.getenv("LIVEKIT_INFERENCE_API_SECRET", os.getenv("LIVEKIT_API_SECRET", ""))
        )
        if not lk_api_secret and token_mode_token() is None:
            raise ValueError(
                "api_secret is required, either as argument or set LIVEKIT_API_SECRET environmental variable"
            )

        fallback_models: NotGivenOr[list[FallbackModel]] = NOT_GIVEN
        if is_given(fallback):
            fallback_models = _normalize_fallback(fallback)

        self._opts = _TTSOptions(
            model=model,
            voice=voice,
            language=LanguageCode(language) if isinstance(language, str) else language,
            encoding=encoding if is_given(encoding) else DEFAULT_ENCODING,
            sample_rate=sample_rate,
            base_url=lk_base_url,
            api_key=lk_api_key,
            api_secret=lk_api_secret,
            extra_kwargs=resolved_extra_kwargs,
            fallback=fallback_models,
            disable_system_default_fallback=disable_system_default_fallback,
            conn_options=conn_options if is_given(conn_options) else DEFAULT_API_CONNECT_OPTIONS,
        )
        self._session = http_session
        self._pool = utils.ConnectionPool[_TTSConnection](
            connect_cb=self._connect_ws,
            close_cb=self._close_ws,
            max_session_duration=300,
            mark_refreshed_on_get=True,
        )
        self._streams = weakref.WeakSet[SynthesizeStream]()

    class Markup(tts.TTS.Markup):
        def __init__(self, gateway_tts: TTS) -> None:
            super().__init__(gateway_tts)
            self._gateway_tts = gateway_tts

        def _provider_key(self) -> str:
            model = self._gateway_tts._opts.model
            provider = model.split("/")[0]
            if provider == "inworld" and "tts-2" in model:
                return "inworld"
            elif provider == "inworld":
                return ""  # older inworld models don't support markup
            elif provider == "fishaudio" and "drama" in model:
                return "fishaudio_drama"  # free-form direction instead of fixed emotions
            elif provider == "google":
                # the delivery marker rides each transcript's extra.style (_gemini_packets)
                return "gemini" if model in _GEMINI_STYLE_MODELS else ""
            return provider

        # llm_instructions / normalize / convert are inherited from the base Markup,
        # keyed on _provider_key() above.

    @classmethod
    def from_model_string(cls, model: str) -> TTS:
        """Create a TTS instance from a model string

        Args:
            model (str): TTS model to use, in "provider/model[:voice_id]" format

        Returns:
            TTS: TTS instance
        """
        model, voice = _parse_model_string(model)
        return cls(model=model, voice=voice if voice else NOT_GIVEN)

    @property
    def model(self) -> str:
        return self._opts.model

    @property
    def provider(self) -> str:
        return "livekit"

    async def _connect_ws(self, timeout: float) -> _TTSConnection:
        session = self._ensure_session()
        base_url = self._opts.base_url
        if base_url.startswith(("http://", "https://")):
            base_url = base_url.replace("http", "ws", 1)

        headers = {
            **get_inference_headers(),
            "Authorization": f"Bearer {create_access_token(self._opts.api_key, self._opts.api_secret)}",
        }
        session_id = headers.get(HEADER_SESSION_ID)
        ws = None
        try:
            ws = await asyncio.wait_for(
                session.ws_connect(
                    f"{base_url}/tts?{urlencode({'model': self._opts.model})}", headers=headers
                ),
                timeout,
            )
        except aiohttp.ClientResponseError as e:
            raise create_api_error_from_response(e) from e
        except asyncio.TimeoutError as e:
            raise APITimeoutError("LiveKit Inference TTS connection timed out.") from e
        except aiohttp.ClientConnectorError as e:
            raise APIConnectionError("failed to connect to LiveKit Inference TTS") from e

        params = _build_session_create_payload(self._opts)

        try:
            payload = json.dumps(params)
            await ws.send_str(payload)
        except Exception as e:
            await ws.close()
            raise APIConnectionError(
                "failed to send session.create message to LiveKit Inference TTS"
            ) from e

        connection = _TTSConnection(ws=ws, session_id=session_id)
        connection.reader = asyncio.create_task(self._read_ws(connection))
        return connection

    async def _close_ws(self, connection: _TTSConnection) -> None:
        if connection.reader is not None:
            connection.reader.cancel()
        await connection.ws.close()

    async def _read_ws(self, connection: _TTSConnection) -> None:
        while True:
            msg = await connection.ws.receive()
            if msg.type == aiohttp.WSMsgType.TEXT:
                try:
                    data = json.loads(msg.data)
                except ValueError:
                    data = {}
                if data.get("type") == "session.handoff.request":
                    # the gateway is draining: finish any turn here, then leave
                    connection.handoff_id = str(data.get("handoff_id", ""))
                    if not connection.in_use:
                        await self._retire(connection)
                    continue
            connection.inbox.put_nowait(msg)
            if msg.type in (
                aiohttp.WSMsgType.CLOSE,
                aiohttp.WSMsgType.CLOSED,
                aiohttp.WSMsgType.CLOSING,
                aiohttp.WSMsgType.ERROR,
            ):
                if not connection.in_use:
                    self._pool.remove(connection)
                return

    async def _retire(self, connection: _TTSConnection) -> None:
        """Leave a draining gateway: acknowledge, close, and open the next connection elsewhere."""
        if connection.retired:
            return
        connection.retired = True
        self._pool.remove(connection)
        try:
            await connection.ws.send_str(
                json.dumps(
                    {"type": "session.handoff.complete", "handoff_id": connection.handoff_id}
                )
            )
        except Exception:
            pass
        await connection.ws.close()
        self._pool.prewarm()

    def _ensure_session(self) -> aiohttp.ClientSession:
        if not self._session:
            self._session = utils.http_context.http_session()

        return self._session

    def prewarm(self) -> None:
        self._pool.prewarm()

    def update_options(
        self,
        *,
        voice: NotGivenOr[str] = NOT_GIVEN,
        model: NotGivenOr[TTSModels | str] = NOT_GIVEN,
        language: NotGivenOr[str] = NOT_GIVEN,
        extra_kwargs: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
    ) -> None:
        """
        Args:
            voice (str, optional): Voice.
            model (TTSModels | str, optional): TTS model to use.
            language (str, optional): Language code for the TTS model.
            extra_kwargs (dict, optional): Extra kwargs to pass to the TTS model.
        """
        if is_given(model):
            self._opts.model = model
        if is_given(voice):
            self._opts.voice = voice
        if is_given(language):
            self._opts.language = LanguageCode(language)
        if is_given(extra_kwargs):
            self._opts.extra_kwargs.update(extra_kwargs)

        self._capabilities.aligned_transcript = _has_aligned_transcript(
            self._opts.model, self._opts.extra_kwargs
        )

    def synthesize(
        self, text: str, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
    ) -> tts.ChunkedStream:
        return self._synthesize_with_stream(text, conn_options=conn_options)

    def stream(
        self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
    ) -> SynthesizeStream:
        stream = SynthesizeStream(tts=self, conn_options=conn_options)
        self._streams.add(stream)
        return stream

    async def aclose(self) -> None:
        for stream in list(self._streams):
            await stream.aclose()

        self._streams.clear()
        await self._pool.aclose()

Helper class that provides a standard way to create an ABC using inheritance.

Livekit Cloud Inference TTS

Args

model : TTSModels | str
TTS model to use, in "provider/model[:voice]" format
voice : str, optional
Voice to use, use a default one if not provided
language : str, optional
Language of the TTS model.
encoding : TTSEncoding, optional
Encoding of the TTS model.
sample_rate : int, optional
Sample rate of the TTS model.
base_url : str, optional
LIVEKIT_URL, if not provided, read from environment variable.
api_key : str, optional
LIVEKIT_API_KEY, if not provided, read from environment variable.
api_secret : str, optional
LIVEKIT_API_SECRET, if not provided, read from environment variable.
http_session : aiohttp.ClientSession, optional
HTTP session to use.
extra_kwargs : dict, optional
Extra kwargs to pass to the TTS model.
fallback : FallbackModelType | list[FallbackModelType], optional
Fallback models that LiveKit Inference tries in order if the primary model fails. Pass a single entry or a list. Each entry is a "provider/model[:voice]" string or a FallbackModel.
disable_system_default_fallback : bool, optional
Opt out of LiveKit Inference's system-default fallback models. Models in fallback still apply.
conn_options : APIConnectOptions, optional
Connection options for request attempts.

Ancestors

  • livekit.agents.tts.tts.TTS
  • abc.ABC
  • EventEmitter
  • typing.Generic

Class variables

var Markup

Declares TTS markup capabilities for the expressive pipeline.

Plugins override this inner class to declare which markup dialect the TTS speaks: what the LLM is taught to write, and how those markers are normalized and lowered to the provider's native syntax before synthesis. Stripping markup back out is not here — the transcript sinks do it provider-agnostically (see _provider_format.split_all_markup).

Static methods

def from_model_string(model: str) ‑> TTS

Create a TTS instance from a model string

Args

model : str
TTS model to use, in "provider/model[:voice_id]" format

Returns

TTS
TTS instance

Instance variables

prop model : str
Expand source code
@property
def model(self) -> str:
    return self._opts.model

Get the model name/identifier for this TTS instance.

Returns

The model name if available, "unknown" otherwise.

Note

Plugins should override this property to provide their model information.

prop provider : str
Expand source code
@property
def provider(self) -> str:
    return "livekit"

Get the provider name/identifier for this TTS instance.

Returns

The provider name if available, "unknown" otherwise.

Note

Plugins should override this property to provide their provider information.

Methods

async def aclose(self) ‑> None
Expand source code
async def aclose(self) -> None:
    for stream in list(self._streams):
        await stream.aclose()

    self._streams.clear()
    await self._pool.aclose()
def prewarm(self) ‑> None
Expand source code
def prewarm(self) -> None:
    self._pool.prewarm()

Pre-warm connection to the TTS service

def stream(self,
*,
conn_options: APIConnectOptions = APIConnectOptions(max_retry=3, retry_interval=2.0, timeout=10.0, liveness_timeout=6.0)) ‑> SynthesizeStream
Expand source code
def stream(
    self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
) -> SynthesizeStream:
    stream = SynthesizeStream(tts=self, conn_options=conn_options)
    self._streams.add(stream)
    return stream
def synthesize(self,
text: str,
*,
conn_options: APIConnectOptions = APIConnectOptions(max_retry=3, retry_interval=2.0, timeout=10.0, liveness_timeout=6.0)) ‑> livekit.agents.tts.tts.ChunkedStream
Expand source code
def synthesize(
    self, text: str, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
) -> tts.ChunkedStream:
    return self._synthesize_with_stream(text, conn_options=conn_options)
def update_options(self,
*,
voice: NotGivenOr[str] = NOT_GIVEN,
model: NotGivenOr[TTSModels | str] = NOT_GIVEN,
language: NotGivenOr[str] = NOT_GIVEN,
extra_kwargs: NotGivenOr[dict[str, Any]] = NOT_GIVEN) ‑> None
Expand source code
def update_options(
    self,
    *,
    voice: NotGivenOr[str] = NOT_GIVEN,
    model: NotGivenOr[TTSModels | str] = NOT_GIVEN,
    language: NotGivenOr[str] = NOT_GIVEN,
    extra_kwargs: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
) -> None:
    """
    Args:
        voice (str, optional): Voice.
        model (TTSModels | str, optional): TTS model to use.
        language (str, optional): Language code for the TTS model.
        extra_kwargs (dict, optional): Extra kwargs to pass to the TTS model.
    """
    if is_given(model):
        self._opts.model = model
    if is_given(voice):
        self._opts.voice = voice
    if is_given(language):
        self._opts.language = LanguageCode(language)
    if is_given(extra_kwargs):
        self._opts.extra_kwargs.update(extra_kwargs)

    self._capabilities.aligned_transcript = _has_aligned_transcript(
        self._opts.model, self._opts.extra_kwargs
    )

Args

voice : str, optional
Voice.
model : TTSModels | str, optional
TTS model to use.
language : str, optional
Language code for the TTS model.
extra_kwargs : dict, optional
Extra kwargs to pass to the TTS model.

Inherited members

class XaiOptions (*args, **kwargs)
Expand source code
class XaiOptions(TypedDict, total=False):
    bit_rate: Literal[32000, 64000, 96000, 128000, 192000]
    speed: float  # speaking-rate multiplier, default 1.0
    optimize_streaming_latency: Literal[0, 1, 2]  # latency optimization level, default 0

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

Ancestors

  • builtins.dict

Class variables

var bit_rate : Literal[32000, 64000, 96000, 128000, 192000]
var optimize_streaming_latency : Literal[0, 1, 2]
var speed : float