Creating a Dialogflow ES Text Bot Using Avaya OneCloud CPaaS

Every once in a while, a new technology, an old problem, and a big idea turn into an innovation.

Dean Kamen

In my previous article, Writing a Voice Bot Application Using Avaya CPaaS, I showed you how to use Avaya CPaaS inboundXML elements to create a simple voice bot. Here, I will show you how to do the same for text messages. However, to spice things up a bit, I will integrate the bot with Google DialogFlow ES for intent-based FAQ processing. Unlike my voice bot example, this approach gives me a bot that has no hardcoded responses. DialogFlow performs natural language processing (NLP) on the incoming text message to determine the correct response. This eliminates all the “if this then that” code to provide a much more flexible response engine.

Note: You can build a no-code text bot by using Avaya’s One-Click Dialogflow Integration, but the method in this article give you a platform that can be extended to add all sorts of interesting functionality — database dips, CRM integration, webhooks, etc.

Google DialogFlow

Building the Dialogflow ES Agent is straightforward. All you need to do is create a bunch of intents and responses. For an FAQ bot, I often use the Knowledgebase functionality of Dialogflow to simplify the process. This saves me the effort of having to create individual intents for every dialog interaction. I may still create a few that aren’t strictly FAQish in nature, but that effort can be minimal.

The more involved part is giving an external application programmatic access to the agent. Once you understand what to do it makes sense, but the steps aren’t intuitively obvious — at least they weren’t to me.

I suspect there might be a more efficient way to accomplish this, but my method works. It involves the following steps:

  • Create the DialogFlow ES Agent
  • Click on the gear icon for the Agent
  • Click on the Project ID
  • From the menu on the left side, choose IAM and Admin –> Service Accounts
  • Create a new Service Account
  • Assign the Service Account the following Role:
    • DialogFlow API Admin
  • Select “Manage Keys” for the new Service Account
  • Select ADD KEY –> Create new key –> JSON
  • This creates a credentials file that ends in .json — download it to your target machine

The application needs two items to connect it to the Dialogflow Agent — the Project ID name and the filename of the JSON file (stored on the target machine). After they are set, the application will be able to pass received text to a DialogFlow Agent and receive an Intent Object in return. The fulfillmentText value inside the Intent Object is sent back to CPaaS and ultimately the device that generated the original text.

Got all that? Here is a node.js application that demonstrates CPaaS/Dialogflow integration:

/*

This Avaya CPaaS application accepts incoming SMS text messages and uses
Google Dialogflow ES to generate responses back to the sender.

*/

const express = require('express');
const request = require('request-promise');
const bodyParser = require('body-parser');
const cpaas = require('@avaya/cpaas'); //Avaya cloud
var enums = cpaas.enums;
var ix = cpaas.inboundXml;
const uuid = require('uuid');
const dialogflow = require('dialogflow');

// Create a new Dialogflow sessionClient.
var projectId = "DialogFlow Agent Project Id"; 
var sessionClient = new dialogflow.v2beta1.SessionsClient({
	keyFilename: "Filename of Service Account's JSON credentials" 
}); 
var sessionId = uuid.v4(); // Create random session ID
var sessionPath = sessionClient.sessionPath(projectId, sessionId);

const URL_PORT = xxxx; //UDP Port for application

var app = express();

// Middleware to parse JSON
app.use(bodyParser.urlencoded({
    extended : true
}));
app.use(bodyParser.json());

// Tell server to listen on port
var server = app.listen(URL_PORT, function () {
   var port = server.address().port;
   console.log("SMS Virtual Agent is listening on port %s", port)
});

// Entry point for sms text
app.post('/cpaas-sms/', function (req, res) {
    processText(req.body.From, req.body.To, req.body.Body, res);
});

async function processText(from, to, body, res) {
	var result = await callGoogleIntent(body, sessionPath);
	prompt = result.fulfillmentText;
	returnTextResponse(prompt, from, to, res);
}

async function returnTextResponse(prompt, from, to, res) {
	var xmlDefinition = generateXMLText(from, to, prompt)
    var serverResponse = await buildCPaaSResponse(xmlDefinition);

    res.type('application/xml');
    res.send(serverResponse);
}

function generateXMLText(customer , cpaas , body) {
    var sms = ix.sms({
        text : body ,
        to : customer ,
        from : cpaas
    });

    var xml_content = [];
    xml_content.push(sms);
    var xmlDefinition = ix.response({content: xml_content});
    return xmlDefinition;
}

async function buildCPaaSResponse(xmlDefinition) {
      var result = await ix.build(xmlDefinition).then(function(xml){
          return xml;
      }).catch(function(err){
          console.log('The generated XML is not valid!', err);
      });
      return result;
}

//-----------  Google Dialogflow function

async function callGoogleIntent(speech, sessionPath) {
	const request = {
		session: sessionPath,
		queryInput: {
			text: {
				text: speech,
				languageCode: 'en-US',
			},
		},
	};
	const responses = await sessionClient.detectIntent(request);
	return responses[0].queryResult;
}

In addition to the two DialogFlow values, make sure to set URL_PORT to an available port on your server.


Now that you’ve written and launched the application (I run mine on my Linux server), you need to attach it to the SMS webhook of a CPaaS number. Mine looks like this:

Once you’ve completed this step, you should now be able to send text messages to your CPaaS number and receive responses from your Dialogflow-enabled text bot.

If you want to experience my version of the bot in action, simply send text messages to 289-205-0780. My Dialogflow agent supports all kinds of questions about Avaya CPaaS along with some small talk functions (“I love you”). Here are a few of the phrases it supports. Since I am using NLP, you can rephrase them in many different ways.

How long does it take to port a number?

What is the default SMS filtering?

How do I get an account?

How old are you?

Good morning.

Where can I find the pricing list of supported companies?

I can’t guarantee how long the bot will be up and running, but it’s working now.

Mischief Managed

That’s all there is to it. Granted, this is a simple FAQ bot that could have been created without having to write code, but you now have a framework that can be extended far beyond basic interactions.

Additionally, it wouldn’t be too difficult to take the Dialogflow code from this application and integrate it with the voice bot example in Writing a Voice Bot Application Using Avaya CPaaS. This removes all the hardcoded “it this then that” processing and replaces it with a powerful natural language processing engine.

As always, feel free to reach out to me with any questions you might have. I am happy to help.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: