How we transformed our Chatbot language to a state-machine DSL
Tags: chatbots, statemachine, dsl, bots
Published: 2020-04-29 19:02:27

Nothing better to eat your own dog food to understand how you need to improve your tool to better serve your customers. At [Xatkit](https://xatkit.com/), we have started to create a number of bot projects (including the very friendly <a href="https://xatkit.com/" target="_blank" rel="noopener noreferrer">Xat</a> that you see on our home page). This helped us to realize that our current bot definition language had to undergo a major change if we wanted to:
<ol>
 	<li>Simplify the creation of bots requiring complex conversational flows.</li>
 	<li>Maximize the reusability opportunities, advancing towards creating bots by reusing building blocks and conversation paths already defined in the past</li>
</ol>
This wasn't easy in the "old language version" as the <em>intents</em> definition was mixed with partial order constraints to restrict the freedom in the conversation path. That was enough when dealing with "open" bots (FAQ style bots) where most of the questions are independent and are always available but not when dealing with more "closed" bots where the potential conversations are much more restricted (think of a bot to order food from a website).

To bring the capabilities of our chatbot definition language to the next level we have moved to<strong> a DSL closer to <a href="https://en.wikipedia.org/wiki/Finite-state_machine" target="_blank" rel="noopener noreferrer">state machine semantics</a> </strong>and completely decoupled the intent definition from the transition rules that control what intents are available at any given point of the bot execution. This brings the following key benefits:
<ul>
 	<li>You can now <strong>reuse previous intents in new bots</strong> even if the new bot is implementing different conversation paths.</li>
 	<li>You can use all the power of the state machine formalism to<strong> define very complex conversation flows while keeping a clear and precise semantics for the bot</strong>.</li>
 	<li>Create very <strong>complex guards in transitions</strong>. Move the bot to a new state based on the user input, coming events but also conditions on previous data, parameters of the conversation,...</li>
 	<li>Place <strong>complex conversation logic</strong> to respond to user requests using the state body.</li>
 	<li><strong>Modularize the bot</strong>. Reuse parts of the state machine in other bots.</li>
 	<li>Possibility to define <strong>local fallbacks</strong> as part of the state behaviour. Beyond a default global fallback, you can now attach local fallbacks to states that let you handle errors within the state context (e.g. to show a message helping the user to respond to the question posed by the bot in the specific state the conversation is in).</li>
</ul>
Convinced already?. Great!. Let us show a glimpse of what the new language looks like.
<h2>Intent definition language</h2>
The intent definition remains a separate sublanguage but not even more decoupled from the execution part. Now, for each intent, we just define the set of training sentences for the intent and collect the parameters from the user utterance we want to save with the intent.

See the following example where we have a simple bot that just recognizes two types of user utterances (greetings and stating the name):
<pre lang="java" line="1">intent Hello {
  inputs {
    "Hi"
    "Hello"
  }
}

intent MyNameIs {
  inputs {
    "My name is NAME"
    "I'm NAME"
    "Call me NAME"
  }
  creates context Greetings {
    set parameter name from fragment "NAME" (entity any)
  }
}
</pre>
For each intent, we show a couple of training sentences to teach the bot how to recognize them. Moreover, see how we collect the <code>NAME</code> parameter in a <em>context</em> to use it later on (e.g. to answer to the user in a more personalized way).

At this point, we are not stating what intent the bot should try to match first, this is something that belongs to the execution DSL we're going to see just next. This enables us to reuse the intents (for example, in another bot where we may also need to ask for the user's name but not just after a greeting intent).
<h2>Execution definition language</h2>
The execution file now defines a state machine that describes both the bot reactions to the intents/events and the potential transitions between them. Bot <strong>designers can now look at the execution file and have an idea of the entire conversation flow</strong>.
<div>Each state in the execution language contains 3 sections</div>
<ul>
 	<li><strong>Body </strong>(<em>optional</em>): the bot reaction, executed when entering the state.</li>
 	<li><strong>Next </strong>(<em>mandatory</em>): the outgoing transitions defined as <em>condition --&gt; State. </em>The conditions are evaluated when an event/intent is received, and if a transition is navigable the execution engine moves to the specified state (and executes its body, etc). Note that <strong>transition conditions can be as complex as you want. </strong> And they are real guards, meaning that if the entire condition is not true the transition is not navigable, and the engine will stay in the same state.</li>
 	<li><strong>Fallback </strong>(<em>optional</em>): <strong>local fallbacks made easy.</strong> This section can contain arbitrary code (as the <em>Body </em>section) that will be executed if the engine cannot find a navigable transition.</li>
</ul>
<div>An execution model also contains 2 special states:</div>
<ul>
 	<li><strong>Init</strong>: a regular state that is entered when the user session is created. It can contain a <em>Body</em>, <em>Next</em>, and <em>Fallback </em>section.</li>
 	<li><strong>Default_Fallback</strong>: a state that can <strong>only contain a Body section</strong>, and cannot be the target of a transition. This state represents the default fallback code to execute when there is no local fallback defined in a state. This state can be used to print a generic error message (<em>"Sorry I didn't get it</em>"), while local fallback can print a custom message tailored to the current state ("<em>Please reply by yes or no</em>").</li>
</ul>
Finally, states can define a <strong>single wildcard transition</strong> (using the reserved character <em>_</em> as the transition condition) that will be automatically navigated when the state's body has been computed. This allows us to <strong>modularize the execution logic</strong> and reuse the same code in multiple places. See the detailed example below that shows a simple bot that just replies to the Hello intent above, asks for the user name and says hello to her (this example bot is supposed to be displayed via our <a href="https://github.com/xatkit-bot-platform/xatkit-chat-widget" target="_blank" rel="noopener noreferrer">React-based chat widget</a>):
<pre lang="java" line="1">//We can always have an init state in case we need to initialize some bot parameters (e.g. welcoming message)
Init {
  Next { 
    //Here we state that the bot will first listen for an utterance matching the Hello intent, it will ignore anything else
    intent == Hello --> HandleHello  
  }
}
HandleHello {
  Body {
     ReactPlatform.Reply("Hi, what's your name?")
  }
  Next {
    //We wait for the user to input the name, no other transition is possible at this point
    //Obviously, in more complex bots we may have several possible outgoing transitions in a given state
    intent == MyNameIs --> HandleMyNameIs
  }
}
HandleMyNameIs {
  Body {
    ReactPlatform.Reply("Hi " + context.get("Greetings").get("name"))
  }
  Next {
    // An automatic transition to the Init state since at this point the conversation is finished and we can start again
    _ --> Init
  }
}
// Default Fallback state could go here

</pre>
I hope you are as excited as we are with this new version of the language. And we are grateful to language version 1 to have been a wonderful learning tool to understand what we needed to create a much better chatbot creation experience for you!.

Remember that Xatkit is an open source (chat)bot platform. So feel free to take a look at [our GitHub repo](https://github.com/xatkit-bot-platform/xatkit) and give Xatkit a try!.