> ## 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 ASR Components

> Implement and configure a custom automatic speech recognition engine for Rasa voice-stream channels.

## Custom ASR

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

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

You can implement your own custom ASR component as a Python class to
integrate with any third-party speech recognition service. A custom ASR
component must subclass the `ASREngine` class from `rasa.core.channels.voice_stream.asr.asr_engine`.

Your custom ASR component receives audio as `RasaAudioBytes` in the format selected for the channel. Convert it if your provider expects a different encoding.

### Required Methods

Your custom ASR component must provide the following methods:

* `name()`: Return the engine name.
* `open_websocket_connection()`: Establish a WebSocket connection to your ASR service.
* `from_config_dict(config, format, rasa_language, additional_languages)`: Create an engine from channel configuration.
* `signal_audio_done()`: Signal that audio input has ended.
* `engine_event_to_asr_event(event)`: Convert provider messages to `ASREvent` objects.
* `get_default_config(rasa_language)`: Return defaults for the assistant language.

Override `rasa_audio_bytes_to_engine_bytes()` if the provider needs a different audio format. Its default implementation returns the audio bytes as-is.

### Optional Methods

You may also override these methods as needed:

* `send_keep_alive()`: Send keep-alive messages to maintain the connection. The default implementation is only a `pass` statement.
* `close_connection()`: Add provider-specific cleanup when needed. The base implementation flushes buffered audio and closes the WebSocket.

### ASR Events

Your `engine_event_to_asr_event` method should return appropriate `ASREvent` objects:

* `UserIsSpeaking(transcript)`: For interim/partial transcripts while the user is speaking
* `NewTranscript(transcript)`: For final transcripts when the user has finished speaking

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

### Example Implementation

This example shows the integration points. Replace the WebSocket URL, request parameters, and event parsing with the protocol used by your provider.

```python title="custom_asr.py" theme={null}
import json
import os
from typing import Any, Dict, List, Optional, Type
from urllib.parse import urlencode

from websockets.asyncio.client import ClientConnection, connect

from rasa.core.channels.voice_stream.asr.asr_engine import (
    ASREngine,
    ASREngineConfig,
    ASRLanguageMapEntry,
)
from rasa.core.channels.voice_stream.asr.asr_event import (
    ASREvent,
    NewTranscript,
    UserIsSpeaking,
)
from rasa.core.channels.voice_stream.audio_bytes import AudioFormat, RasaAudioBytes

class MyASRConfig(ASREngineConfig):
    endpoint: str = "wss://api.example.com/v1/speech"

class MyASR(ASREngine[MyASRConfig]):
    required_env_vars = ("MY_ASR_API_KEY",)
    required_packages = ("websockets",)

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

    async def open_websocket_connection(self) -> ClientConnection:
        api_key = os.environ["MY_ASR_API_KEY"]
        headers = {"Authorization": f"Bearer {api_key}"}
        query_params = {
            "language": self.current_language_config.engine_language_key or "en-US",
            "encoding": self.audio_format.encoding.value,
            "sample_rate": str(self.audio_format.sample_rate),
            "interim_results": "true",
        }
        url = f"{self.config.endpoint}?{urlencode(query_params)}"
        return await connect(url, additional_headers=headers)

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

    async def signal_audio_done(self) -> None:
        if self.asr_socket is not None:
            await self.asr_socket.send(json.dumps({"type": "stop_audio"}))

    def rasa_audio_bytes_to_engine_bytes(self, chunk: RasaAudioBytes) -> bytes:
        return chunk.data

    def engine_event_to_asr_event(self, event: Any) -> Optional[ASREvent]:
        data = json.loads(event)
        if data.get("type") == "transcript":
            transcript = data.get("text", "")
            if data.get("is_final"):
                return NewTranscript(transcript)
            if transcript:
                return UserIsSpeaking(transcript)
        return None

    @staticmethod
    def get_default_config(rasa_language: str) -> MyASRConfig:
        return MyASRConfig(
            endpoint="wss://api.example.com/v1/speech",
            language_map={
                rasa_language: ASRLanguageMapEntry(language=rasa_language),
            },
        )

    async def send_keep_alive(self) -> None:
        """Send keep-alive message if supported by your service."""
        if self.asr_socket is not None:
            await self.asr_socket.send(json.dumps({"type": "keep_alive"}))
```

This structure allows you to integrate any speech recognition service with Rasa's voice capabilities while maintaining compatibility with the existing voice stream infrastructure.

## Configure a custom ASR component

To use a custom ASR component, configure its module path and settings in your `credentials.yml` file. The configuration should contain the **module path** of your custom class and any required configuration parameters.

The module path follows the format `path.to.module.ClassName`. For example, a class `MyASR` in `addons/custom_asr.py` has module path `addons.custom_asr.MyASR`.

### Custom ASR Configuration Example

```yaml title="credentials.yml" theme={null}
browser_audio:
  # ... other configuration
  asr:
    name: addons.custom_asr.MyASR
    endpoint: "wss://api.example.com/v1/speech"
    # any other custom parameters your ASR needs
```

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


## Related topics

- [ASR Integrations](https://rasa.com/docs/reference/integrations/asr-integrations.md)
- [Speech Integrations](https://rasa.com/docs/reference/integrations/speech-integrations.md)
- [Custom TTS Components](https://rasa.com/docs/reference/integrations/custom-tts.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.