Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored Code to support Assistant V2 #6

Merged
merged 2 commits into from Dec 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
@@ -1,5 +1,5 @@
# Environment variables
WORKSPACE_ID=
ASSISTANT_ID=
# You need to provide either username and password
ASSISTANT_USERNAME=
ASSISTANT_PASSWORD=
Expand Down
8 changes: 6 additions & 2 deletions README.md
Expand Up @@ -14,6 +14,10 @@

You can view a [demo][demo_url] of this app.

Please note this app uses the [Watson Assistant V2 API](https://console.bluemix.net/apidocs/assistant-v2#introduction). To access a version of the V1 app, you can go to [v1.1.0](https://github.com/watson-developer-cloud/assistant-intermediate/releases/tag/v1.1.0).

If you need more information about the V1 API, you can go to the [Watson Assistant V1 API page](https://cloud.ibm.com/apidocs/assistant#introduction).


## Prerequisites

Expand Down Expand Up @@ -83,10 +87,10 @@ You can view a [demo][demo_url] of this app.
ASSISTANT_IAM_URL=https://gateway-syd.watsonplatform.net/assistant/api
```

8. Add the `WORKSPACE_ID` to the previous properties
8. Add the `ASSISTANT_ID` to the previous properties

```
WORKSPACE_ID=522be-7b41-ab44-dec3-g1eab2ha73c6
ASSISTANT_ID=522be-7b41-ab44-dec3-g1eab2ha73c6
```

## Running locally
Expand Down
96 changes: 68 additions & 28 deletions app.js
Expand Up @@ -18,7 +18,7 @@

var express = require('express'); // app server
var bodyParser = require('body-parser'); // parser for post requests
var AssistantV1 = require('watson-developer-cloud/assistant/v1'); // watson sdk
var AssistantV2 = require('watson-developer-cloud/assistant/v2'); // watson sdk

var Actions = require('./functions/actions');
var actions = new Actions();
Expand All @@ -33,59 +33,87 @@ app.use(express.static('./public')); // load UI from public folder
app.use(bodyParser.json());

// Create the service wrapper

var assistant = new AssistantV1({
version: '2018-07-10'
var assistant = new AssistantV2({
version: '2018-11-08'
});
var date = new Date();
date.setMonth(date.getMonth() + 1);
var accountData = {
acc_minamt: 50,
acc_currbal: 430,
acc_paydue: date.getFullYear() + '-' + (date.getMonth() + 1) + '-26 12:00:00',
accnames: [
5624,
5893,
9225,
],
private: {
function_creds: {
user: process.env.CLOUD_FUNCTION_USER,
password: process.env.CLOUD_FUNCTION_PASS,
},
var newContext = {
global : {
system : {
turn_count : 1
}
},
skills: {
'main skill': {
user_defined: {
acc_minamt: 50,
acc_currbal: 430,
acc_paydue: date.getFullYear() + '-' + (date.getMonth() + 1) + '-26 12:00:00',
accnames: [
5624,
5893,
9225,
],
private: {
function_creds: {
user: process.env.CLOUD_FUNCTION_USER,
password: process.env.CLOUD_FUNCTION_PASS,
},
}
}
}
}
};

// Endpoint to be call from the client side
app.post('/api/message', function (req, res) {
var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
if (!workspace || workspace === '<workspace-id>') {
var assistantId = process.env.ASSISTANT_ID || '<assistant-id>';
if (!assistantId || assistantId === '<assistant-id>') {
return res.json({
'output': {
'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' + '<a href="https://github.com/watson-developer-cloud/assistant-intermediate">README</a> documentation on how to set this variable. <br>' + 'Once a workspace has been defined the intents may be imported from ' + '<a href="https://github.com/watson-developer-cloud/assistant-intermediate/blob/master/training/banking_workspace.json">here</a> in order to get a working application.'
'text': 'The app has not been configured with a <b>ASSISTANT_ID</b> environment variable. Please refer to the ' + '<a href="https://github.com/watson-developer-cloud/assistant-intermediate">README</a> documentation on how to set this variable. <br>' + 'Once a workspace has been defined the intents may be imported from ' + '<a href="https://github.com/watson-developer-cloud/assistant-intermediate/blob/master/training/banking_workspace.json">here</a> in order to get a working application.'
}
});
}

var contextWithAcc = Object.assign({}, req.body.context, accountData);
var contextWithAcc = (req.body.context) ? req.body.context : newContext;

if (req.body.context) {
contextWithAcc.global.system.turn_count += 1;
}

//console.log(JSON.stringify(contextWithAcc, null, 2));

var textIn = '';

if(req.body.input) {
textIn = req.body.input.text;
}

var payload = {
workspace_id: workspace,
context: contextWithAcc || {},
input: req.body.input || {}
assistant_id: assistantId,
session_id: req.body.session_id,
context: contextWithAcc,
input: {
message_type : 'text',
text : textIn,
options : {
return_context : true
}
}
};

// Send the input to the assistant service
assistant.message(payload, function (err, data) {
if (err) {
return res.status(err.code || 500).json(err);
}
actions.testForAction(data).then(function (d) {
actions.testForAction(data, req.body.session_id).then(function (d) {
return res.json(d);
}).catch(function (error) {
return res.json(error);
});

});
});

Expand All @@ -105,4 +133,16 @@ app.get('/bank/locate', function (req, res) {
res.send({ result: 'zip123retrieved' });
});

app.get('/api/session', function (req, res) {
assistant.createSession({
assistant_id: process.env.ASSISTANT_ID || '{assistant_id}',
}, function (error, response) {
if (error) {
return res.send(error);
} else {
return res.send(response);
}
});
});

module.exports = app;
4 changes: 2 additions & 2 deletions casper-runner.js
Expand Up @@ -16,9 +16,9 @@

require('dotenv').config({ silent: true });

if (!process.env.WORKSPACE_ID) {
if (!process.env.ASSISTANT_ID) {
// eslint-disable-next-line
console.warn('Skipping casper tests because WORKSPACE_ID is null');
console.warn('Skipping casper tests because ASSISTANT_ID is null');
return;
}

Expand Down
23 changes: 11 additions & 12 deletions functions/actions.js
Expand Up @@ -19,24 +19,23 @@ function actions() {

var http = require('http');

this.testForAction = function (data) {
this.testForAction = function (data, sessionId) {
return new Promise(function (resolve, reject) {
if (data.hasOwnProperty('actions')) {
//console.log(JSON.stringify(data.actions, null, 2));
data.actions.forEach(function (action) {
if (data.output.hasOwnProperty('actions')) {
data.output.actions.forEach(function (action) {
var endPoint = '';
var value = '';
var sendType = '';
if (action.name === 'ValidateAcc') {
endPoint = '/bank/validate';
value = action.parameters.chosen_acc;
sendType = action.result_variable;
bankCalls(endPoint, value, sendType, data, resolve, reject);
bankCalls(endPoint, value, sendType, data, sessionId, resolve, reject);
} else if (action.name === 'RetrieveZip') {
endPoint = '/bank/locate';
value = action.parameters.zip_value;
sendType = action.result_variable;
bankCalls(endPoint, value, sendType, data, resolve, reject);
bankCalls(endPoint, value, sendType, data, sessionId, resolve, reject);
}
});
} else {
Expand All @@ -45,10 +44,9 @@ function actions() {
});
};

function bankCalls(endPoint, value, sendType, data, resolve, reject) {
function bankCalls(endPoint, value, sendType, data, sessionId, resolve, reject) {
// construct the endpoint based on which client action
var parameterizedEndpoint = endPoint + '?value=' + value;

http.get({
path: parameterizedEndpoint,
port: process.env.PORT || 3000,
Expand All @@ -57,7 +55,7 @@ function actions() {
}
}, function (resp) {
resp.on('data', function (res) {
sendMessage(JSON.parse(res), value, sendType, data.context, resolve, reject);
sendMessage(JSON.parse(res), value, sendType, data.context, sessionId, resolve, reject);
});
resp.on('end', function () {
});
Expand All @@ -66,14 +64,15 @@ function actions() {
});
}

function sendMessage(res, value, sendType, context, resolve, reject) {
function sendMessage(res, value, sendType, context, sessionId, resolve, reject) {
var parameterizedEndpoint = '/api/message';

var payloadToWatson = {
'context': context
'context': context,
'session_id': sessionId
};

payloadToWatson.input = {};
payloadToWatson.input = {text : ''};

if (sendType === 'input.text') {
payloadToWatson.input.text = res.result;
Expand Down
18 changes: 12 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -22,7 +22,7 @@
"body-parser": "^1.18.3",
"dotenv": "^6.1.0",
"express": "^4.16.4",
"watson-developer-cloud": "^3.13.0"
"watson-developer-cloud": "^3.13.1"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
Expand Down