-
Notifications
You must be signed in to change notification settings - Fork 4
/
wit.js
executable file
·265 lines (231 loc) · 7.5 KB
/
wit.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
'use strict';
const {
DEFAULT_API_VERSION,
DEFAULT_MAX_STEPS,
DEFAULT_WIT_URL
} = require('./config');
const fetch = require('isomorphic-fetch');
const log = require('./log');
const learnMore = 'Learn more at https://wit.ai/docs/quickstart';
function Wit(opts) {
if (!(this instanceof Wit)) {
return new Wit(opts);
}
const {
accessToken, apiVersion, actions, headers, logger, witURL
} = this.config = Object.freeze(validate(opts));
this._sessions = {};
this.message = (message, context) => {
let qs = 'q=' + encodeURIComponent(message);
if (context) {
qs += '&context=' + encodeURIComponent(JSON.stringify(context));
}
const method = 'GET';
const fullURL = witURL + '/message?' + qs
const handler = makeWitResponseHandler(logger, 'message');
logger.debug(method, fullURL);
return fetch(fullURL, {
method,
headers,
})
.then(response => Promise.all([response.json(), response.status]))
.then(handler)
;
};
this.converse = (sessionId, message, context, reset) => {
let qs = 'session_id=' + encodeURIComponent(sessionId);
if (message) {
qs += '&q=' + encodeURIComponent(message);
}
if (reset) {
qs += '&reset=true';
}
const method = 'POST';
const fullURL = witURL + '/converse?' + qs;
const handler = makeWitResponseHandler(logger, 'converse');
logger.debug(method, fullURL);
return fetch(fullURL, {
method,
headers,
body: JSON.stringify(context),
})
.then(response => Promise.all([response.json(), response.status]))
.then(handler)
;
};
const continueRunActions = (sessionId, currentRequest, message, prevContext, i) => {
return (json) => {
if (i < 0) {
logger.warn('Max steps reached, stopping.');
return prevContext;
}
if (currentRequest !== this._sessions[sessionId]) {
return prevContext;
}
if (!json.type) {
throw new Error('Couldn\'t find type in Wit response');
}
logger.debug('Context: ' + JSON.stringify(prevContext));
logger.debug('Response type: ' + json.type);
// backwards-compatibility with API version 20160516
if (json.type === 'merge') {
json.type = 'action';
json.action = 'merge';
}
if (json.type === 'error') {
throw new Error('Oops, I don\'t know what to do.');
}
if (json.type === 'stop') {
return prevContext;
}
const request = {
sessionId,
context: clone(prevContext),
text: message,
entities: json.entities,
};
if (json.type === 'msg') {
const response = {
text: json.msg,
quickreplies: json.quickreplies,
};
return runAction(actions, 'send', request, response).then(ctx => {
if (ctx) {
throw new Error('Cannot update context after \'send\' action');
}
if (currentRequest !== this._sessions[sessionId]) {
return ctx;
}
return this.converse(sessionId, null, prevContext).then(
continueRunActions(sessionId, currentRequest, message, prevContext, i - 1)
);
});
} else if (json.type === 'action') {
return runAction(actions, json.action, request).then(ctx => {
const nextContext = ctx || {};
if (currentRequest !== this._sessions[sessionId]) {
return nextContext;
}
return this.converse(sessionId, null, nextContext).then(
continueRunActions(sessionId, currentRequest, message, nextContext, i - 1)
);
});
} else {
logger.debug('unknown response type ' + json.type);
throw new Error('unknown response type ' + json.type);
}
};
};
this.runActions = function(sessionId, message, context, maxSteps) {
if (!actions) throwMustHaveActions();
const steps = maxSteps ? maxSteps : DEFAULT_MAX_STEPS;
// Figuring out whether we need to reset the last turn.
// Each new call increments an index for the session.
// We only care about the last call to runActions.
// All the previous ones are discarded (preemptive exit).
const currentRequest = (this._sessions[sessionId] || 0) + 1;
this._sessions[sessionId] = currentRequest;
const cleanup = ctx => {
if (currentRequest === this._sessions[sessionId]) {
delete this._sessions[sessionId];
}
return ctx;
};
return this.converse(sessionId, message, context, currentRequest > 1).then(
continueRunActions(sessionId, currentRequest, message, context, steps)
).then(cleanup);
};
};
const makeWitResponseHandler = (logger, endpoint) => {
return rsp => {
const error = err => {
logger.error('[' + endpoint + '] Error: ' + err);
throw err;
};
if (rsp instanceof Error) {
return error(rsp);
}
const [json, status] = rsp;
if (json instanceof Error) {
return error(json);
}
const err = json.error || status !== 200 && json.body + ' (' + status + ')';
if (err) {
return error(err);
}
logger.debug('[' + endpoint + '] Response: ' + JSON.stringify(json));
return json;
}
};
const throwMustHaveActions = () => {
throw new Error('You must provide the `actions` parameter to be able to use runActions. ' + learnMore)
};
const throwIfActionMissing = (actions, action) => {
if (!actions[action]) {
throw new Error('No \'' + action + '\' action found.');
}
};
const runAction = (actions, name, ...rest) => {
throwIfActionMissing(actions, name);
return Promise.resolve(actions[name](...rest));
};
const validate = (opts) => {
if (!opts.accessToken) {
throw new Error('Could not find access token, learn more at https://wit.ai/docs');
}
opts.witURL = opts.witURL || DEFAULT_WIT_URL;
opts.apiVersion = opts.apiVersion || DEFAULT_API_VERSION;
opts.headers = opts.headers || {
'Authorization': 'Bearer ' + opts.accessToken,
'Accept': 'application/vnd.wit.' + opts.apiVersion + '+json',
'Content-Type': 'application/json',
};
opts.logger = opts.logger || new log.Logger(log.INFO);
if (opts.actions) {
opts.actions = validateActions(opts.logger, opts.actions);
}
return opts;
};
const validateActions = (logger, actions) => {
if (typeof actions !== 'object') {
throw new Error('Actions should be an object. ' + learnMore);
}
if (!actions.send) {
throw new Error('The \'send\' action is missing. ' + learnMore);
}
Object.keys(actions).forEach(key => {
if (typeof actions[key] !== 'function') {
logger.warn('The \'' + key + '\' action should be a function.');
}
if (key === 'say' && actions[key].length > 2 ||
key === 'merge' && actions[key].length > 2 ||
key === 'error' && actions[key].length > 2
) {
logger.warn('The \'' + key + '\' action has been deprecated. ' + learnMore);
}
if (key === 'send') {
if (actions[key].length !== 2) {
logger.warn('The \'send\' action should accept 2 arguments: request and response. ' + learnMore);
}
} else if (actions[key].length !== 1) {
logger.warn('The \'' + key + '\' action should accept 1 argument: request. ' + learnMore);
}
});
return actions;
};
const clone = (obj) => {
if (obj !== null && typeof obj === 'object') {
if (Array.isArray(obj)) {
return obj.map(clone);
} else {
const newObj = {};
Object.keys(obj).forEach(k => {
newObj[k] = clone(obj[k]);
});
return newObj;
}
} else {
return obj;
}
};
module.exports = Wit;