| Previously published on Medium, Jan2019 |
Smart speakers have seen phenomenal growth over the last few years and devices such as Amazon Echo and Google Home have been one of the top gift items this holiday season. This year alone, Amazon has shipped over 20 million Echo devices. Part of the reason for Amazon’s success in this space is its extensible Alexa voice assistant and the associated Skills. There are now over 70,000 skills available worldwide. In addition to adding new functionality to the voice assistant, Alexa Skills enable the devices to call external services such as ride-sharing and music streaming apps. This enables voice interface to be added to virtually any application. In this article we will look at adding voice user interface capability to the ServiceNow ITSM application.
ServiceNow is the leading IT Service Management and IT Operations Management platform that provides capabilities for enterprises to manage their IT infrastructure and services. It is an extensible SaaS platform, integrating easily with third party applications through open interfaces, offering great potential in building the latest AIOps, ChatOps and voice-enabled applications for enterprise management.
We will build a simple skill that queries a ServiceNow instance for most recent tickets and plays them back. The figure below shows the overview of the skill.
When the skill is invoked, Alexa triggers an AWS Lambda function to process the command or Intent. The Lambda function in turn calls the REST API to query the appropriate ServiceNow table and retrieves the relevant records. The records returned are then played back through the Echo device. The skill uses Account Linking to authenticate the skill user with ServiceNow.
Prerequisites
We need to perform some preparatory work in order to get started.
Node.js and npm
We will use Node.js to implement our Lambda function. So we need to install Node.js and npm to build the dependencies locally before deploying the code to AWS Lambda. You will need Node.js version 6.10 or later.
AWS account
This will be needed to run the Lambda function. If you do not have an AWS account, you can register for a free-tier account at https://aws.amazon.com/free. CAUTION: You may incur charges if you are not using the free-tier.
IAM user and policy
In the AWS console create an IAM user and attach the following policy to it.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iam:CreateRole",
"iam:GetRole",
"iam:AttachRolePolicy",
"iam:PassRole"
],
"Resource": "arn:aws:iam::*:role/ask-*"
},
{
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:CreateFunction",
"lambda:GetFunction",
"lambda:UpdateFunctionCode",
"lambda:ListFunctions"
],
"Resource": "arn:aws:lambda:*:*:function:alexa-servicenow"
}
]
}
Make a note of the user’s access key and secret key. You will need these to configure the AWS CLI environment further on.
Amazon developer account
An Amazon developer account is required to create and configure skills. You can create one at https://developer.amazon.com. We will use Alexa Skills Kit SDK v2.
AWS CLI
The AWS CLI is used during skill deployment by the ASK CLI. Install it as follows.
$ pip install awscli --upgrade --user
More details can be found at https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html.
Configure the CLI as follows:
$ aws configure
AWS Access Key ID [None]: <Your_Access_Key>
AWS Secret Access Key [None]: <Your_Secret_Access_Key>
Default region name [None]: eu-west-2
Default output format [None]: json
ASK CLI
Although skills can be developed using the console, we will use the command line interface. ASK CLI is a Node.js package, installed as follows.
$ npm install -g ask-cli
Configure the CLI tool as follows.
$ ask init
? Please create a new profile or overwrite the existing profile.
Create new profile
? Please type in your new profile name:
default
-------------------- Initialize CLI --------------------
Setting up ask profile: [default]
? Please choose one from the following AWS profiles for skill's Lambda function deployment.
alexa-dev
This will open a browser window and prompt you to log into your Amazon account.
ServiceNow developer instance
You can sign up for a developer instance at https://developer.servicenow.com. You will receive a personal sandbox environment of the form devNNNNN.service-now.com.
Alexa companion app
This is required to authenticate the skill user with ServiceNow, once Account Linking has been configured. Install the app on your phone from the Android or Apple store.
Download code
The code for the skill is available at https://github.com/sanjayraina/alexa-servicenow. It contains the following files.
.ask/config — deployment configuration
skill.json — the skill configuration
models/en-GB.json — the interaction model
lambda/custom/index.js — core lambda function
lambda/custom/constants.js — constants used in the code
lambda/custom/package.json — package dependencies
Interaction Model
The definition of the interaction model is contained in skill.json and en-GB.json. Alexa voice interactions work by decomposing speech into words and phrases that are sent to Alexa Voice Service (AVS) and an AWS Lambda function to be processed. The interaction schema is described in models/en-GB.json.
Invocation
Invocations are used to launch the skill. Our skill uses the following invocation.
Wake word initiates a new session. Launch “opens’ the skill and the invocation name identifies the skill.
Utterance
Utterances define the dialog in the skill and include phrases that get mapped onto Intents. Utterances can also include Slots that can take “variable” values. In our skill, sample utterances are of the form:
Intents
Intents define the goal or action that is to be accomplished by a voice exchange. There is only one custom Intent in our skill.
{
"name": "ServiceNowIntent",
"slots": [{
"name": "Tickets",
"type": "TICKETS"
}],
"samples": ["Read out the recent {Tickets}"]
}
It has one slot called Tickets, that can take values such as Incidents, Changes, Problems etc.
Lambda Function
The Lambda function contains handlers to process the launch request and intents.
Launch Request Handler
The handler simply plays a greeting and awaits a response to trigger an intent. It also retrieves the access token from the request, to be used later in the Intent handler. The access token is provided by ServiceNow on authentication, once Account Linking has been enabled.
const speechText = 'Welcome to the ServiceNow skill, how can I help?';
accessToken = handlerInput.requestEnvelope.session.user.accessToken;
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.getResponse();
Intent Handler
The handler contains code to determine the slot value and then to make the appropriate REST API request to the ServiceNow instance.
The slot value is obtained from the request envelope to determine which table in the ServiceNow instance to retrieve the records from.
const filledSlots = handlerInput.requestEnvelope.request.intent.slots;
const ticketType = filledSlots.Tickets.value;
Next, the handler makes a GET request as follows.
const options = {
hostname: snowInstance,
port: 443,
path: '/api/now/table/' + recType +
'sysparm_query=ORDERBYDESCsys_updated_on&sysparm_limit=5',
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: hdrAuth
}
};
const request = https.request(options, (response) => {
...
The returned records are then assembled into speech text as follows.
let speechText = "Here are the 5 most recent " + ticketType + ": ";
for (let i = 0; i < 5; i++) {
var rec_number = i + 1;
speechText += "Record " + (i+1) + '<break time=".5s"/>'
+ records.result[i].short_description + ". ";
}
speechText += '<break time=".5s"/>' + "End of " + ticketType + ".";
Notice the extra pauses added with the “break time” markup.
Account Linking with ServiceNow
External client applications that access ServiceNow need to be authenticated. To achieve this, an OAuth endpoint needs to be created in ServiceNow so that it can generate a token on authentication.
The above identity is used when setting up Account Linking to enable the Alexa Skills user to authenticate and connect to ServiceNow.
Skill Deployment
Ensure that all the prerequisite steps have been completed. Perform the following steps to deploy the code.
Clone or download code from Github repository:
$ git clone https://github.com/sanjayraina/alexa-servicenow.git
$ cd alexa-servicenow
Amend constants.js with the name of your instance:
exports.servicenow = {
instance: 'devNNNNN.service-now.com',
};
Download the skill dependencies:
$ cd lambda/custom; npm install
Deploy the skill and lambda function with ASK CLI:
$ ask deploy
Once the code is deployed, the next step is to setup Account Linking and authentication with ServiceNow.
Create OAuth API Endpoint in ServiceNow.
Log in to your ServiceNow developer instance at devNNNNN.service-now.com. Navigate to System OAuth →Application Registry.
Click on New to create a new Endpoint and fill out the fields as follows:
Name: Alexa Skill Test
Redirect URL: https://layla.amazon.com/api/skill/link/M26D1D2CM95YM6
Client Id will be filled out automatically and Client Secret will be generated automatically once the form is saved.
Now we need to link the Amazon developer account with ServiceNow using the Endpoint and credentials created above.
Head over to your Amazon developer account at developer.amazon.com and log in.
Navigate to your newly deployed skill and click on Account Linking on the left to open the Account Linking form.
Turn on account linking using the first toggle button at the top and fill out the details from your ServiceNow OAuth Endpoint.
Select an authorization grant type: Auth Code Grant
Authorization URI: https://devNNNNN.service-now.com/oauth_auth.do
Access Token URI: https://devNNNNN.service-now.com/oauth_token.do
Client Id: <As generated by ServiceNow above>
Client Secret: <As generated by ServiceNow above>
Save the form.
Finally, open the Alexa app on the phone and authenticate the linked account.
Enter your ServiceNow credentials when prompted to login. A message will appear asking your permission to link the accounts. Press “Allow” to proceed and complete the Account Linking set up.
Deployment and setup is now complete.
Take it for a spin
Now that we have the skill deployed, let’s try it out.
Make sure that the Skill has been linked with ServiceNow using the companion phone app. You will need to login with your ServiceNow user credentials.
You should now be able to initial a dialog with your Echo device.
You: “Alexa, open ServiceNow”
Alexa: “Welcome to the ServiceNow skill. How can I help?”
You: “Tell me the recent incidents”
Alexa: “Here are the 5 most recent incidents…”
Comments