> ## Documentation Index
> Fetch the complete documentation index at: https://rasa.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom TTS Components

> Implement and configure a custom text-to-speech engine for Rasa voice-stream channels.

## Custom TTS

Implement a custom provider when none of the [built-in TTS engines](https://rasa.com/docs/reference/integrations/tts-integrations.md) meet your requirements. This guide covers the component class, streaming modes, and credentials configuration.

> [!TIP]
>
> **Create Custom TTS with Skills**
>
> [Rasa MCP Tools](https://rasa.com/docs/pro/installation/rasa-mcp-tools.md) includes AI Skills to scaffold and audit your custom TTS component with your IDE copilot.
> Run `rasa tools init` in your project root to install the agent skills.

You can implement your own custom TTS component as a Python class to
integrate with any third-party text-to-speech service. A custom TTS component
must subclass the `TTSEngine` class from
`rasa.core.channels.voice_stream.tts.tts_engine`.

Your custom TTS component must output audio in the [RasaAudioBytes format](https://rasa.com/docs/reference/integrations/speech-integrations.md#audio-format)
and convert it using the `engine_bytes_to_rasa_audio_bytes` method.

### Component methods

Implement `name()`, `from_config_dict(config, format, rasa_language, additional_languages)`, and `get_default_config(rasa_language)` for your component. For streaming input, also implement `send_text_chunk()`, `signal_text_done()`, and `stream_audio()`. The base class provides `connect()`, `close_connection()`, `synthesize()`, and audio wrapping; override them when your provider needs custom connection, synthesis, cleanup, or audio conversion behavior.

### Optional Methods

You may also override these methods as needed:

* `connect(config: Optional[T])`: Establish connection to the TTS engine if necessary. Default implementation does nothing.
* `close_connection()`: Custom cleanup when closing connections (e.g., closing websockets or HTTP sessions). Default implementation does nothing.
* `send_text_chunk(text: str)`: Send text chunks to the TTS system for streaming synthesis. Used with `stream_audio()` for real-time streaming.
* `signal_text_done()`: Signal TTS engine to process any remaining buffered text and prepare to end the stream.
* `stream_audio()`: Stream audio output from the TTS engine. Continuously yields audio chunks as they are produced by the engine.

### Streaming vs Non-Streaming TTS

The TTSEngine supports both streaming and non-streaming modes:

* **Non-streaming**: Implement only `synthesize()` method for simple request-response synthesis
* **Streaming**: Set `streaming_input = True` and implement `send_text_chunk()`, `signal_text_done()`, and `stream_audio()` methods for real-time streaming synthesis

### Required Class Attributes

You can optionally define these class attributes:

* `required_env_vars`: Tuple of required environment variable names
* `required_packages`: Tuple of required Python package names
* `streaming_input`: Boolean indicating if the engine supports streaming input (defaults to `False`)

See [Configure a custom TTS component](#configure-a-custom-tts-component) for the credentials configuration.

### Example Implementation

Here's an example of an implementation for TTS streaming:

```python title="custom_tts.py" theme={null}
import base64
import os
from typing import AsyncIterator, Dict, List, Optional, Type
from urllib.parse import urlencode

import aiohttp
from aiohttp import ClientTimeout, WSMsgType

from rasa.core.channels.voice_stream.audio_bytes import AudioFormat, RasaAudioBytes
from rasa.core.channels.voice_stream.tts.tts_engine import (
    TTSEngine,
    TTSEngineConfig,
    TTSLanguageMapEntry,
    TTSError,
)
class MyTTSConfig(TTSEngineConfig):
    endpoint: str = "wss://api.example.com/v1/speak"
    model_id: str = "en-US-standard"


class MyTTS(TTSEngine[MyTTSConfig]):
    required_env_vars = ("MY_TTS_API_KEY",)
    required_packages = ("aiohttp",)
    streaming_input = True

    def __init__(
        self,
        rasa_language: str,
        format: AudioFormat,
        config: Optional[MyTTSConfig] = None,
        additional_languages: Optional[List[str]] = None,
    ):
        super().__init__(rasa_language, format, config, additional_languages)
        self.session: Optional[aiohttp.ClientSession] = None
        self.ws: Optional[aiohttp.ClientWebSocketResponse] = None

    @classmethod
    def name(cls) -> str:
        return "my_tts"

    async def connect(self, config: Optional[MyTTSConfig] = None) -> None:
        if self.ws is not None and not self.ws.closed:
            return

        self.session = aiohttp.ClientSession(
            timeout=ClientTimeout(total=self.config.timeout)
        )
        headers = {"Authorization": f"Bearer {os.environ['MY_TTS_API_KEY']}"}
        query_params = {
            "model": self.current_language_config.model or self.config.model_id,
            "language": self.current_language_config.engine_language_key,
            "voice": self.current_language_config.voice,
            "encoding": self.audio_format.encoding.value,
            "sample_rate": str(self.audio_format.sample_rate),
        }
        query_params = {key: value for key, value in query_params.items() if value}
        ws_url = f"{self.config.endpoint}?{urlencode(query_params)}"

        try:
            self.ws = await self.session.ws_connect(ws_url, headers=headers)
        except Exception as error:
            await self.session.close()
            self.session = None
            raise TTSError(f"Failed to connect to TTS service: {error}") from error

    async def close_connection(self) -> None:
        if self.ws and not self.ws.closed:
            await self.ws.close()
        self.ws = None
        if self.session and not self.session.closed:
            await self.session.close()
        self.session = None

    async def send_text_chunk(self, text: str) -> None:
        if self.ws is None:
            raise TTSError("The TTS WebSocket is not connected.")
        await self.ws.send_json({"text": text})

    async def signal_text_done(self) -> None:
        if self.ws is None:
            raise TTSError("The TTS WebSocket is not connected.")
        await self.ws.send_json({"operation": "flush"})

    async def stream_audio(self) -> AsyncIterator[RasaAudioBytes]:
        if self.ws is None:
            raise TTSError("The TTS WebSocket is not connected.")

        try:
            async for message in self.ws:
                if message.type == WSMsgType.TEXT:
                    data = message.json()
                    if data.get("type") == "audio":
                        audio_bytes = base64.b64decode(data.get("data", ""))
                        if audio_bytes:
                            yield self.engine_bytes_to_rasa_audio_bytes(audio_bytes)
                    elif data.get("type") == "error":
                        raise TTSError(f"TTS error: {data.get('message')}")
                elif message.type == WSMsgType.ERROR:
                    raise TTSError("WebSocket error during audio streaming")
        except TTSError:
            raise
        except Exception as error:
            raise TTSError(f"Error during audio streaming: {error}") from error

    def engine_bytes_to_rasa_audio_bytes(self, chunk: bytes) -> RasaAudioBytes:
        # Convert the bytes here if your provider's audio format differs from
        # the format negotiated for the channel.
        return RasaAudioBytes(chunk, format=self.audio_format)

    @staticmethod
    def get_default_config(rasa_language: str) -> MyTTSConfig:
        return MyTTSConfig(
            language_map={
                rasa_language: TTSLanguageMapEntry(
                    language=rasa_language,
                    voice="female-1",
                ),
            },
        )

    @classmethod
    def from_config_dict(
        cls: Type["MyTTS"],
        config: Dict,
        format: AudioFormat,
        rasa_language: str,
        additional_languages: Optional[List[str]] = None,
    ) -> "MyTTS":
        return cls(
            config=MyTTSConfig.model_validate(config or {}),
            format=format,
            rasa_language=rasa_language,
            additional_languages=additional_languages,
        )
```

> [!TIP]
>
> **Non-Streaming TTS**
>
> If your TTS service doesn't support continuous input streaming (i.e., you need to send all text at once), set `streaming_input = False` and only implement the `synthesize()` method. You can skip implementing `connect()`, `send_text_chunk()`, `signal_text_done()`, and `stream_audio()` methods. The `synthesize()` method should handle the entire synthesis process from text to audio.

## Configure a custom TTS component

To use a custom TTS component, configure its module path and settings in your `credentials.yml` file. The module path follows the format `path.to.module.ClassName`. For example, a class `MyTTS` in `addons/custom_tts.py` has module path `addons.custom_tts.MyTTS`.

### Custom TTS Configuration Example

```yaml title="credentials.yml" theme={null}
browser_audio:
  # ... other configuration
  tts:
    name: addons.custom_tts.MyTTS
    endpoint: "wss://api.example.com/v1/speak"
    model_id: "en-US-standard"
    language_map:
      en:
        language: "en-US"
        voice: "female-1"
    timeout: 30
    # any other custom parameters your TTS needs
```

Any custom parameters you define in your configuration class (e.g., `MyASRConfig` or `MyTTSConfig`) can be passed through the credentials file and will be available in your component via `self.config`.

Set the `MY_TTS_API_KEY` environment variable before starting Rasa. The example reads this variable when it opens the provider connection.


## Related topics

- [TTS Integrations](https://rasa.com/docs/reference/integrations/tts-integrations.md)
- [Speech Integrations](https://rasa.com/docs/reference/integrations/speech-integrations.md)
- [Custom ASR Components](https://rasa.com/docs/reference/integrations/custom-asr.md)
- [Custom Information Retrieval with Enterprise Search Policy](https://rasa.com/docs/reference/config/policies/custom-information-retrievers.md)
- [Rasa Pro Version Migration Guide](https://rasa.com/docs/reference/changelogs/rasa-pro-migration-guide.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.