Compare commits

...

4 Commits

Author SHA1 Message Date
Dave Horton
2dc0cd11ba minor rasa fix 2021-09-07 13:38:22 -04:00
Dave Horton
9df76302fe rasa: add support for eventhook which provides user and bot messages in realtime and supports redirecting to a new app 2021-09-02 10:27:59 -04:00
Dave Horton
98f53138d1 initial support for Rasa 2021-09-01 21:06:32 -04:00
Dave Horton
47073955e0 dialogflow: support for regional endpoints 2021-08-31 20:31:16 -04:00
10 changed files with 221 additions and 10 deletions

View File

@@ -45,7 +45,7 @@ module.exports = function(srf, logger) {
// TODO: alert
return res.send(503, {headers: {'X-Reason': 'Account exists but is inactive'}});
}
logger.debug({accountInfo: req.locals.accountInfo}, `retrieved account info for ${account_sid}`);
logger.debug({accountInfo: req.locals?.accountInfo?.account}, `retrieved account info for ${account_sid}`);
next();
} catch (err) {
logger.info({err}, `Error retrieving account details for account ${account_sid}`);

View File

@@ -202,7 +202,6 @@ class CallSession extends Emitter {
*/
getSpeechCredentials(vendor, type) {
const {writeAlerts, AlertType} = this.srf.locals;
this.logger.debug({vendor, type, speech: this.accountInfo.speech}, `searching for speech for vendor ${vendor}`);
if (this.accountInfo.speech && this.accountInfo.speech.length > 0) {
const credential = this.accountInfo.speech.find((s) => s.vendor === vendor);
if (credential && (

View File

@@ -9,10 +9,22 @@ class Dialogflow extends Task {
constructor(logger, opts) {
super(logger, opts);
this.preconditions = TaskPreconditions.Endpoint;
this.credentials = this.data.credentials;
if (this.data.environment) this.project = `${this.data.project}:${this.data.environment}`;
else this.project = this.data.project;
/* set project id with environment and region (optionally) */
if (this.data.environment && this.data.region) {
this.project = `${this.data.project}:${this.data.environment}:${this.data.region}`;
}
else if (this.data.environment) {
this.project = `${this.data.project}:${this.data.environment}`;
}
else if (this.data.region) {
this.project = `${this.data.project}::${this.data.region}`;
}
else {
this.project = this.data.project;
}
this.lang = this.data.lang || 'en-US';
this.welcomeEvent = this.data.welcomeEvent || '';
if (this.welcomeEvent.length && this.data.welcomeEventParams && typeof this.data.welcomeEventParams === 'object') {

View File

@@ -10,7 +10,7 @@ const makeTask = require('./make_task');
const assert = require('assert');
class TaskGather extends Task {
constructor(logger, opts) {
constructor(logger, opts, parentTask) {
super(logger, opts);
this.preconditions = TaskPreconditions.Endpoint;
@@ -40,6 +40,8 @@ class TaskGather extends Task {
if (this.say) this.sayTask = makeTask(this.logger, {say: this.say}, this);
if (this.play) this.playTask = makeTask(this.logger, {play: this.play}, this);
this.parentTask = parentTask;
}
get name() { return TaskName.Gather; }
@@ -154,7 +156,6 @@ class TaskGather extends Task {
});
ep.addCustomEventListener(AwsTranscriptionEvents.Transcription, this._onTranscription.bind(this, cs, ep));
}
this.logger.debug({vars: opts}, 'setting freeswitch vars');
await ep.set(opts)
.catch((err) => this.logger.info(err, 'Error setting channel variables'));
@@ -235,7 +236,11 @@ class TaskGather extends Task {
await this.performAction({digits: this.digitBuffer});
}
else if (reason.startsWith('speech')) {
await this.performAction({speech: evt});
if (this.parentTask) this.parentTask.emit('transcription', evt);
else await this.performAction({speech: evt});
}
else if (reason.startsWith('timeout') && this.parentTask) {
this.parentTask.emit('timeout', evt);
}
this.notifyTaskDone();
}

View File

@@ -48,6 +48,9 @@ function makeTask(logger, obj, parent) {
case TaskName.Message:
const TaskMessage = require('./message');
return new TaskMessage(logger, data, parent);
case TaskName.Rasa:
const TaskRasa = require('./rasa');
return new TaskRasa(logger, data, parent);
case TaskName.Say:
const TaskSay = require('./say');
return new TaskSay(logger, data, parent);

156
lib/tasks/rasa.js Normal file
View File

@@ -0,0 +1,156 @@
const Task = require('./task');
const {TaskName, TaskPreconditions} = require('../utils/constants');
const makeTask = require('./make_task');
const bent = require('bent');
class Rasa extends Task {
constructor(logger, opts) {
super(logger, opts);
this.preconditions = TaskPreconditions.Endpoint;
this.prompt = this.data.prompt;
this.eventHook = this.data?.eventHook;
this.actionHook = this.data?.actionHook;
this.post = bent('POST', 'json', 200);
}
get name() { return TaskName.Rasa; }
get hasReportedFinalAction() {
return this.reportedFinalAction || this.isReplacingApplication;
}
async exec(cs, ep) {
await super.exec(cs);
this.ep = ep;
try {
/* set event handlers */
this.on('transcription', this._onTranscription.bind(this, cs, ep));
this.on('timeout', this._onTimeout.bind(this, cs, ep));
/* start the first gather */
this.gatherTask = this._makeGatherTask(this.prompt);
this.gatherTask.exec(cs, ep, this)
.catch((err) => this.logger.info({err}, 'Rasa gather task returned error'));
await this.awaitTaskDone();
} catch (err) {
this.logger.error({err}, 'Rasa error');
throw err;
}
}
async kill(cs) {
super.kill(cs);
this.logger.debug('Rasa:kill');
if (!this.hasReportedFinalAction) {
this.reportedFinalAction = true;
this.performAction({rasaResult: 'caller hungup'})
.catch((err) => this.logger.info({err}, 'rasa - error w/ action webook'));
}
if (this.ep.connected) {
await this.ep.api('uuid_break', this.ep.uuid).catch((err) => this.logger.info(err, 'Error killing audio'));
}
this.removeAllListeners();
this.notifyTaskDone();
}
_makeGatherTask(prompt) {
let opts = {
input: ['speech'],
timeout: this.data.timeout || 10,
recognizer: this.data.recognizer || {
vendor: 'default',
language: 'default'
}
};
if (prompt) {
const sayOpts = this.data.tts ?
{text: prompt, synthesizer: this.data.tts} :
{text: prompt};
opts = {
...opts,
say: sayOpts
};
}
//this.logger.debug({opts}, 'constructing a nested gather object');
const gather = makeTask(this.logger, {gather: opts}, this);
return gather;
}
async _onTranscription(cs, ep, evt) {
//this.logger.debug({evt}, `Rasa: got transcription for callSid ${cs.callSid}`);
const utterance = evt.alternatives[0].transcript;
if (this.eventHook) {
this.performHook(cs, this.eventHook, {event: 'userMessage', message: utterance})
.then((redirected) => {
if (redirected) {
this.logger.info('Rasa_onTranscription: event handler for user message redirected us to new webhook');
this.reportedFinalAction = true;
this.performAction({rasaResult: 'redirect'}, false);
if (this.gatherTask) this.gatherTask.kill(cs);
}
return;
})
.catch(({err}) => {
this.logger.info({err}, 'Rasa_onTranscription: error sending event hook');
});
}
try {
const payload = {
sender: cs.callSid,
message: utterance
};
this.logger.debug({payload}, 'Rasa:_onTranscription - sending payload to Rasa');
const response = await this.post(this.data.url, payload);
this.logger.debug({response}, 'Rasa:_onTranscription - got response from Rasa');
const botUtterance = Array.isArray(response) ?
response.reduce((prev, current) => {
return current.text ? `${prev} ${current.text}` : '';
}, '') :
null;
if (botUtterance) {
this.logger.debug({botUtterance}, 'Rasa:_onTranscription: got user utterance');
this.gatherTask = this._makeGatherTask(botUtterance);
this.gatherTask.exec(cs, ep, this)
.catch((err) => this.logger.info({err}, 'Rasa gather task returned error'));
if (this.eventHook) {
this.performHook(cs, this.eventHook, {event: 'botMessage', message: response})
.then((redirected) => {
if (redirected) {
this.logger.info('Rasa_onTranscription: event handler for bot message redirected us to new webhook');
this.reportedFinalAction = true;
this.performAction({rasaResult: 'redirect'}, false);
if (this.gatherTask) this.gatherTask.kill(cs);
}
return;
})
.catch(({err}) => {
this.logger.info({err}, 'Rasa_onTranscription: error sending event hook');
});
}
}
} catch (err) {
this.logger.error({err}, 'Rasa_onTranscription: Error sending user utterance to Rasa - ending task');
this.performAction({rasaResult: 'webhookError'});
this.reportedFinalAction = true;
this.notifyTaskDone();
}
}
_onTimeout(cs, ep, evt) {
this.logger.debug({evt}, 'Rasa: got timeout');
if (!this.hasReportedFinalAction) this.performAction({rasaResult: 'timeout'});
this.reportedFinalAction = true;
this.notifyTaskDone();
}
}
module.exports = Rasa;

View File

@@ -78,7 +78,6 @@
"say": "#say"
},
"required": [
"actionHook"
]
},
"conference": {
@@ -124,6 +123,10 @@
"credentials": "object|string",
"project": "string",
"environment": "string",
"region": {
"type": "string",
"enum": ["europe-west1", "europe-west2", "australia-southeast1", "asia-northeast1"]
},
"lang": "string",
"actionHook": "object|string",
"eventHook": "object|string",
@@ -224,6 +227,19 @@
"length"
]
},
"rasa": {
"properties": {
"url": "string",
"recognizer": "#recognizer",
"tts": "#synthesizer",
"prompt": "string",
"actionHook": "object|string",
"eventHook": "object|string"
},
"required": [
"url"
]
},
"redirect": {
"properties": {
"actionHook": "object|string"

View File

@@ -99,6 +99,25 @@ class Task extends Emitter {
}
}
async performHook(cs, hook, results) {
const json = await cs.requestor.request(hook, results);
if (json && Array.isArray(json)) {
const makeTask = require('./make_task');
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
if (tasks && tasks.length > 0) {
this.redirect(cs, tasks);
return true;
}
}
return false;
}
redirect(cs, tasks) {
this.logger.info({tasks: tasks}, `${this.name} replacing application with ${tasks.length} tasks`);
this.isReplacingApplication = true;
cs.replaceApplication(tasks);
}
async transferCallToFeatureServer(cs, sipAddress, opts) {
const uuid = uuidv4();
const {addKey} = cs.srf.locals.dbHelpers;

View File

@@ -14,6 +14,7 @@
"Message": "message",
"Pause": "pause",
"Play": "play",
"Rasa": "rasa",
"Redirect": "redirect",
"RestDial": "rest:dial",
"SipDecline": "sip:decline",

View File

@@ -1,6 +1,6 @@
{
"name": "jambonz-feature-server",
"version": "0.3.1",
"version": "0.6.6",
"main": "app.js",
"engines": {
"node": ">= 10.16.0"