This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
app.js
164 lines (144 loc) · 5.98 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var express = require('express'); // app server
var bodyParser = require('body-parser'); // parser for post requests
const AssistantV1 = require('ibm-watson/assistant/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
var app = express();
// Bootstrap application settings
app.use(express.static('./public')); // load UI from public folder
app.use(bodyParser.json());
var assistantAPIKey = process.env["ASSISTANT_IAM_API_KEY"];
var assistantURL = process.env["ASSISTANT_IAM_URL"];
var assistantVersion = process.env["VERSION"];
console.log("assistantVersion = " + assistantVersion);
// Create the service wrapper
const assistant = new AssistantV1({
version: assistantVersion,
authenticator: new IamAuthenticator({
apikey: assistantAPIKey,
}),
url: assistantURL,
});
// Endpoint to be call from the client side
app.post('/api/message', function (req, res) {
console.log("");
var workspace = getDestinationBot(req.body.context) || '<workspace-id>';
console.log("workspace = " + workspace);
if (!workspace || workspace === '<workspace-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-simple">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-simple/blob/master/training/car_workspace.json">here</a> in order to get a working application.'
}
});
}
var payload = {
workspaceId: workspace,
context: req.body.context || {},
input: req.body.input || {}
};
// Send the input to the assistant service
assistant.message(payload, function (err, data) {
data = data.result
console.log("Message: " + JSON.stringify(payload.input));
if (err) {
console.log("Error occurred: " + JSON.stringify(err.message))
return res.status(err.code || 500).json(err);
}
if (isRedirect(data.context)) {
// When there is a redirect, get the redirect bot workspace id
payload.workspaceId = getDestinationBot(data.context);
// When there is a redirect, update destination bot in context so it persists along with the conversation
payload.context.destination_bot = data.context.destination_bot;
// Where there is redirect, old conversation_id is not needed. Delete it
delete payload.context.conversation_id;
// For redirect, no user action is needed. Call the redirect bot automatically and send back that response to user
assistant.message(payload, function (err, data) {
data = data.result
if (err) {
return res.status(err.code || 500).json(err);
}
return res.json(updateMessage(payload, data));
});
} else { // There is no redirect. So send back the response to user for further action
return res.json(updateMessage(payload, data));
}
});
});
// The function checks if the bot response says messages to be redirected
function isRedirect(context) {
if (context && context.redirect_to_another_bot) {
var isRedirect = context.redirect_to_another_bot;
if (isRedirect == true) {
return true;
} else {
return false;
}
} else {
return false;
}
}
// The agent bot decides which bot the request should be redirected to and updates that in context variable.
// Get worspace_id for redirected bot details so messages can be sent to that bot
function getDestinationBot(context) {
var destination_bot = null;
if (context && context.destination_bot) {
destination_bot = context.destination_bot.toUpperCase();
}
var wsId = process.env["WORKSPACE_ID_" + destination_bot];
if (!wsId) {
wsId = process.env["WORKSPACE_ID_AGENT"];
}
if (!destination_bot) {
destination_bot = "AGENT";
}
console.log("Message being sent to: " + destination_bot + " bot");
return wsId;
}
/**
* Updates the response text using the intent confidence
* @param {Object} input The request to the Assistant service
* @param {Object} response The response from the Assistant service
* @return {Object} The response with the updated message
*/
function updateMessage(input, response) {
var responseText = null;
if (!response.output) {
response.output = {};
} else {
console.log("Response message: " + JSON.stringify(response.output.text));
return response;
}
if (response.intents && response.intents[0]) {
var intent = response.intents[0];
// Depending on the confidence of the response the app can return different messages.
// The confidence will vary depending on how well the system is trained. The service will always try to assign
// a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the
// user's intent . In these cases it is usually best to return a disambiguation message
// ('I did not understand your intent, please rephrase your question', etc..)
if (intent.confidence >= 0.75) {
responseText = 'I understood your intent was ' + intent.intent;
} else if (intent.confidence >= 0.5) {
responseText = 'I think your intent was ' + intent.intent;
} else {
responseText = 'I did not understand your intent';
}
}
response.output.text = responseText;
return response;
}
module.exports = app;