Hey all, I’m looking for info on for to create session entities using the Dialogflow marketplace plugin. I’ve been able to do it with the Google Assistant as shown in these docs, but not with vanilla dialogflow that’s not using the Google Assistant. Is there a way to achieve this other than modifying the output JSON?
Cheers.
Session Entities and Dialogflow Plugin
Thamilton
#1
Max
#2
Hello there,
for a project, I’ve implemented a small Plugin to do that for Dialogflow.
Here’s the code of the plugin:
import {
AxiosRequestConfig,
ErrorCode,
HttpService,
Jovo,
JovoError,
Plugin,
PluginConfig,
} from 'jovo-core';
export interface DialogflowClientMethodOptions {
authToken: string;
projectId: string;
sessionId: string;
}
export interface DialogflowEntity {
value: string;
synonyms: string[];
}
export interface DialogflowClientPayload {
name: string;
entityOverrideMode: 'ENTITY_OVERRIDE_MODE_OVERRIDE' | 'ENTITY_OVERRIDE_MODE_SUPPLEMENT';
entities: DialogflowEntity[];
}
const BASE_URL = 'https://dialogflow.googleapis.com';
export class DialogflowClient {
async addSessionEntities(
options: DialogflowClientMethodOptions & { data: DialogflowClientPayload },
) {
const subPath = `projects/${options.projectId}/agent/sessions/${options.sessionId}/entityTypes`;
const path = `/v2/${subPath}`;
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${options.authToken}`,
};
const config: AxiosRequestConfig = {
baseURL: BASE_URL,
url: path,
data: {
...options.data,
name: `${subPath}/${options.data.name}`,
},
method: 'POST',
headers,
validateStatus: (status) => {
return true;
},
};
try {
const response = await HttpService.request(config);
if (response.status === 200 && response.data) {
return response.data;
}
throw new JovoError(
'Could not add session entities!',
ErrorCode.ERR_PLUGIN,
'DialogflowClient',
`Response: ${response.status} ${
response.data ? JSON.stringify(response.data, undefined, 2) : 'undefined'
}`,
);
} catch (e) {
throw new JovoError(
e.message || e,
ErrorCode.ERR_PLUGIN,
e.module || 'DialogflowClient',
e.details,
e.hint,
e.seeMore,
);
}
}
}
declare module 'jovo-core/dist/src/core/Jovo' {
interface Jovo {
$dialogflow: DialogflowClient;
}
}
export interface Config extends PluginConfig {}
export class DialogflowPlugin implements Plugin {
config: Config = {
enabled: true,
};
name: string = this.constructor.name;
install(parent: object): void {
Jovo.prototype.$dialogflow = new DialogflowClient();
}
}
How to use it:
- Include it in the app.ts
app.use(new DialogflowPlugin())
- Call the
addSessionEntities
-method from within a Jovo-handler:
await this.$dialogflow.addSessionEntities({
projectId,
authToken,
sessionId,
data: {
name: 'EntityName',
entities: [...],
entityOverrideMode: 'ENTITY_OVERRIDE_MODE_SUPPLEMENT'
},
});
The data-object is the same as for session-entities in Google-Assistant.
I hope it helps and if you have any questions, just let me know.