Skip to content

Simple Rule

The SimpleRule can be used to define basic dialog rules. In principle, it can be used with any condition but it is recommended to use it with the PatternCondition.

Example

Example Code

The complete, runnable code for this example can be found in the repository StepDP-Basic-Examples. There, the example is called HelloWorldExample. The documentation only includes the most relevant code snippets.

Let's define a simple rule that reacts on tokens with a greeting intent by printing a greeting to the console. To illustrate how we can access and use information from tokens, let's assume that the greeting token contains the name of the user that uttered the greeting.
First, we define the type GreetingIntent with the String property "userName" in our semantic tree:

Type greetingIntent = new Type("GreetingIntent", this.getKB());
greetingIntent.addProperty(new PropString("userName", this.getKB()));
this.getKB().addType(greetingIntent);

Now, we define the actual rule:

Rule greetingRule = new SimpleRule(tokens -> {
    IToken t = tokens[0];
    if (!t.isSet("userName")) {
        System.out.println("Hello! What's your name?");
    } else {
        String userName = t.getString("userName");
        System.out.println("Hello, nice to meet you, " + userName + "!");
    }
}, "GreetingRule");
Pattern p = new PatternBuilder("GreetingIntent", this.getKB()).build();
greetingRule.setCondition(new PatternCondition(p));
this.getBlackboard().addRule(greetingRule);

We use a lambda expression to define what the rule should do with incoming tokens. The input to the lambda expression is an array of tokens. For most dialog rules, this array will only contain one token but there might be certain rules (e.g. fusion) that take more than one token as input.
We also need to set a condition for the rule that defines which tokens should trigger it. For that purpose, we can use a PatternCondition with a pattern that matches all tokens with type "GreetingIntent". To find out more about the PatternCondition, refer to the section Pattern Condition.
Finally, we need to add the rule to the blackboard, which is responsible for executing the rules.

Multiple matches

If more than one token (or token combination) matches the condition, the SimpleRule will take the first token (token combination) that the condition returns.