Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
public static async executeLuisQuery(context: TurnContext): Promise {
const bookingDetails = new BookingDetails();
try {
const recognizer = new LuisRecognizer({
applicationId: process.env.LuisAppId,
endpoint: `https://${ process.env.LuisAPIHostName }`,
endpointKey: process.env.LuisAPIKey,
}, {}, true);
const recognizerResult = await recognizer.recognize(context);
const intent = LuisRecognizer.topIntent(recognizerResult);
bookingDetails.intent = intent;
if (intent === 'Book_flight') {
// We need to get the result from the LUIS JSON which at every level returns an array
bookingDetails.destination = LuisHelper.parseCompositeEntity(recognizerResult, 'To', 'Airport');
bookingDetails.origin = LuisHelper.parseCompositeEntity(recognizerResult, 'From', 'Airport');
// This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
// TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
bookingDetails.travelDate = LuisHelper.parseDatetimeEntity(recognizerResult);
}
} catch (err) {
console.warn(`LUIS Exception: ${ err } Check your LUIS configuration`);
}
public static async executeLuisQuery(logger: Logger, context: TurnContext): Promise {
const bookingDetails = new BookingDetails();
try {
const recognizer = new LuisRecognizer({
applicationId: process.env.LuisAppId,
endpoint: `https://${ process.env.LuisAPIHostName }`,
endpointKey: process.env.LuisAPIKey,
}, {}, true);
const recognizerResult = await recognizer.recognize(context);
const intent = LuisRecognizer.topIntent(recognizerResult);
bookingDetails.intent = intent;
if (intent === 'Book_flight') {
// We need to get the result from the LUIS JSON which at every level returns an array
bookingDetails.destination = LuisHelper.parseCompositeEntity(recognizerResult, 'To', 'Airport');
bookingDetails.origin = LuisHelper.parseCompositeEntity(recognizerResult, 'From', 'Airport');
// This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
// TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
bookingDetails.travelDate = LuisHelper.parseDatetimeEntity(recognizerResult);
}
} catch (err) {
logger.warn(`LUIS Exception: ${ err } Check your LUIS configuration`);
}
protected async onInterruptDialog(dc: DialogContext): Promise {
const luisServiceName: string = 'general';
// get current activity locale
const locale: string = dc.context.activity.locale || 'en';
const localeConfig: LocaleConfiguration | undefined = this.services.localeConfigurations.get(locale);
// check luis intent
const luisService: ITelemetryLuisRecognizer | undefined = localeConfig !== undefined ?
localeConfig.luisServices.get(luisServiceName) : undefined;
const luisResult: RecognizerResult | undefined = luisService !== undefined ?
await luisService.recognize(dc.context, true) : undefined;
const intent: string = LuisRecognizer.topIntent(luisResult);
// PENDING: Evolve this pattern
if (luisResult && luisResult.intents[intent].score > 0.5) {
// Add the luis result (intent and entities) for further processing in the derived dialog
dc.context.turnState.set(this.luisResultKey, luisResult);
switch (intent) {
case 'Cancel': {
return this.onCancel(dc);
}
case 'Help': {
return this.onHelp(dc);
}
default:
}
}
return InterruptionAction.NoAction;
// See if we have card input. This would come in through onTurnProperty
const onTurnProperty = await this.onTurnAccessor.get(context);
if (onTurnProperty !== undefined) {
if (onTurnProperty.entities.length !== 0) {
// find user name in on turn property
const userNameInOnTurnProperty = onTurnProperty.entities.find(item => item.entityName === USER_NAME);
if (userNameInOnTurnProperty !== undefined) {
await this.updateUserProfileProperty(userNameInOnTurnProperty.entityValue, context);
return await super.continueDialog(dc);
}
}
}
// call LUIS and get results
const LUISResults = await this.luisRecognizer.recognize(context);
let topIntent = LuisRecognizer.topIntent(LUISResults);
if (Object.keys(LUISResults.intents).length === 0) {
// go with intent in onTurnProperty
topIntent = (onTurnProperty.intent || 'None');
}
// Did user ask for help or said they are not going to give us the name?
switch (topIntent) {
case NO_NAME_INTENT: {
// set user name in profile to Human
await this.userProfileAccessor.set(context, new UserProfile('Human'));
return await this.endGetUserNamePrompt(dc);
}
case GET_USER_NAME_INTENT: {
// Find the user's name from LUIS entities list.
if (USER_NAME in LUISResults.entities) {
await this.updateUserProfileProperty(LUISResults.entities[USER_NAME][0], context);
return await super.continueDialog(dc);
.then(async res => {
// Resolve intents returned from LUIS
let topIntent = LuisRecognizer.topIntent(res);
state.intent = topIntent;
// Start addReminder dialog
if (topIntent === 'Calendar_Add') {
// Resolve entities returned from LUIS, and save these to state
let title = state.title = res.entities['Calendar.Subject'];
let date = res.entities.builtin_datetimeV2_date;
let time = res.entities.builtin_datetimeV2_time;
let datetime = res.entities.builtin_datetimeV2_datetime;
// TODO: The datetime parsing below should be
// updated to use TIMEX parsing instead of moment parsing
if (datetime) {
let dtvalue = datetime[0];
state.date = moment(dtvalue).format('DD-MM-YYYY');
state.time = moment(dtvalue).format('hh:mm a');
} else if (date) {
// Handle commands
if (utterance === localizer.gettext(locale, 'restartCommand')) {
const userData: UserData = new UserData();
// Save locale and any other data you need to persist between resets
userData.locale = locale;
await this.userDataAccessor.set(dc.context, userData);
await dc.cancelAllDialogs();
turnResult = await dc.beginDialog(WelcomeDialog.name);
} else if (dc.activeDialog && dc.activeDialog.id === QnADialog.name) {
// If current active dialog is QnADialog, continue the flow inside that dialog.
turnResult = await dc.continueDialog();
} else {
// Perform a call to LUIS to retrieve results for the current activity message.
const results: RecognizerResult = await this.luisRecognizers[locale].recognize(dc.context);
const topIntent: string = LuisRecognizer.topIntent(results, undefined, LUIS_CONFIDENCE_THRESHOLD);
// Based on LUIS topIntent, evaluate if we have an interruption.
const interrupted: boolean = await this.chitchatDialog.isTurnInterrupted(dc, topIntent);
if (interrupted) {
if (dc.activeDialog) {
// issue a re-prompt on the active dialog
await dc.repromptDialog();
} // Else: We don't have an active dialog so nothing to continue here.
} else {
// No interruption. Continue any active dialogs.
turnResult = await dc.continueDialog();
}
// If no active dialog or no active dialog has responded,
if (!dc.context.responded) {
updateResult = newReservation.updateProperties(onTurnProperties);
}
// see if updates to reservation resulted in errors, if so, report them to user.
if (updateResult &&
updateResult.status === reservationStatusEnum.INCOMPLETE &&
updateResult.outcome !== undefined &&
updateResult.outcome.length !== 0) {
// set reservation property
this.reservationsAccessor.set(turnContext, updateResult.newReservation);
// return and do not continue if there is an error
await turnContext.sendActivity(updateResult.outcome[0].message);
return await super.continueDialog(dc);
}
// call LUIS (bookTableTurnN model) and get results
const LUISResults = await this.luisRecognizer.recognize(turnContext);
let topIntent = LuisRecognizer.topIntent(LUISResults);
// If we dont have an intent match from LUIS, go with the intent available via
// the on turn property (parent's LUIS model)
if (Object.keys(LUISResults.intents).length === 0) {
// go with intent in onTurnProperty
topIntent = (onTurnProperties.intent || 'None');
}
// update reservation object with LUIS result
updateResult = newReservation.updateProperties(OnTurnProperty.fromLUISResults(LUISResults));
// see if update reservation resulted in errors, if so, report them to user.
if (updateResult &&
updateResult.status === reservationStatusEnum.INCOMPLETE &&
updateResult.outcome !== undefined &&
updateResult.outcome.length !== 0) {
// set reservation property
this.reservationsAccessor.set(turnContext, updateResult.newReservation);
if (identifiedSkill !== undefined) {
// We have identified a skill so initialize the skill connection with the target skill
const result: DialogTurnResult = await dc.beginDialog(identifiedSkill.id);
if (result.status === DialogTurnStatus.complete) {
await this.complete(dc);
}
} else if (intent === 'l_general') {
// If dispatch result is general luis model
const luisService: LuisRecognizerTelemetryClient | undefined = cognitiveModels.luisServices.get(this.luisServiceGeneral);
if (luisService === undefined) {
throw new Error('The specified LUIS Model could not be found in your Bot Services configuration.');
} else {
const result: RecognizerResult = await luisService.recognize(dc.context);
if (result !== undefined) {
const generalIntent: string = LuisRecognizer.topIntent(result);
// switch on general intents
switch (generalIntent) {
case 'Escalate': {
// start escalate dialog
await dc.beginDialog(EscalateDialog.name);
break;
}
case 'None':
default: {
// No intent was identified, send confused message
await this.responder.replyWith(dc.context, MainResponses.responseIds.confused);
}
}
}
}
// We have identified a skill so initialize the skill connection with the target skill
const result: DialogTurnResult = await dc.beginDialog(identifiedSkill.id);
if (result.status === DialogTurnStatus.complete) {
await this.complete(dc);
}
} else if (intent === 'l_general') {
// If dispatch result is general luis model
const luisService: LuisRecognizerTelemetryClient | undefined = cognitiveModels.luisServices.get(this.luisServiceGeneral);
if (luisService === undefined) {
throw new Error('The General LUIS Model could not be found in your Bot Services configuration.');
} else {
const result: RecognizerResult = await luisService.recognize(dc.context);
if (result !== undefined) {
const generalIntent: string = LuisRecognizer.topIntent(result);
// switch on general intents
switch (generalIntent) {
case 'Escalate': {
// start escalate dialog
await dc.beginDialog(EscalateDialog.name);
break;
}
case 'None':
default: {
// No intent was identified, send confused message
await this.responder.replyWith(dc.context, MainResponses.responseIds.confused);
break;
}
}
}
logOriginalMessage: boolean = false,
dialogId?: string): Promise {
if (context === null) {
throw new Error('context is null');
}
// Call Luis Recognizer
const recognizerResult: RecognizerResult = await super.recognize(context);
const conversationId: string = context.activity.conversation.id;
// Find the Telemetry Client
if (recognizerResult && context.turnState.has(TelemetryLoggerMiddleware.appInsightsServiceKey)) {
const telemetryClient: TelemetryClient = context.turnState.get(TelemetryLoggerMiddleware.appInsightsServiceKey);
const topLuisIntent: string = LuisRecognizer.topIntent(recognizerResult);
const intentScore: number = recognizerResult.intents[topLuisIntent].score;
// Add the intent score and conversation id properties
const properties: { [key: string]: string } = {};
properties[this.luisTelemetryConstants.applicationId] = this.luisApplication.applicationId;
properties[this.luisTelemetryConstants.intentProperty] = topLuisIntent;
properties[this.luisTelemetryConstants.intentScoreProperty] = intentScore.toString();
if (dialogId !== undefined) {
properties[this.luisTelemetryConstants.dialogId] = dialogId;
}
if (recognizerResult.sentiment) {
if (recognizerResult.sentiment.label) {
properties[this.luisTelemetryConstants.sentimentLabelProperty] = recognizerResult.sentiment.label;
}