I am using dialogflow
NPM module and I want to send input/output context
but I am not sure how to do.
I know I can do in google-assistant
NPM with
I can set contexts
with parameter
using below method,
const parameters = { // Custom parameters to pass with context
welcome: true,
};
conv.contexts.set('welcome-context', 5, parameters);
In order to send a context using the Dialogflow NPM module, you have to first create a context, using dialogflow.ContextsClient
and then send it on the query.
To convert the parameters to the format required by Dialogflow you will need to use this module: pb-util
const dialogflow = require('dialogflow');
const { struct } = require('pb-util');
const projectId = 'projectId';
const contextsClient = new dialogflow.ContextsClient();
const sessionClient = new dialogflow.SessionsClient();
async function createContext(sessionId, contextId, parameters, lifespanCount = 5) {
const sessionPath = contextsClient.sessionPath(projectId, sessionId);
const contextPath = contextsClient.contextPath(
projectId,
sessionId,
contextId
);
const request = {
parent: sessionPath,
context: {
name: contextPath,
parameters: struct.encode(parameters)
lifespanCount
}
};
const [context] = await contextsClient.createContext(request);
return context;
}
function sendQuery(sessionId, query, context) {
const session = sessionClient.sessionPath(projectId, sessionId);
const request = {
session,
queryInput: {
text: {
text: query
}
},
queryParams: {
contexts: [context] // You can pass multiple contexts if you wish
}
};
return sessionClient.detectIntent(request);
}
(async() => {
const parameters = { // Custom parameters to pass with context
welcome: true
};
const sessionId = 'my-session';
const context = await createContext(sessionId, 'welcome-context', parameters);
const response = await sendQuery(sessionId, 'Hi', context);
console.log(response);
})();
Have in mind that you send an input context. The output context is generated in the intent.
If you have trouble authenticating the clients SessionClient
& ContextClient
you can check this other question: Dialogflow easy way for authorization