Reputation: 181
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?
Upvotes: 1
Views: 1250
Reputation: 413
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}]
Upvotes: 1
Reputation: 732
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);
Upvotes: 3