Update parameter value for all contexts with DialogFlow Fulfillment? - dialogflow-es

How can we update a parameter value with the DialogFlow Fulfillment library? I wrote a helper method to access the agent's contexts and loop through updating the values, but that does not seem to be working:
export const dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const wbhc = new WebhookClient({ request, response });
function testIntentHandler(agent: any) {
const date = agent.parameters['date'];
const datePeriod = agent.parameters['date-period'];
if (date && !datePeriod) {
setDialogFlowParameter('date-period', {
startDate: date,
endDate: date
}, agent.context);
}
agent.add("I've set the value");
}
// Run the proper function handler based on the matched Dialogflow intent name
const intentMap = new Map();
intentMap.set('TestIntent', testIntentHandler);
wbhc.handleRequest(intentMap);
});
function setDialogFlowParameter(param: string, val: any, context: any) {
const contexts = context.contexts;
const keys = Object.keys(contexts);
for (const key of keys) {
const c = context.get(key);
c.parameters[param] = val;
context.set(key, c.lifespan, c.parameters);
}
}
Please note, this question is focused around the NodeJS dialogflow-fulfillment library, which I couldn't find an answer for after hours of searching.

Did you look at the output contexts attribute of FULFILMENT RESPONSE tab in"DIAGNOSTIC INFO" of the Dialogflow console? You should be able to see the values there after you use the agent.context.set() method and update the param values.

Related

Context is not working properly in dialogflow

const contextlist = 'customer';
app.intent('Welcome', (conv) => {
const customer = { 'companyId': '11131' };
conv.contexts.set(contextlist, 5, customer);
});
app.intent('Delivery',(conv)=>{
let companycontext = conv.contexts.get(contextlist);
})
These are the logs regarding the context
I'm going to set the context when my welcome intent is called and getting the value from intent when the Delivery intent will call, But I'm getting undefined at the time of getting context value.
First try adding a conv.ask() call with some text, in the code example you showed you are not returning a response, this might affect the setting of the context.
If that doesn't work, try changing the way you are setting your variables in your context to the following:
conv.contexts.set(contextlist, 5, { customer });
The properties that you want to set need to be part of an object. If you want to retrieve the customer, you need to use the following code:
// Set context
conv.contexts.set(contextlist, 5, { customer });
// Retrieve context
const companycontext = conv.contexts.get(contextlist);
const customer = companycontext.parameters.customer;

How to update existing Intent in Dialogflow(V2) using nodejs SDK?

I am using Dialogflow nodejs SDK(V2) to Integrate Dialogflow in my nodjs application for that I am using dialogflow npm node library. I'm able to create the Intent and get the list of Intents and I'm able to query as well. But I can't find any method for updating the existing Intent and getting Intent details based on the Intent ID.
can you please help me or guide me how to resolve this issue?
Thanks.
To update an intent, first, you need to get the intent details. If you have the intent name or ID, then you can simply make a request to list intent API and find the intent details with matching intent name.
Once you have the intent details you wish to update( here referred as existingIntent), you can use the below code to update it.
async function updateIntent(newTrainingPhrases) {
// Imports the Dialogflow library
const dialogflow = require("dialogflow");
// Instantiates clients
const intentsClient = new dialogflow.IntentsClient();
const intent = existingIntent; //intent that needs to be updated
const trainingPhrases = [];
let previousTrainingPhrases =
existingIntent.trainingPhrases.length > 0
? existingIntent.trainingPhrases
: [];
previousTrainingPhrases.forEach(textdata => {
newTrainingPhrases.push(textdata.parts[0].text);
});
newTrainingPhrases.forEach(phrase => {
const part = {
text: phrase
};
// Here we create a new training phrase for each provided part.
const trainingPhrase = {
type: "EXAMPLE",
parts: [part]
};
trainingPhrases.push(trainingPhrase);
});
intent.trainingPhrases = trainingPhrases;
const updateIntentRequest = {
intent,
languageCode: "en-US"
};
// Send the request for update the intent.
const result = await intentsClient.updateIntent(updateIntentRequest);
return result;
}

Using conditional operators with QnAMaker - operators aren't routing correctly

I'm having difficulty figuring out what most likely is a simple issue, which relates to a 'if then else' problem in my code (NodeJS, Bot Framework v4).
I can't quite figure out why the relevant card isn't being shown depending on the number of semi-colons it finds in the response string from QnAMaker.
When testing with the Bot Framework emulator, it only returns one response type, whether that's plain text or one Rich Card no matter how many semi-colons are in the response.
I've tried to see if it's the length of the string it's having problems with by parsing the number value in the length statement. Didn't make a difference sadly. Notably if I use any other conditional operator such as '===' for example, it breaks the response completely.
const { ActivityTypes, CardFactory } = require('botbuilder');
const { WelcomeCard } = require('./dialogs/welcome');
// const { HeroCard } = require('./dialogs/welcome');
// const { VideoCard } = require('./dialogs/welcome');
class MyBot {
/**
*
* #param {TurnContext} on turn context object.
*/
constructor(qnaServices) {
this.qnaServices = qnaServices;
}
async onTurn(turnContext) {
if (turnContext.activity.type === ActivityTypes.Message) {
for (let i = 0; i < this.qnaServices.length; i++) {
// Perform a call to the QnA Maker service to retrieve matching Question and Answer pairs.
const qnaResults = await this.qnaServices[i].getAnswers(turnContext);
const qnaCard = qnaResults.includes(';');
// If an answer was received from QnA Maker, send the answer back to the user and exit.
if (qnaCard.toString().split(';').length < 3) {
await turnContext.sendActivity(qnaResults[0].answer);
await turnContext.sendActivity({
text: 'Hero Card',
attachments: [CardFactory.heroCard(HeroCard)]
});
} else if (qnaCard.toString().split(';').length > 3) {
await turnContext.sendActivity(qnaResults[0].answer);
await turnContext.sendActivity({
text: 'Video Card',
attachments: [CardFactory.videoCard(VideoCard)]
});
} else if (qnaCard.toString().split(';').length === 0) {
await turnContext.sendActivity(qnaResults[0].answer);
return;
}
}
// If no answers were returned from QnA Maker, reply with help.
await turnContext.sendActivity('No QnA Maker answers were found.');
} else {
await turnContext.sendActivity(`[${ turnContext.activity.type } event detected]`);
} if (turnContext.activity.type === ActivityTypes.ConversationUpdate) {
// Handle ConversationUpdate activity type, which is used to indicates new members add to
// the conversation.
// See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types
// Do we have any new members added to the conversation?
if (turnContext.activity.membersAdded.length !== 0) {
// Iterate over all new members added to the conversation
for (var idx in turnContext.activity.membersAdded) {
// Greet anyone that was not the target (recipient) of this message
// the 'bot' is the recipient for events from the channel,
// context.activity.membersAdded == context.activity.recipient.Id indicates the
// bot was added to the conversation.
if (turnContext.activity.membersAdded[idx].id !== turnContext.activity.recipient.id) {
// Welcome user.
// When activity type is "conversationUpdate" and the member joining the conversation is the bot
// we will send our Welcome Adaptive Card. This will only be sent once, when the Bot joins conversation
// To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
const welcomeCard = CardFactory.adaptiveCard(WelcomeCard);
await turnContext.sendActivity({ attachments: [welcomeCard] });
}
}
}
}
}
}
module.exports.MyBot = MyBot;
Ideally, what I'm hoping to see is if I ask a question which has 3 semi-colons in the response, it outputs a Hero Card. If it has more than 3, then a Video Card and if it doesn't have either, a text response.
I'm not a js specialist, but I'm quite confused by the following:
const qnaCard = qnaResults.includes(';');
In Javascript, includes is the following (source):
The includes() method determines whether an array includes a certain
value among its entries, returning true or false as appropriate.
So here your qnaCard is true or false. But it looks like you are trying to use it as if it was containing the text:
if (qnaCard.toString().split(';').length < 3) {
...
You have to work on the object containing the answer: qnaResults[0].answer.

How to create OutPutContext via V2 client library for node js

I am working on entity and intents creation in my agent using v2 client library for node.js . And for that i am going through this sample which is on git. And it says something related to session id and context id. Can anyone explain me what is sessionId and contextId. And also provide me link where i can read those thing in details.
I am unable to create context by following those example. How can i create context while creating intent at the same time.
The following is code to create a context. You cannot create a context and an intent in a single API call, you first need to create the context and then create the intent that uses the context. The response to the create context API call will return a context ID you can use in your intent.
const dialogflow = require('dialogflow');
// Instantiates clients
const entityTypesClient = new dialogflow.EntityTypesClient();
// The path to the agent the created entity type belongs to.
const agentPath = entityTypesClient.projectAgentPath(projectId);
const createEntityTypeRequest = {
parent: agentPath,
entityType: {
displayName: displayName,
kind: kind,
},
};
entityTypesClient
.createEntityType(createEntityTypeRequest)
.then(responses => {
console.log(`Created ${responses[0].name} entity type`);
})
.catch(err => {
console.error('Failed to create size entity type:', err);
});
Source: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js
Contexts are very closely associated with SessionID. Say for eg, you have a chatbot that gets spun up on two computers serving two different user's. Each user will have a respective session_id (If you're coding in NODE, when a new user fires the chatbot, you need to ensure he/she will get a unique session_id).
Now, every unique session id will have unique contexts. From above example, let's say user 1 will initialize an intent that has input context named 'abc' with lifespan of 2 and user 2 will initialize another intent that has input context named 'xyz' with lifespan of 5, these respective contexts gets recorded against each of these user's individual session id's. You can programatically control (edit) contexts and its lifecycle. This is the biggest advantage of code facilitated Dialogflow as opposed to using GUI. Using services like Firebase, you can also preserve session id's and its associated contexts so, next time same user sign's in again, they can start from where they had last left.
I can share a snippet from one of my previous projects where I was managing contexts programatically. Initialization script is as follows:
/**
* #author Pruthvi Kumar
* #email pruthvikumar.123#gmail.com
* #create date 2018-08-15 04:42:22
* #modify date 2018-08-15 04:42:22
* #desc Dialogflow config for chatbot.
*/
const dialogflow_config = {
projectId: 'xxx',
sessionId: 'chatbot-session-id', //This is default assignment. This will hve to be overridden by sessionId as obtained from client in order to main context per sessionId.
languageCode: 'en-US'
};
exports.configStoreSingleton = (function () {
let instanceStacks;
let instanceSessionId;
let contextStack = {};
let intentsStack = {};
let successfulIntentResponseStack = {};
function init() {
contextStack[dialogflow_config['sessionId']] = [];
intentsStack[dialogflow_config['sessionId']] = [];
successfulIntentResponseStack[dialogflow_config['sessionId']] = [];
return {
contextStack: contextStack,
intentsStack: intentsStack,
successfulIntentResponseStack: successfulIntentResponseStack
};
}
return {
init: function () {
if (!instanceStacks || (instanceSessionId !== dialogflow_config['sessionId'] && (!intentsStack[dialogflow_config['sessionId']]))) {
console.log('[dialogflow_config]: Singleton is not instantiated previously or New userSession is triggered! Fresh instance stack will be provisioned');
instanceStacks = init();
instanceSessionId = dialogflow_config['sessionId'];
}
return instanceStacks;
}
};
})();
exports.updateSessionIdOfDialogflowConfig = function (sessionId) {
if (typeof (sessionId) === 'string') {
dialogflow_config['sessionId'] = sessionId;
return true;
} else {
console.warn('[dialogflow_config]: SessionId must be of type STRING!');
return;
}
};
exports.getDialogflowConfig = function () {
return dialogflow_config;
};
And then, to programmatically manage contexts:
/**
* #author Pruthvi Kumar
* #email pruthvikumar.123#gmail.com
* #create date 2018-08-15 04:37:15
* #modify date 2018-08-15 04:37:15
* #desc Operate on Dialogflow Contexts
*/
const dialogflow = require('dialogflow');
const dialogflowConfig = require('../modules/dialogflow_config');
const structjson = require('./dialogflow_structjson');
const util = require('util');
const contextsClient = new dialogflow.ContextsClient();
exports.setContextHistory = function (sessionId, intent_name, context_payload, preservedContext=false) {
/* maintain context stack per session */
/* context_payload = {input_contexts: [], output_contexts = []}
*/
const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
if (intent_name) {
contextStack[sessionId].push({
intent: intent_name,
contexts: context_payload,
preserveContext: preservedContext
});
} else {
console.warn('[dialogflow_contexts]: Intent name is not provided OR Nothing in context_payload to add to history!');
}
};
exports.getContextHistory = function () {
const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
return contextStack;
}
exports.preserveContext = function () {
const contextStack = dialogflowConfig.configStoreSingleton.init().contextStack;
//Traverse contextStack, get the last contexts.
let context_to_be_preserved = contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']][contextStack[dialogflowConfig.getDialogflowConfig()['sessionId']].length - 1];
//console.log(`context to be preserved is: ${util.inspect(context_to_be_preserved)}`);
return context_to_be_preserved['contexts'].map((context, index) => {
let context_id = exports.getContextId(context);
return exports.updateContext(context_id, true)
});
}
From here, you can reference this github resource to build your own contexts - https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/resource.js
Happy creating digital souls!

Mapping mulitiple intents to one function using actionMap for a DialogFlowApp

I am building an app using Dialogflow. The user answers some questions, and can review their answers later. My problem is with building the server to return the user's previous answers.
This is the code so far, where the intents are QUESTION_1 and QUESTION_2, and the parameters are GRATEFUL_1 and GRATEFUL_2:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
const App = require('actions-on-google').DialogflowApp;
const functions = require('firebase-functions');
// a. the action names from the Dialogflow intents
const QUESTION_1 = 'Question-1';
const QUESTION_2 = 'Question-2';
// b. the parameters that are parsed from the intents
const GRATEFUL_1 = 'any-grateful-1';
const GRATEFUL_2 = 'any-grateful-2';
exports.JournalBot = functions.https.onRequest((request, response) => {
const app = new App({request, response});
console.log('Request headers: ' + JSON.stringify(request.headers));
console.log('Request body: ' + JSON.stringify(request.body));
// Return the last journal entry
function reflect (app) {
let grateful_1 = app.getArgument(GRATEFUL_1);
app.tell('Here is your previous entry: ' + grateful_1);
}
// Build an action map, which maps intent names to functions
let actionMap = new Map();
actionMap.set(QUESTION_1, reflect);
app.handleRequest(actionMap);
});
I want the 'reflect' function to be mapped to the GRATEFUL_2 response as well as GRATEFUL_1. I know how to do this, but how do I change this next bit to include both intents:
actionMap.set(QUESTION_1, reflect);
If you wanted the QUESTION_2 intent to also go to the reflect() function, you can simply add
actionMap.set(QUESTION_2, reflect);
But I don't think that is your problem. Inside reflect() you need to know which intent it was that got you there.
You can use app.getIntent() to get a string with the intent name and then match this to which response you want to give. So something like this might work:
function reflect( app ){
let intent = app.getIntent();
var grateful;
switch( intent ){
case QUESTION_1:
grateful = GRATEFUL_1;
break;
case QUESTION_2:
grateful = GRATEFUL_2;
break;
}
var response = app.getArgument( grateful );
app.tell( 'You previously said: '+response );
}
There are other variants, of course.
There is no requirement you actually use the actionMap and app.handleRequest() at all. If you have another way you want to determine which output you want to give based on the intent string, you're free to use it.

Resources