-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialogflow.js
52 lines (44 loc) · 1.86 KB
/
dialogflow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { SessionsClient } from '@google-cloud/dialogflow-cx';
export default class Dialogflow {
constructor(projectId, location, agentId) {
this.projectId = projectId;
this.location = location;
this.agentId = agentId;
this.client = new SessionsClient({ apiEndpoint: `${location}-dialogflow.googleapis.com` });
}
/**
* @param {String} sessionId Identifier for the DialogFlow conversation
* @param {String} query User input text to send to the agent
* @param {String} languageCode
* @returns {String} The response to speak to the user
*/
async detectIntentText(sessionId, query, languageCode = 'en') {
const sessionPath = this.client.projectLocationAgentSessionPath(
this.projectId,
this.location,
this.agentId,
sessionId
);
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
},
languageCode,
}
};
const [response] = await this.client.detectIntent(request);
const responseMessages = (response.queryResult.responseMessages ?? []);
const textResponses = responseMessages.filter(m => m.text !== null && m.text !== undefined);
const textResponseStrings = [].concat(...textResponses.map(r => r.text.text));
const matchedIntent = response.queryResult.match.intent?.displayName ?? "NONE MATCHED";
const newPage = response.queryResult.currentPage.displayName;
console.log("Dialogflow agent response:");
console.log(" Agent response(s): ", textResponseStrings);
console.log(" Matched intent: ", matchedIntent);
console.log(" New page: ", newPage);
console.log();
return textResponseStrings.join("\n\n");
}
}