How to set dialogflow context from node.js dialogflow package - node.js

I am using sessionClient.detectIntent() to send text to dialogflow and it is working fine, now I want to send context too with the text. How can I do that?

I usually create contexts in the following way:
exports.createContext = async function(contextId, parameters, sessionPath, sessionId, lifespan = 333) {
let contextPath;
try {
contextPath = contextClient.contextPath(projectId, sessionId, contextId);
} catch (e) {
console.error("Error => ");
console.error(e)
}
const request = {
parent: sessionPath,
context: {
name: contextPath,
parameters: struct.encode(parameters),
lifespanCount: lifespan
}
};
contextClient.createContext(request)
};
And simply call this method when I have to create a context before I call the detectIntent method:
bot.createContext('CONTEXT_NAME_GOES_HERE', '{PARAMETER: VALUE}', sessionPath, session_id, lifespan = 1);

You can send contexts on detectIntent alongside with the Query Text by adding it on the context array field under queryParams. Note that this method of sending context via detectIntent will create (if not created) and activates the context before the query is executed.
You can refer to the code snippet below:
const dialogflow = require('#google-cloud/dialogflow');
/**
* Send a query and a context to the Dialogflow agent, and return the query result.
* #param {string} projectId The project to be used
*/
async function detectIntent(projectId, sessionId, text) {
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryParams:{
//List of context to be sent and activated before the query is executed
contexts:[
{
// The context to be sent and activated or overrated in the session
name: `projects/${projectId}/agent/sessions/${sessionId}/contexts/CONTEXT_NAME`,
// The lifespan of the context
lifespanCount: 8
}
]
},
queryInput: {
text: {
// The query to send to the dialogflow agent
text: text,
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
console.log(` Output Contexts: ${JSON.stringify(result.outputContexts)}`)
}
detectIntent("PROJECT_ID","SESSION_ID","TEXT_QUERY");
Output:
Detected intent
Query: Hi
Response: Hello! How can I help you?
Output Contexts: [{"name":"projects/PROJECT_ID/agent/sessions/SESSION_ID/contexts/CONTEXT_NAME","lifespanCount":7,"parameters":null}]

Related

For some reason when using the dialogflow detectIntent googleapi, I keep getting default fallback intent even though other api's like listIntents work

Has anyone experienced this issue?
I am sure the dialogflow connection works because listing the intents works which is (intentsClient.listIntents(request)) and it gives me back all the intents from my dialogflow es agent. So it looks like the credentials should be fine.
Any help would be highly appreciated,
Thanks
const dialogflow = require('#google-cloud/dialogflow').v2;
const uuid = require('uuid');
const sessionId = uuid.v4();
const sessionClient = new dialogflow.SessionsClient({ keyFilename: '..........' });
const sessionPath = sessionClient.projectAgentSessionPath(
projectId,
sessionId
);
const query = 'What are the pets rules';
async function detectIntentForQuestion() {
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: 'en-US',
},
},
queryParams: {
sentimentAnalysisRequestConfig: {
analyzeQueryTextSentiment: true,
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(' No intent matched.');
}
if (result.sentimentAnalysisResult) {
console.log('Detected sentiment');
console.log(
` Score: ${result.sentimentAnalysisResult.queryTextSentiment.score}`
);
console.log(
` Magnitude: ${result.sentimentAnalysisResult.queryTextSentiment.magnitude}`
);
} else {
console.log('No sentiment Analysis Found');
}
};
you are setting languageCode: 'en-US' for language. Does your agent support this language? If it is set using a different language (ie. Spanish), then it is expected to give you back only the fallback intent response.
other thing that you can do is checking at https://dialogflow.cloud.google.com/#/agent/<your agent name>/history and in your last interactions, you click on the 3 dots in the agent response and go to Raw interaction log. There you can see the information the agent got from your code, how it was interpreted by the agent and how it answered you back.

Error : Dialogflow server in 'us' received request for resources located in 'europe-west2-dialogflow.googleapis.com.'

I want to detect an intent with dialogflow, but my dialogflow agent's region is europe-west2 for some reasons. So to specify a location, I use the version v2beta1 of Dialogflow API like described in the documentation. But it doesn't worked and I have the following error Dialogflow server in 'us' received request for resources located in 'europe-west2-dialogflow.googleapis.com.
Code :
const sessionId = crypto.randomBytes(16).toString("hex");
// Create a new dialogflow session
const sessionClient = new Dialogflow.SessionsClient(this.dialogFlowConfig)
const sessionPath = sessionClient.projectLocationAgentSessionPath(this.projectId, "europe-west2-dialogflow.googleapis.com", sessionId);
// The text query request.
const dfRequest = {
session: sessionPath,
queryInput: {
event: {
name: "Welcome",
languageCode: DialogFlowService.LANGUAGE_CODE
}
}
}
try {
const responses = await sessionClient.detectIntent(dfRequest);
const result = responses[0].queryResult!;
Logger.debug(` Query: ${result.queryText}`);
Logger.debug(` Response: ${result.fulfillmentText}`);
if (result.intent) {
Logger.debug(` Intent: ${result.intent.displayName}`);
} else {
Logger.debug(` No intent matched.`);
}
return result
I had the similar issue, but the below config worked to access dialogflow agent's in region europe-west2
Set the Location as "europe-west2"
Also need to set the
SessionsClient's 'apiEndpoint' as
"europe-west2-dialogflow.googleapis.com"
const sessionClient = new dialogflow.SessionsClient({ apiEndpoint: "europe-west2-dialogflow.googleapis.com" });
const sessionPath = sessionClient.projectLocationAgentSessionPath(
projectId,
"europe-west2",
sessionId
);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: languageCode,
},
},
};
Try to use 'europe-west2' as location. More docs here.

how to run the dialogflow node js?

i am still confused about the documentation on Dialogflow nodejs, can I get clear for this?
I have read the documentation this -> https://cloud.google.com/dialogflow/docs/reference/rest/v2/projects.agent.sessions/detectIntent
how to test my code and see the result of my query I input then ?
should I do POST via Axios inside this functions
async function runSample(projectId = 'your-project-id') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hello',
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
}
i still not get clear for this, so do we need use HTTP request also in local to check this?
I already follow the Dialogflow nodejs example, but what next?
it said on google we must POST to
POST https://dialogflow.googleapis.com/v2/{session=projects//agent/sessions/}:detectIntent
nd the req body is on the request variable inside that functions,
but I still not clear on dialogflow nodejs for the next step to run that method
You can run this directly using the express app. Just call this function from your express app route or you can call the given function in the file and use node <filename.js> to run the code. Make sure you add your google cloud credentials in the path name using process.env.GOOGLE_APPLICATION_CREDENTIALS = "<your_json_file_path>";
const sessionClient = new dialogflow.SessionsClient(
// below can be used to set the variable in code itself, if below is not working you can run following in the terminal
//export GOOGLE_APPLICATION_CREDENTIALS="/<path of the json file"
{
keyFilename: "/<path of the json file"
}
);

Possibility to send context data to dialogflow without webhook being called from Dialogflow, but from server itself

Currently I have a webhook which is being called from Dialogflow (fulfillment) and checks which intent is currently applicable. (I do everything via JSON) once I know which Intent, I send back (via the webhook) a JSON response. I was wondering if it is possible to initiate a JSON object and send it to Dialogflow. (I want to send context without letting the user type first and Dialogflow receiving a fallback) (NodeJS Server -> Dialogflow) Currently the only way I can do it is (Dialogflow -> NodeJS Server (JSON object with contex) -> Dialogflow)
CURRENT:
var dialog_flow = {
// Create context using Google dialogflow
createContext: async function(projectId, sessionId, contextId, parameters, lifespanCount){
console.log("params to be sent: ", parameters);
//Instantiates client to create the actual context before sending
const contextsClient = new dialogflow.ContextsClient({
keyFilename: './dialogflow_credentials.json'
});
const sessionPath = contextsClient.sessionPath(projectId, sessionId);
const contextPath = contextsClient.contextPath(
projectId,
sessionId,
contextId
);
const createContextRequest = {
parent: sessionPath,
context: {
name: contextPath,
lifespanCount: lifespanCount,
parameters: parameters
},
};
const response = await contextsClient.createContext(createContextRequest);
console.log(`Created ${response[0].name}`);
}
};
PARAMETERS:
let testobj = {
firstname: 'test name',
lastname: 'itworks!!',
dd: 'fgfgf',
ff: 'fgfg'
}
You can call directly Dialogflow from Node.js, without the need of receiving a webhook. For that you will need to use the dialogflow package.
const sessionClient = new dialogflow.SessionsClient();
const session = sessionClient.sessionPath(projectId, sessionId);
const request = {
session,
queryInput: {
text: {
text: 'Some text'
}
},
queryParams: {
contexts: [context] // here you send the data
}
};
sessionClient.detectIntent(request)
.then(console.log)
.catch(console.error);
In order to send a context, with data, you will need to use dialogflow.ContextsClient
I give a detailed explanation about that in these other questions:
set input or output context dialogflow nodejs v2
Dialogflow pass parameters through NodeJS
And in order to authenticate the client you can check:
Dialogflow easy way for authorization
UPDATE: 2 weeks ago, Dialogflow, removed the structjson.js sample from the repository, but in favor of an npm package to handle the encoding/decoding of the protobuf struct: pb-util

Dialogflow Node SDK permission fail (dialogflow.sessions.detectIntent)

I got a problem with Node DialogFlow API integration.
I can not have the necessary permissions to make calls to the API, although I have followed all possible documentation.
Here is my Agent Service Account from Dialogflow admin :
Then the Service Account roles :
The "Client de l'API Dialogflow" role detail, where we can see "dialogflow.sessions.detectIntent" :
And finally, the Node error after downloading the JSON file corresponding to the Service Account :
Am I missing something ?
I tried to generate other JSON files, create other Service Accounts, nothing worked...
The Node script is simple, just pasted from the official tutorial :
const projectId = 'newagent-9e77e '; //https://dialogflow.com/docs/agents#settings
const sessionId = 'quickstart-session-id';
const query = 'bonjour';
const languageCode = 'fr-FR';
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: languageCode,
},
},
};
// Send request and log result
sessionClient
.detectIntent(request)
.then(responses => {
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
})
.catch(err => {
console.error('ERROR:', err);
});
Thanks !
The problem was on space on the "projectId" constant.
Shame on me.

Resources