Custom NLU Components

User Guide

NLU

Core

Conversation Design

API Reference

Migrate from (beta)

Reference

Versions

viewing: 1.10.1

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 class with the methods you’ll need to implement.

Note: There is a detailed tutorial on building custom components here.

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:

pipeline:
- name: "sentiment.SentimentAnalyzer"

Also be sure to read the section on the Component Lifecycle.

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

```\
1\
2\
3\
4\
5\
6\
7\
8\
9\
10\
11\
12\
13\
14\
15\
16\
17\
18\
19\
20\
21\
22\
23\
24\
25\
26\
27\
28\
29\
30\
31\
32\
33\
34\
35\
36\
37\
38\
39\
40\
41\
42\
43\
44\
45\
46\
47\
48\
49\
50\
51\
52\
53\
54\
55\
56\
57\
58\
59\
60\
61\
62\
63\
64\
65\
66\
67\
68\
69\
70\
71\
72\
73\
74\
75\
76\
77\
78\
79\
80\
81\
82\
83\
84\
85\
86\
87\
88\
``` ```\
import typing\
from typing import Any, Optional, Text, Dict, List, Type\
from rasa.nlu.components import Component\
from rasa.nlu.config import RasaNLUModelConfig\
from rasa.nlu.training_data import Message, TrainingData\
if typing.TYPE_CHECKING:\
from rasa.nlu.model import Metadata\

class MyComponent(Component):
"""A new component"""
# Which components are required by this component.
# Listed components should appear before the component itself in the pipeline.
@classmethod
def required_components(cls) -> List[Type[Component]]:
"""Specify which components need to be present in the pipeline."""
return []
# Defines the default configuration parameters of a component
# these values can be overwritten in the pipeline configuration
# of the model. The component should choose sensible defaults
# and should be able to create reasonable results with the defaults.
defaults = {}
# Defines what language(s) this component can handle.
# This attribute is designed for instance method: can_handle_language.
# Default value is None which means it can handle all languages.
# This is an important feature for backwards compatibility of components.
language_list = None
def init(self, component_config: Optional[Dict[Text, Any]] = None) -> None:
super().init(component_config)
def train(
self,
training_data: TrainingData,
config: Optional[RasaNLUModelConfig] = None,
**kwargs: Any,
) -> None:
"""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 :meth:components.Component.pipeline_init
of ANY component and
on any context attributes created by a call to
:meth:components.Component.train
of components previous to this one."""
pass
def process(self, message: Message, **kwargs: Any) -> None:
"""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 :meth:components.Component.pipeline_init
of ANY component and
on any context attributes created by a call to
:meth:components.Component.process
of components previous to this one."""
pass
def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:
"""Persist this component to disk for future loading."""
pass
@classmethod
def load(
cls,
meta: Dict[Text, Any],
model_dir: Optional[Text] = None,
model_metadata: Optional["Metadata"] = None,
cached_component: Optional["Component"] = None,
**kwargs: Any,
) -> "Component":
"""Load this component from file."""
if cached_component:
return cached_component
else:
return cls(meta)\


**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.