How to count the words in user utterance

Hey Rasa team and Rasa comunity, In my chatbot, I need to count the words in the user utterance and use it in my actions. For example, if the user says: “transfer money”, I would need to have user_utterance_length = 2, and if the user says: “how can I send some cash to my friend?”, I would need to set the user_utterance_length to 9. any ideas on how I can access this in Rasa? Cheers Mina

Do you need this functionality while in a form, or in all user messages?

You can get the message with message = tracker.latest_message['text'] in your actions. Then use the functions split and len.

1 Like

I need it in all actions and bot utterances.

Then I think what you need is a custom component:

Which you can add in your pipeline.

1 Like

An example of a component I have written:

from typing import Text, Any, Optional, Dict
from rasa.nlu.components import Component
try:
    from rasa.nlu.training_data import Message
    from rasa.nlu.constants import (
        ENTITIES,
        INTENT,
        TEXT,
    )
except Exception as e:
    from rasa.shared.nlu.training_data.message import Message
    from rasa.shared.nlu.constants import (
        ENTITIES,
        INTENT,
        TEXT,
    )

logger = logging.getLogger(__name__)

class LanguageDetection(Component):
    """Identify the input language"""

    def process(self, message: Message, **kwargs: Any) -> None:
        """Fix input, add language slot."""
        text = message.get(TEXT)
        if text:
            # message.set(TEXT, text)
            lang = predict([text])
            entities = message.get(ENTITIES, [])
            entities.append({
                "start":      0,
                "end":        len(message.get(TEXT)),
                "value":      lang,
                "entity":     "language",
                "extractor":  "LanguageDetection",
                "confidence": 0.8,
                "processors": []
            })
            message.set(ENTITIES, entities, add_to_output=True)
1 Like

I have put the file in a folder named packages, and in the pipeline I call it as:

pipeline:

  • name: packages.LanguageDetection.LanguageDetection
1 Like

@petasis Hey Georg, thanks a lot for sharing your solution. I had no idea about the possibility of creating custom components. I think this is exactly what I need for the solutions I am developing for my master thesis.