How to pass params from one intent to another dialogflow - node.js

how does one pass the params from a intent in the fulfillment editor to another followup intent.
Here is my code
// original intent
// the params defined here are the ones I want to pass to the app.intent below.
app.intent('Book Appointment', (conv, params) => {
// the params that i want to access in the next intent
const date = params['date'];
const time = params['time'];
const firstName = params['given-name'];
const email = params['email'];
// what i dont get is what to put in here is it
// how am i formatting this?
const parameters = {'date':params.date,}
// is the 'welcome-context' replaced with this one from the JSON? like so?
conv.contexts.set('projects/myproject-120c2/agent/sessions/c2c1c9e0-2ccf-0cf0-d7ce-e52561d44de3/contexts/bookappointment-followup"', 5, parameters);
// or is it
conv.contexts.set('bookappointment-followup', 5, parameters); // ??
// like it is in Dialogflow
})
// follow-up intent
app.intent('Book Appointment - yes', (conv, params) => {
// this is where I want to access the ones above
// then im accessing them like this?
const conv.contexts.get('bookappointment-followup').parameters['whatever it is above'];
})
The variables in the email return undefined. I reckon it's something to do with the contexts but I dont know if its the same code like #book.appointment.follow.date etc.
Help is appreciated, cheers

You may check my answer here
Use the output context to save parameters
{
"fulfillmentText":"This is a text response",
"fulfillmentMessages":[ ],
"source":"example.com",
"payload":{
"google":{ },
"facebook":{ },
"slack":{ }
},
"outputContexts":[
{
"name":"<Context Name>",
"lifespanCount":5,
"parameters":{
"<param name>":"<param value>"
}
}
],
"followupEventInput":{ }
}
If you are using NodeJS client
You can save context with parameters like
let param1 = [];
let param2 = {};
let ctx = {'name': '<context name>', 'lifespan': 5, 'parameters': {'param1':param1, 'param2': param2}};
agent.setContext(ctx);
and get it like
let params = agent.getContext("<context name>").parameters;
let param1 = params.param1;
let param2 = params.param2;
If using conv, you may also try like this:
app.intent('<INTENT>', conv => {
conv.ask('<RESPONSE>');
const parameters = {'param1':param1, 'param2': param2}};
conv.contexts.set('welcome-context', 5, parameters);
});
and access it like here :
const conv.contexts.get(<context>).parameters[<param>];
If via context doesn't work, you may try with data like
conv.data.someProperty = 'someValue'
as stated here

Thanks this worked.
const firstName = conv.contexts.get('bookappointment-followup').parameters['given-name'];
:)

Related

Move data in Waterfall-Dialog. Bot Framework SDK

I'm using Bot Framework SDK with nodejs to implement a disamibuation flow.
I want that if two intents predicted by Luis are close to each other, ask the user from which of them are the one they want. I have done the validator but, I have a problem with the flow.
It is a waterfall Dialog with 3 steps:
FirstStep: Calls Orchestrator and Luis to get intents and entities. It pass the data with return await step.next({...})
Disamiguation Step: Checks if it is necessary to disambiguate, and, in that case, prompts the options. If not, it pass the data like the first step.
Answer step: If it has a disambiguation flag in the data it receives in step.result, it prompts the answer acordingly with the user response. Elsewhere, it uses the data in step.result that comes from the first step.
The problem is that, when it prompts user to say the intent, I lost the data of the FirstStep since I cannot use step.next({...})
¿How can I maintain both the data from the first step and the user answer in the prompt?
Here are the basic code:
async firstStep(step) {
logger.info(`FinalAnswer Dialog: firstStep`);
let model_dispatch = await this.bot.get_intent_dispatch(step.context);
let result = await this.bot.dispatchToTopIntentAsync(step.context, model_dispatch.model)
// model_dispatch = orchestrator_model
// result = {topIntent: String, entities: Array, disamibiguation: Array}
return await step.next({ model_dispatch: model_dispatch, result: result})
}
async disambiguationStep(step) {
logger.info(`FinalAnswer Dialog: disambiguationStep`);
if (step.result.result.disambiguation) {
logger.info("We need to disambiguate")
let disambiguation_options = step.result.result.disambiguation
const message_text = "What do you need";
const data = [
{
"title": "TEXT",
"value": disambiguation_option[0]
},
{
"title": "TEXT",
"value": disambiguation_option[1]
},
]
let buttons = data.map(function (d) {
return {
type: ActionTypes.PostBack,
title: d.title,
value: d.value
}
});
const msg = MessageFactory.suggestedActions(buttons, message_text);
return await step.prompt(TEXT_PROMPT, { prompt: msg });
return step.next(step.result) //not working
}
else {
logger.info("We dont desambiguate")
return step.next(step.result)
}
}
async answerStep(step) {
logger.info(`FinalAnswer Dialog: answerStep`);
let model_dispatch = step.result.model_dispatch
let result = step.result.result
//Show answer
return await step.endDialog();
}
You can use the step dictionary to store your values. The complex dialogs sample on GitHub is excellent for demonstrating this. https://github.com/microsoft/BotBuilder-Samples/blob/main/samples/javascript_nodejs/43.complex-dialog/dialogs/topLevelDialog.js
You can save data in the context with whatever name you want:
step.values['nameProperty'] = {}
This will be accessible within the entire execution context of the waterfall dialog:
const data = step.values['nameProperty'] // {}

Dialogflow Context

I got some problem, I can't access my parameters from context on dialogflow, i just trying using agent.getContext and agent.context.get but still not work.
there is my code for set the context
function noTelp(agent){
const telp = agent.parameters.phoneNumber;
let query = db.collection('pelanggan').where('no_telp','==',telp);
return query.get().then(snapshot => {
if (snapshot.empty) {
agent.add('Mohon Maaf data no telepon '+telp+' tidak ditemukan');
agent.add('untuk menambahkan data kamu silahkan tuliskan nama kamu');
agent.setContext({ >set the context
name : 'tambahData',
lifespan : 2,
parameters : {noTelp : telp}
});
console.log('No matching documents.');
return;
}
}
and this for the calling the context
function tambahData(agent){
const context = agent.getContext('tambahData'); >get the context
const telp = context.parameters.noTelp; >get the parameters from context
const nama = agent.parameters.nama;
agent.add(nama+telp); >test calling parameters
}
Used a consistent method either from V1 or V2. You can modify the code as below, it will work. I managed to work like this only.
Setting context:
agent.context.set({
name: 'global_main_context',
lifespan: 5,
parameters: param
});
Getting Context
let globalContext = agent.context.get('global_main_context');
I would suggest to keep updating the context in each of transaction because it as lifespan that will automatically kill that context if you cross a number of transactions.

ES6 : Object restructuration for mailchimp api

I want to construct a object base on an array and another object.
The goal is to send to mailchimp api my users interests, for that, I've got :
//Array of skills for one user
const skillsUser1 = ["SKILL1", "SKILL3"]
//List of all my skills match to mailchimp interest group
const skillsMailchimpId = {
'SKILL1': 'list_id_1',
'SKILL2': 'list_id_2',
'SKILL3': 'list_id_3',
}
//Mapping of user skill to all skills
const outputSkills = skillsUser1.map((skill) => skillsMailchimpId[skill]);
console.log(outputSkills);
The problem is after, outputSkill get me an array :
["ID1", "ID3"]
But what the mailchimp api need, and so what I need : :
{ "list_id_1": true,
"list_id_2": false, //or empty
"list_id_3" : true
}
A simple way would be this (see comments in code for explanation):
// Array of skills for one user
const skillsUser1 = ["SKILL1", "SKILL3"]
// List of all my skills match to mailchimp interest group
const skillsMailchimpId = {
'SKILL1': 'list_id_1',
'SKILL2': 'list_id_2',
'SKILL3': 'list_id_3',
}
// Create an output object
const outputSkills = {};
// Use `Object.entries` to transform `skillsMailchimpId` to array
Object.entries(skillsMailchimpId)
// Use `.forEach` to add properties to `outputSkills`
.forEach(keyValuePair => {
const [key, val] = keyValuePair;
outputSkills[val] = skillsUser1.includes(key);
});
console.log(outputSkills);
The basic idea is to loop over skillsMailchimpId instead of skillsUser.
But that is not very dynamic. For your production code, you probably want to refactor it to be more flexible.
// Array of skills for one user
const skillsUser1 = ["SKILL1", "SKILL3"]
// List of all my skills match to mailchimp interest group
const skillsMailchimpId = {
'SKILL1': 'list_id_1',
'SKILL2': 'list_id_2',
'SKILL3': 'list_id_3',
}
// Use `Object.entries` to transform `skillsMailchimpId` to array
const skillsMailchimpIdEntries = Object.entries(skillsMailchimpId);
const parseUserSkills = userSkills => {
// Create an output object
const outputSkills = {};
// Use `.forEach` to add properties to `outputSkills`
skillsMailchimpIdEntries.forEach(([key, val]) => {
outputSkills[val] = userSkills.includes(key);
});
return outputSkills;
}
// Now you can use the function with any user
console.log(parseUserSkills(skillsUser1));

dialogflow with node.js how do you swtich intents

I have an intent that has a required parameter and a fulfilment. When you answer it takes you to my node.js application which currently looks like this:
app.intent(QUESTIONS_INTENT, (conv, params) => {
let data = conv.data;
let categoryId = data.categoryId;
let formulas = data.formulas;
let options = {
'method': 'PUT',
'url': apiUrl + 'questions/filter',
'body': {
categoryId: categoryId,
organisationId: organisation,
formulas: formulas
},
'json': true
};
return request(options).then(response => {
// We need to change how we get these
var questionText = params.questions;
var questions = response.filter(item => item.text === questionText);
data.questions = questions;
conv.ask(questions[0].text);
conv.contexts.set('colour');
}, error => {
conv.ask(JSON.stringify(error));
});
})
Currently it gets the questionText and finds the question that matches what you said. What I want it to do is to swap to a new intent. I have tried by conv.contexts.set('colour') but that doesn't appear to work.
I have an intent setup with input context as "Colour" so I would expect that when my fulfilment completes, it should swap to that intent, but it doesn't.
Can someone help me with this?
You need to make sure that you have a colour intent setup in DialogFlow that will handle the input from the user and respond to them. The question should be asked after you set the context.
return request(options).then(response => {
// We need to change how we get these
var questionText = params.questions;
var questions = response.filter(item => item.text === questionText);
data.questions = questions;
// Sets the context to colour.
conv.contexts.set('colour', 1);
// Now that the context is in control you'll be able to ask a question.
conv.ask(questions[0].text);
You'll also want to provide a lifespan after the context arg. This will make the context active for that many prompts, in the example above I set it for one so your question context will only be active for that specific response.
conv.contexts.set('colour', 1);

Passing user provided value from one intent to other intent in Dialogflow

Team,
In DialogFlow, I getting a value from the user in intent A; (let's say it's the employee ID).
In next Intent B, I want to use the Employee ID (collected in previous intent A) and provide a response and execute a webhook.
I am able to collect the value in Intent A and display in same intent. When tried to pass it to another Intent, I am failing miserably.
Appreciate ayny help in this regard.
Tnx
Sathiya
You will need to use contexts to store the parameters and access these parameters through the context in the other intent.
Check out my full answer here
{
"fulfillmentText":"This is a text response",
"fulfillmentMessages":[ ],
"source":"example.com",
"payload":{
"google":{ },
"facebook":{ },
"slack":{ }
},
"outputContexts":[
{
"name":"<Context Name>",
"lifespanCount":5,
"parameters":{
"<param name>":"<param value>"
}
}
],
"followupEventInput":{ }
}
from NodeJS code
save in first Intent
let param1 = [];
let param2 = {};
let ctx = {'name': '<context name>', 'lifespan': 5, 'parameters': {'param1':param1, 'param2': param2}};
agent.setContext(ctx);
Access in other Intent as
let params = agent.getContext("<context name>").parameters;
let param1 = params.param1;
let param2 = params.param2;

Resources