How to use tracker in a custom class and call custom function in an action class?

I would like to use tracker in my custom actions. The tracker works well for the class taking Action as its parameter. However, Can I use tracker in my self-defined classes which are not taking Action/ FormAction as parameter?

Besides, can I add new function into the an action class? For example, if I define a function sum() in class ActionCalculation(Action), there will be an error saying “name ‘sum’ is not defined”. What can I to with this?

Thank you.

Hi there,

Does not mean that Action is the parameter of ActionCalculation! it means that ActionCalculation inherits from Action class.

The entry point of your ActionCalculation is run(), inside this function you can call your custom function sum().

Hi @cwying817, custom actions need to inherit from Action (CustomAction(Action)), and if you want to use the tracker it has to be in an action’s run() method. You can perform other calculations in your custom action. Here’s an example using a function called get_sum():

from rasa_core_sdk import Action
from rasa_core_sdk.events import SlotSet

def get_sum(x, y):
    return x + y

class CustomAction(Action):
   def name(self):
      # type: () -> Text
      return "custom_action"

   def run(self, dispatcher, tracker, domain):
      # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict[Text, Any]]

      a = tracker.get_slot('value_a')
      b = tracker.get_slot('value_b')

      result = get_sum(a, b)
      
      print("Do something with result {}".format(result))

      return [SlotSet("result", result)]
1 Like