DEV Community

Committed Software
Committed Software

Posted on • Originally published at committed.software on

Conversational Bots With Dialogflow

Building Conversational Bots With Dialogflow

Conversational bots are becoming increasingly popular, with AI assistants available on most mobile phones, devices like the Amazon Alexa and Google Home and in various chat applications like Slack and Facebook Messenger. However, developing conversational bots can produce a number of problems:

  • Speech recognition to understand a spoken user request.
  • Extracting query parameters contained within a query.
  • Understanding the intent of a query to determine the correct action.
  • Generating an appropriate response for the query.
  • Integration with a growing number of assistant devices or chat applications.

Each platform usually has their own suggested approach for developers creating chatbots, for example Slack offers various APIs and suggests the use of JS libraries like “Botkit”, whilst Amazon offer the “Alexa Skills Kit” and “AWS Lambda functions”. Ideally, we don’t want to support multiple solutions for each device, so how can we write a conversational bot once whilst integrating with a variety of platforms?

Dialogflow

Google’s Dialogflow platform provides us with a suitable solution; handling query parsing, parameter extraction, intent detection and offering easy integrations with a variety of common applications.

Intents

Dialogflow allows us to define different Intents which it will match incoming queries to. We define examples of phrases that would trigger our intent and Dialogflow will use these to train a model used in query recognition. The more example queries provided, the more accurate the query recognition will be.

We can also state the parameters that should be extracted from each request. For each parameter, we specify its name, type and default value. Dialogflow offers a number of existing types for common types like numbers, dates or locations whilst also allowing us to define our own entity types.

We state if each parameter is required, and we can also provide prompts to be used when a user does not provide all the required parameters. In the example above, the question regarding lunch requires a FoodType parameter.

User: “Where should I go for lunch?”

Bot: “Any preferences?”

User: “A burger”

Dialogflow automatically handles these parameter filling exchanges, in a conversational manner utilising our provided prompts, before proceeding to build a response.

Response Creation

Once a user’s Intent has been determined we need to provide a response for their request. Dialogflow allows us to provide basic text responses in the browser, with specific responses for different platforms like Google Assistant or Slack.

However, we probably want to provide a customised response, and for this Dialogflow offers integration with Firebase Cloud Functions. Once again it allows us to edit and deploy this function completely within the browser. Dialogflow provides us with a templated function to edit, in this function we write our request fulfilment code and provide Dialogflow with a map stating the functions to be called to handle each Intent.

For each Intent handler, we can use the provided request to extract specific parameters and build a custom response. We can also detect the request source, so that we can build a response specific to that platform, for example adding Cards to a Google Assistant response, or making use of Slack’s styled responses.

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function lunchHandler(agent) {
    var source = request.body.originalDetectIntentRequest ? request.body.originalDetectIntentRequest.source : undefined

    // Your code here - using request.body parameters to build a response

    switch(source){
        case 'slack': buildSlackResponse(agent); break;
        case 'google': buildGoogleAssistantResponse(agent); break;
        default: agent.add("Default response"); break;
    }

    // Add context for chained intents to use
    agent.setContext({ name: 'preference', lifespan: 2, parameters: { foodType: 'burger' }});
  }

  function buildSlackResponse(agent){
      // Building slack specific response
  }

  function buildGoogleAssistantResponse(agent){
      // Building Google Assistant cards
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Lunch Intent', lunchHandler)
  agent.handleRequest(intentMap);
});

We may want to make an asynchronous request from within our cloud function, calling an API or requesting data from a data store to populate a response. In this case, Dialogflow allows us to return a Promise from our intent handler function. Dialogflow will wait for the Promise to resolve before processing the agent response.

function lunchHandler(agent) {
    return Promise.resolve(someAsyncRequest()
      .then(function (res) {
        agent.add("Here is a service specific response")
      })
      .catch(function (err) {
        console.log(err.stack)
        agent.add('Sorry, the service is not available right now')
      })
    );
}

Integrations

One of the main advantages of Dialogflow is its application integrations. Dialogflow offers simple integration with Google Assistant, Facebook Messenger, Slack, Twitter, Alexa, Skype and more. In most cases, these integrations are very simple to set up, with many being a case of activating the integration and providing a set of credentials required for the two services to communicate. In each case, Dialogflow provides a simple set of steps to follow to set up the integration.

Once an integration is setup, any query requests from that platform are forwarded to Dialogflow for processing and results are returned, all requests from each platform are all handled by the same underlying service.

Wrapping Up

Dialogflow is incredibly easy to use, conversational bots providing basic responses can be created entirely within the browser, without having to download or setup any development kits or having to write a single line of code. A user only requires any programming knowledge once they need to produce complex responses.

Its many integrations truly seem to be its main advantage, allowing the developer to have one single service support a wide range of clients provides a maintainable solution. Every request is handled by the same parsing service and parameter extraction, leaving the developer to only be concerned with producing a suitable user response.

As with most fits all solutions, Dialogflow does have its drawbacks. Many applications offer differing features within their chatbots, and supporting a large number of integrations may mean that some of these platform specific features cannot be taken advantage of. For example, at the moment of writing this, there are issues with the Slack integration and responding to direct @Bot mentions.

However, Dialogflow is constantly being updated and improved, new features are gradually being implemented and so these issues may be addressed over time.

Credit: Blog photo by “Ben Kolde” on “Unsplash”

Top comments (0)