# Custom NLU Components

You can create a custom component to perform a specific task which NLU doesn’t currently offer (for example, sentiment analysis). Below is the specification of the [`rasa.nlu.components.Component`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component "rasa.nlu.components.Component") class with the methods you’ll need to implement.

**Note**  
There is a detailed tutorial on building custom components [here](https://blog.rasa.com/enhancing-rasa-nlu-with-custom-components/).

You can add a custom component to your pipeline by adding the module path.  
So if you have a module called `sentiment`  
containing a `SentimentAnalyzer` class:

```yaml
pipeline:
- name: "sentiment.SentimentAnalyzer"
```

Also be sure to read the section on the [Component Lifecycle](https://legacy-docs-v1.rasa.com/1.7.2/nlu/choosing-a-pipeline/#section-component-lifecycle).

To get started, you can use this skeleton that contains the most important methods that you should implement:

|     |     |
| --- | --- |
| ```<br> 1<br> 2<br> 3<br> 4<br> 5<br> 6<br> 7<br> 8<br> 9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33<br>34<br>35<br>36<br>37<br>38<br>39<br>40<br>41<br>42<br>43<br>44<br>45<br>46<br>47<br>48<br>49<br>50<br>51<br>52<br>53<br>54<br>55<br>56<br>57<br>58<br>59<br>60<br>61<br>62<br>63<br>64<br>65<br>66<br>67<br>68<br>69<br>70<br>71<br>72<br>73<br>74<br>75<br>76<br>77<br>78<br>79<br>80<br>81<br>82<br>83<br>84<br>85<br>86<br>87<br>88<br>``` | ````<br>from rasa.nlu.components import Component<br>import typing<br>from typing import Any, Optional, Text, Dict<br>if typing.TYPE_CHECKING:<br>    from rasa.nlu.model import Metadata<br>class MyComponent(Component):<br>    """A new component"""<br>    # Defines what attributes the pipeline component will<br>    # provide when called. The listed attributes<br>    # should be set by the component on the message object<br>    # during test and train, e.g.<br>    # ```message.set("entities", [...])```<br>    provides = []<br>    # Which attributes on a message are required by this<br>    # component. E.g. if requires contains "tokens", than a<br>    # previous component in the pipeline needs to have "tokens"<br>    # within the above described `provides` property.<br>    # Use `any_of("option_1", "option_2")` to define that either<br>    # "option_1" or "option_2" needs to be present in the<br>    # provided properties from the previous components.<br>    requires = []<br>    # Defines the default configuration parameters of a component<br>    # these values can be overwritten in the pipeline configuration<br>    # of the model. The component should choose sensible defaults<br>    # and should be able to create reasonable results with the defaults.<br>    defaults = {}<br>    # Defines what language(s) this component can handle.<br>    # This attribute is designed for instance method: `can_handle_language`.<br>    # Default value is None which means it can handle all languages.<br>    # This is an important feature for backwards compatibility of components.<br>    language_list = None<br>    def __init__(self, component_config=None):<br>        super().__init__(component_config)<br>    def train(self, training_data, cfg, **kwargs):<br>        """Train this component.<br>        This is the components chance to train itself provided<br>        with the training data. The component can rely on<br>        any context attribute to be present, that gets created<br>        by a call to :meth:`components.Component.pipeline_init`<br>        of ANY component and<br>        on any context attributes created by a call to<br>        :meth:`components.Component.train`<br>        of components previous to this one."""<br>        pass<br>    def process(self, message, **kwargs):<br>        """Process an incoming message.<br>        This is the components chance to process an incoming<br>        message. The component can rely on<br>        any context attribute to be present, that gets created<br>        by a call to :meth:`components.Component.pipeline_init`<br>        of ANY component and<br>        on any context attributes created by a call to<br>        :meth:`components.Component.process`<br>        of components previous to this one."""<br>        pass<br>    def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:<br>        """Persist this component to disk for future loading."""<br>        pass<br>    @classmethod<br>    def load(<br>        cls,<br>        meta: Dict[Text, Any],<br>        model_dir: Optional[Text] = None,<br>        model_metadata: Optional["Metadata"] = None,<br>        cached_component: Optional["Component"] = None,<br>        **kwargs: Any,<br>    ) -> "Component":<br>        """Load this component from file."""<br>        if cached_component:<br>            return cached_component<br>        else:<br>            return cls(meta)<br>```` |

**Note**  
If you create a custom tokenizer you should implement the methods of `rasa.nlu.tokenizers.tokenizer.Tokenizer`.  
The `train` and `process` methods are already implemented and you simply need to overwrite the `tokenize` method.  
`train` and `process` will automatically add a special token `__CLS__` to the end of list of tokens, which is needed further down the pipeline.

**Note**  
If you create a custom featurizer you should return a sequence of features.  
E.g. your featurizer should return a matrix of size (number-of-tokens x feature-dimension).  
The feature vector of the `__CLS__` token should contain features for the complete message.

## Component

_class_`rasa.nlu.components.``Component`( _component_config=None_)

A component is a message processing unit in a pipeline.

Components are collected sequentially in a pipeline. Each component  
is called one after another. This holds for  
initialization, training, persisting and loading the components.  
If a component comes first in a pipeline, its  
methods will be called first.

E.g. to process an incoming message, the `process` method of  
each component will be called. During the processing  
(as well as the training, persisting and initialization)  
components can pass information to other components.  
The information is passed to other components by providing  
attributes to the so called pipeline context. The  
pipeline context contains all the information of the previous  
components a component can use to do its own  
processing. For example, a featurizer component can provide  
features that are used by another component down  
the pipeline to do intent classification.

_classmethod_`required_packages`()

Specify which python packages need to be installed.

E.g. `["spacy"]`. More specifically, these should be  
importable python package names e.g. sklearn and not package  
names in the dependencies sense e.g. scikit-learn

This list of requirements allows us to fail early during training  
if a required package is not installed.

Returns

The list of required package names.

Return type

`List`
[`str`]

_classmethod_`create`( _component_config_, _config_)

Creates this component (e.g. before a training is started).

Method can access all configuration parameters.

Parameters

- **component_config** – The components configuration parameters.
- **config** – The model configuration parameters.

Returns

The created component.

Return type
[`Component`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component "rasa.nlu.components.Component")

`provide_context`()

Initialize this component for a new pipeline.

This function will be called before the training  
is started and before the first message is processed using  
the interpreter. The component gets the opportunity to  
add information to the context that is passed through  
the pipeline during training and message parsing. Most  
components do not need to implement this method.  
It’s mostly used to initialize framework environments  
like MITIE and spacy  
(e.g. loading word vectors for the pipeline).

Returns

The updated component configuration.

Return type
`Optional`
[`Dict`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component.provide_context "Permalink to this definition")

`train`( _training_data_, _config=None_, _**kwargs_)

Train this component.

This is the components chance to train itself provided  
with the training data. The component can rely on  
any context attribute to be present, that gets created  
by a call to [`rasa.nlu.components.Component.create()`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component.create "rasa.nlu.components.Component.create")  
of ANY component and  
on any context attributes created by a call to  
[`rasa.nlu.components.Component.train()`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component.train "rasa.nlu.components.Component.train")  
of components previous to this one.

Parameters

- **training_data** – The `rasa.nlu.training_data.training_data.TrainingData`.
- **config** – The model configuration parameters.

Return type
`None`

`process`( _message_, _**kwargs_)

Process an incoming message.

This is the components chance to process an incoming  
message. The component can rely on  
any context attribute to be present, that gets created  
by a call to [`rasa.nlu.components.Component.create()`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component.create "rasa.nlu.components.Component.create")  
of ANY component and  
on any context attributes created by a call to  
[`rasa.nlu.components.Component.process()`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component.process "rasa.nlu.components.Component.process")  
of components previous to this one.

Parameters

- **message** – The `rasa.nlu.training_data.message.Message` to process.

Return type
`None`

`persist`( _file_name_, _model_dir_)

Persist this component to disk for future loading.

Parameters

- **file_name** – The file name of the model.
- **model_dir** – The directory to store the model to.

Returns

An optional dictionary with any information about the stored model.

Return type
`Optional`
[`Dict`](https://legacy-docs-v1.rasa.com/1.7.2/api/custom-nlu-components/#rasa.nlu.components.Component.persist "Permalink to this definition")

`prepare_partial_processing`( _pipeline_, _context_)

Sets the pipeline and context used for partial processing.

The pipeline should be a list of components that are  
previous to this one in the pipeline and  
have already finished their training (and can therefore  
be safely used to process messages).

Parameters

- **pipeline** – The list of components.
- **context** – The context of processing.

Return type
`None`

`partially_process`( _message_)

Allows the component to process messages during  
training (e.g. external training data).

The passed message will be processed by all components  
previous to this one in the pipeline.

Parameters

- **message** – The `rasa.nlu.training_data.message.Message` to process.

Returns

The processed `rasa.nlu.training_data.message.Message`.

Return type
`Message`

_classmethod_`can_handle_language`( _language_)

Check if component supports a specific language.

This method can be overwritten when needed. (e.g. dynamically  
determine which language is supported.)

Parameters

- **language** – The language to check.

Returns

True if component can handle specific language, False otherwise.

Return type
`bool`
