Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
e952f42
added routeByEntities flag
offerakrabi Oct 23, 2018
cd12100
added routeByEntities flag
offerakrabi Oct 23, 2018
c631c4c
added validiy check for setRoutingByEntities
offerakrabi Oct 24, 2018
0264964
removed exception
offerakrabi Oct 28, 2018
1749467
Merge pull request #56 from Watson-Personal-Assistant/offer_#1152_rou…
offerakrabi Oct 28, 2018
a1ac9d7
updated to work with apikey
offerakrabi Oct 31, 2018
a1524ca
changed conversation to assistant
offerakrabi Oct 31, 2018
6ab6fc3
fix instancination function
offerakrabi Oct 31, 2018
23800f1
small bug fix
offerakrabi Oct 31, 2018
79c2f27
fixes
offerakrabi Oct 31, 2018
2e0f15e
small bug fix
offerakrabi Nov 1, 2018
bba0b17
small bug fix
offerakrabi Nov 1, 2018
b04494e
changes from review
offerakrabi Nov 1, 2018
533cdf8
added small fix
offerakrabi Nov 1, 2018
cf4ec12
Merge pull request #57 from Watson-Personal-Assistant/offer_#1198_wcs…
Nov 1, 2018
220a344
Updated version to 0.0.17 (WAS Nov Release)
gaynell-gonsalves Nov 6, 2018
24196c1
saved built in context
offerakrabi Nov 6, 2018
dfee6f6
updated swagger
offerakrabi Nov 7, 2018
0141d90
updated swagger
offerakrabi Nov 7, 2018
1ec3d89
Merge pull request #62 from Watson-Personal-Assistant/offer_#242_miss…
erezbi Nov 8, 2018
858767a
Merge pull request #61 from Watson-Personal-Assistant/offer_#1189_del…
erezbi Nov 8, 2018
f08a9f3
updated response and evaluateResponse objects
offerakrabi Nov 12, 2018
d3ffa30
updated response and evaluateResponse objects
offerakrabi Nov 12, 2018
0f25420
added placeholder for context validation functions in handler
offerakrabi Nov 13, 2018
fda5d8a
added get/set/validate functions for built-in context
offerakrabi Nov 13, 2018
3de4fd8
added delete functino
offerakrabi Nov 14, 2018
404d7d5
updated error messages
offerakrabi Nov 14, 2018
bd0f231
small fixes
offerakrabi Nov 14, 2018
a1a917b
updates from code review
offerakrabi Nov 19, 2018
3c35b41
changed builtIn to lowercase
offerakrabi Nov 20, 2018
774d25c
added threshold to evaluation response
offerakrabi Nov 20, 2018
cb86a74
changes requested in code review
offerakrabi Nov 21, 2018
e3a76b2
Merge pull request #65 from Watson-Personal-Assistant/offer_add_thres…
Nov 21, 2018
b87a1a9
removed validation checks
offerakrabi Nov 22, 2018
e358a73
update pakcage bersion
offerakrabi Nov 22, 2018
35b5ab9
Merge pull request #64 from Watson-Personal-Assistant/#1230_add_built…
offerakrabi Nov 25, 2018
8403bff
Updated to v0.0.18 for WASo 29-Nov release
gaynell-gonsalves Dec 3, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion lib/error-responses.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,28 @@ function noNluDeclared() {
return `Could not evaluate request, no NLU engines declared in the manifest`;
}

function errorSettingBuiltInContext(path) {
return 'Error setting built-in context property ' + path;
}

function errorDeletingBuiltInContext(path) {
return 'Error deleting built-in context property ' + path;
}

function builtInContextValidationError() {
return 'Error validating your built-in context object, it will not be saved';
}


// Return response errors
module.exports = {

invalidNluType: invalidNluType,
couldNotReadNluType: couldNotReadNluType,
invalidAction: invalidAction,
noEvaluationAction: noEvaluationAction,
noNluDeclared: noNluDeclared
noNluDeclared: noNluDeclared,
errorSettingBuiltInContext: errorSettingBuiltInContext,
errorDeletingBuiltInContext: errorDeletingBuiltInContext,
builtInContextValidationError: builtInContextValidationError
};
11 changes: 11 additions & 0 deletions lib/evaluation-response.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ function EvaluationResponse(callback) {
responseCode: ErrorCodes.ok,
requestResult: {},
intentities: [],
threshold: 0.85,
handleUtterance: true,
routeByEntities: true,
context: {
},
internal:{
Expand All @@ -26,4 +28,13 @@ EvaluationResponse.prototype.rejectUtterance = function() {
return this;
};

EvaluationResponse.prototype.setRoutingByEntities = function(value) {
if(typeof(value) !== 'boolean') {
console.warn('Could not set RouteByEntities flag, given value was not a boolean');
} else {
this.response.routeByEntities = value;
}
return this;
};

module.exports = EvaluationResponse;
169 changes: 128 additions & 41 deletions lib/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,23 @@
© Copyright IBM Corp. 2017
*/


'use strict';

const i18 = require('i18next');
const sprintf = require('i18next-sprintf-postprocessor');
const Response = require('./response');
const EvaluationResponse = require('./evaluation-response');
const logger = require('./logger');
const Conversation = require('watson-developer-cloud/conversation/v1');
const Assistant = require('watson-developer-cloud/assistant/v1');
const Promise = require('bluebird');
const fs = require('fs');
const path = require('path');
const async = require('async');
const errors = require('./error-responses');
const instrument = require('./instrument.js');
const WaEnvUtils = require('./nlu/utils');
const builtInContextUtils = require('wa-context-utils');


const nluFolder = '/nlu';
const wcsFileName = '/wcs.json';
Expand All @@ -29,17 +31,15 @@ let Handler = function () {
* Initializes the handler, sets up the connection to wcs
*/
Handler.prototype.initialize = function () {
if(process.env.WCS_USERNAME && process.env.WCS_URL && process.env.WCS_PASSWORD && process.env.WCS_VERSION_DATE
&& process.env.WCS_VERSION && process.env.WCS_WORKSPACE_ID && process.env.WCS_WORKSPACE_NAME &&
process.env.WCS_WORKSPACE_LANGUAGE) {
setupWCSCredentialsFromEnv(this);
if(WaEnvUtils.isValidWaEnvVars()) {
this.wcsCredentials = WaEnvUtils.setupWCSCredentialsFromEnv();
} else {
let rawJson = fs.readFileSync(path.join(process.env.skillSDKResDir, nluFolder, wcsFileName));
this.wcsCredentials = JSON.parse(rawJson);
}
if (this.wcsCredentials) {
let credentials = this.wcsCredentials.credentials;
setupWcs(this, credentials.url, credentials.username, credentials.password, credentials.version_date)
setupWcs(this, credentials.url, credentials.username, credentials.password, credentials.version_date, credentials.version, credentials.iam_apikey)
}
};

Expand All @@ -49,16 +49,24 @@ Handler.prototype.initialize = function () {
* @param callback - a callback function that gets the evaluation response
*/
Handler.prototype.handleEvaluationRequest = function (request, callback) {
let self = this;
if(!this.engines || this.engines.length < 1) {
callback({responseCode: 500, requestResult: errors.noNluDeclared()});
return;
}

let evaluationResponse = new EvaluationResponse((err, result) => {
instrument.exitTime(evaluationResponse.response, "evaluate");
if(self.manifest && self.manifest.threshold) {
evaluationResponse.response.threshold = self.manifest.threshold;
}
saveContext(this, request, context, evaluationResponse);
callback(err, evaluationResponse.response);
});
// set the routingByEntities flag to the value defined in the manifest
if(this.manifest && this.manifest.routeByEntities !== undefined) {
evaluationResponse.setRoutingByEntities(this.manifest.routeByEntities);
}
let context = createContext(request);
let state = this.state || 'DEFAULT';
do {
Expand Down Expand Up @@ -101,22 +109,15 @@ Handler.prototype.evaluateRequest = function (request, evaluationResponse, conte
evaluationResponse.response.intentities.push(intentity);
}
});
let textResponse;
if(output) {
context.skill = output.context ? output.context : {};
if(output.actions) {
for(let action of output.actions) {
evaluationResponse.response.actions.push(action)
}
}
textResponse = output.text ? output.text : undefined;
}
let textResponse = output && output.text ? output.text : undefined;
copyFromNluResponse(context, evaluationResponse, output);
callback(textResponse, evaluationResponse, context, undefined);

}
});
};


Handler.prototype.handleRequest = function (request, callback) {
logger.info('Request', JSON.stringify(request));
// State and session context for short access
Expand Down Expand Up @@ -227,6 +228,69 @@ Handler.prototype.saveEvaluationContext = function (context, evaluationContext)
context.session = evaluationContext.session.attributes;
};

/**
* sset built in context
* @param context - context object created by the sdk
* @param path - path to property
* @param value - desired value to be set
*/
Handler.prototype.setBuiltinContextProperty = function(context, path, value) {
const result = builtInContextUtils.setProperty(JSON.parse(JSON.stringify(context.builtin)), path, value);
if(result.valid) {
context.builtin = result.obj;
logger.info('Successfully set built-in context property ' + path);
return result
} else {
logger.error(errors.errorSettingBuiltInContext(path));
return result;
}
};

/**
* delete a built in context property
* @param context - sdk context object
* @param path - path to property
* @returns {{}}
*/
Handler.prototype.deleteBuiltinContextProperty = function(context, path) {
const result = builtInContextUtils.deleteProperty(JSON.parse(JSON.stringify(context.builtin)), path);
if(result.valid) {
context.builtin = result.obj;
logger.log('Successfully deleted built-in context property ' + path);
return result;
} else {
logger.error(errors.errorDeletingBuiltInContext(path));
return result;
}
};


/**
* get built in context
* @param context
* @param path
* @returns {*}
*/
Handler.prototype.getBuiltinContextProperty = function(context, path) {
const result = builtInContextUtils.getProperty(context.builtin, path);
if(result.valid) {
return result;
} else {
logger.error('Error getting built-in context property ' + path);
return result;
}
};

/**
* validate built in context
* @param context - user altered built-in context
* @returns {boolean}
*/
Handler.prototype.validateBuiltinContext = function(context) {
return builtInContextUtils.validateBuiltinContext(context.builtin);
};



module.exports = Handler;

Expand Down Expand Up @@ -260,21 +324,34 @@ let getIntentity = function (self, request, cb) {
* sets up your WCS credentials, these will be used to access your
* WCS service
*
* @param self
* @param wcsUrl - your wcs url, for US: https://gateway.watsonplatform.net/conversation/api
* for Germany: https://gateway-fra.watsonplatform.net/conversation/api
* @param wcsUsername - your wcs username
* @param wcsPassword - your wcs password
* @param versionDate - your wcs version date
* @param apiKey
*/
let setupWcs = function (self, wcsUrl, wcsUsername, wcsPassword, versionDate) {
let setupWcs = function (handler, wcsUrl, wcsUsername, wcsPassword, versionDate, version, apiKey) {
try {
self.conversation = Promise.promisifyAll(
new Conversation({
let options;
if(apiKey) {
options = {
version: version,
iam_apikey: apiKey,
url: wcsUrl
}

} else {
options = {
url: wcsUrl,
username: wcsUsername,
password: wcsPassword,
version_date: versionDate
})
version: versionDate
}
}
handler.conversation = Promise.promisifyAll(
new Assistant(options)
);
} catch (err) {
console.error('Conversation service failure or missing credentials.');
Expand Down Expand Up @@ -339,7 +416,8 @@ let createContext = function (request) {
return {
utterance: request.context.application.attributes,
session: request.context.session.attributes,
skill: skillContext
skill: skillContext,
builtin: request.context.builtin
};
};

Expand All @@ -351,6 +429,10 @@ let createContext = function (request) {
* @param response
*/
let saveContext = function (self, request, context, response) {
const validationResult = builtInContextUtils.validateBuiltinContext(context.builtin);
if(!validationResult.valid) {
logger.error(errors.builtInContextValidationError());
}
request.context.session.attributes.state = self.state;
if(response.response.context && response.response.context.inConversation !== undefined) {
context.skill.inConversation = response.response.context.inConversation;
Expand All @@ -365,30 +447,35 @@ let saveContext = function (self, request, context, response) {
Object.assign(response.response, {
context: {
application: request.context.application,
session: sessionContext
session: sessionContext,
builtin: context.builtin
}
});
};


/**
* Sets up the handler's wcs credentials from environment variables
* @param self
* copies data from the Nlu evaluation response to the evaluation response and context
* @param context
* @param evaluationResponse
* @param NluResponse
*/

let setupWCSCredentialsFromEnv = function (self) {
self.wcsCredentials = {
"workspace": {
[process.env.WCS_WORKSPACE_LANGUAGE]: {
"name": process.env.WCS_WORKSPACE_NAME,
"workspace_id": process.env.WCS_WORKSPACE_ID
let copyFromNluResponse = function(context, evaluationResponse, NluResponse) {
if(NluResponse) {
if(NluResponse.context) {
context.skill = NluResponse.context || {};
//set handleUtterance flag from NLU context
evaluationResponse.response.handleUtterance = NluResponse.context.handleUtterance !== undefined ? NluResponse.context.handleUtterance : evaluationResponse.response.handleUtterance;
//set routeByEntities flag from NLU context
evaluationResponse.response.routeByEntities = NluResponse.context.routeByEntities !== undefined ? NluResponse.context.routeByEntities : evaluationResponse.response.routeByEntities;
}
if(NluResponse.actions) {
for(let action of NluResponse.actions) {
evaluationResponse.response.actions.push(action)
}
},
"credentials": {
"url": process.env.WCS_URL,
"version": process.env.WCS_VERSION,
"version_date": process.env.WCS_VERSION_DATE,
"password": process.env.WCS_PASSWORD,
"username": process.env.WCS_USERNAME
}
}
};
};



10 changes: 6 additions & 4 deletions lib/nlu/bundles/engines/wcs/workspace.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@

'use strict';

const watson = require('watson-developer-cloud');
const Assistant = require('watson-developer-cloud/assistant/v1');
const hash = require('object-hash');
const logger = require('../../../../logger');

var Workspace = function (credentials) {

let options = JSON.parse(JSON.stringify(credentials));
// options.url = "https://gateway-fra.watsonplatform.net/conversation/api/";

// hack for WA changing version to version_date
if(options.version_date) {
options.version = options.version_date;
}
try {
this.wcs = watson.conversation(options);
this.wcs = new Assistant(options);
} catch (error) {
logger.error("Error setting up your wcs workspace, please check your credentials" +
" (either in env vars or wcs.json). \n" + error);
Expand Down
Loading