DialogFlow V1 to V2, GCP Authentication and Accessing APIs by 3 ways.
As everybody knows this warning for dialogFlow V1 version:
The warning was from dialogFlow website before 23 OCT.
Warning: V1 of dialogFlow’s API will be shut down on October 23, 2019.
After 23 OCT its:
Caution: Your project will have an existing service account, but this should not be altered. For additional client and developer API access, you should create a new service account.
DialogFlow Docs: https://dialogflow.com/docs/reference/v2-auth-setup
So our venerated client hoisted disquiet over Dialogflow API version v1 and to get version v2 as early as possible in production before 23 October. As there was less information on the internet and this V2 is under the Google Cloud Platform (GCP). Our team was stimulated to go through GCP. Our thinking was GCP authentication will be like self-explanatory functionality flow but it was very immense.
So to convert Dialogflow v1 to v2 was having less information source, so we decided to write this article, which may help others.
There are 3 ways to implement V2 :
Environment variable ‘Google_Application_Credentia’ is an ENV for every API request, GCP authenticates it for user/account service(same as a ‘Bearer token’ for ajax call).
- Using libraries/packages without ENV var & SDK installation,
- Using libraries/packages using ENV var & without SDK installation,
- By installing Google SDK (using ENV var)
So, firstly we started with creating a new agent in Dialogflow (Agent is created under dialogFlow v2)
- Created the agent — default is V2 now.
- Enabled V2 beta features.
- Downloaded private key JSON file from the GCP service account.
Private key JSON file is same as a user-access token to authenticate the API request in version V1. Private key is for credential verification for the specific GCP account.
- Below is the downloaded private key JSON file (.json)
{
“type”: “<>”, “project_id”: “<>”, “private_key_id”: “<>”, “private_key”: “ <>”, “client_email”: “<>”, “client_id”: “<>”, “auth_uri”: “<>",
“token_uri”: “<>", “auth_provider_x509_cert_url”: “<>",
“client_x509_cert_url”: “<>"
}
* Using libraries/packages with/without ENV var & SDK installation :
For installing libraries, you can install via composer, for Nodejs via ‘ npm I dialogflow’
Import all client libraries/packages needed for CRUD API operation.
Authentication libraries:
Google\Cloud\Storage\StorageClient
Dialogflow libraries:
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\CreateIntentRequest;
use Google\Cloud\Dialogflow\V2\Intent;
use Google\Cloud\Dialogflow\V2\IntentsClient;
use Google\Cloud\Dialogflow\V2\sessionPath;
use Google\Cloud\Dialogflow\V2\RequestParamsHeaderDescriptor;
use Google\Cloud\Dialogflow\V2\Intent_TrainingPhrase_Part;
use Google\Cloud\Dialogflow\V2\Intent_TrainingPhrase;
use Google\Cloud\Dialogflow\V2\Intent_Message_Text;
use Google\Cloud\Dialogflow\V2\Intent_Message;
Setting Credentials(Mandatory)
1.Without ENV variable (Without ENV will be easy for implementation)
//Setup Credentials$credentialObject = array('credentials' => 'path of <private key json file here>');
$sessionsClient = new SessionsClient($credentialObject);
$session = $sessionsClient->sessionName('<ProjectID>', '<SessionId>');
2.With ENV variable:
Set downloaded Private key JSON file path in ENV var ‘GOOGLE_APPLICATION_CREDENTIALS’
putenv
function is just one way to set an environment variable.
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
CRUD APIs methods are same for above both ways, with/without ENV:
Get Specific INTENT
/** TO GET SPECIFIC INTENT **/$textInput = new TextInput();$textInput->setText('What is login');$textInput->setLanguageCode('en-US');$queryInput = new QueryInput();$queryInput->setText($textInput);//request$response = $sessionsClient->detectIntent($session, $queryInput);//response$intentResponse = $response->getQueryResult();$intent = $intentResponse->getIntent();$displayName = $intent->getDisplayName();$fulfilmentText = $intentResponse->getFulfillmentText();
List All INTENTS
/** LISTING ALL INTENTS **/$intentObject = new IntentsClient($credentialObject);$agentNameObject = $intentObject->projectAgentName('<projectID>');$intents = $intentObject->listIntents($agentNameObject);foreach ($intents->iterateAllElements() as $intent) {// print relevant infoprintf('Intent name: %s' . PHP_EOL, $intent->getName());printf('Intent display name: %s' . PHP_EOL, $intent->getDisplayName());printf('Action: %s' . PHP_EOL, $intent->getAction());printf('Root followup intent: %s' . PHP_EOL,$intent->getRootFollowupIntentName());printf('Parent followup intent: %s' . PHP_EOL,$intent->getParentFollowupIntentName());print('Input contexts: ' . PHP_EOL);foreach ($intent->getInputContextNames() as $inputContextName) {printf("\t Name: %s" . PHP_EOL, $inputContextName);}print('Output contexts: ' . PHP_EOL);foreach ($intent->getOutputContexts() as $outputContext) {printf("\t Name: %s" . PHP_EOL, $outputContext->getName());}}
Delete INTENT
/** Delete Intent **/$intentId = $intentObject->intentName('<projectID>', '<intentID>');$intentObject->deleteIntent($intentId);
Create New INTENT
/** Create Intent **/$disaplayName = "Where is Goa";$utterances = ["test", "test1", "test3", "test4"];// prepare training phrases for intent$trainingPhrases = [];foreach ($utterances as $trainingPhrasePart) {$part = new Intent_TrainingPhrase_Part();$part->setText($trainingPhrasePart);// create new training phrase for each provided part$trainingPhrase = new Intent_TrainingPhrase();$trainingPhrase->setParts([$part]);$trainingPhrases[] = $trainingPhrase;}$messageTexts = 'Goa is in India.';// prepare messages for intent$text = new Intent_Message_Text();$text->setText([$messageTexts]);$message = new Intent_Message();$message->setText($text);$createIntentObject = $intentObject->projectAgentName('<projectID>', '<sessionID>');// prepare intent$intent = new Intent();$intent->setDisplayName($disaplayName);$intent->setTrainingPhrases($trainingPhrases);$intent->setMessages([$message]);$response = $intentObject->createIntent($createIntentObject, $intent);printf('Intent created: %s' . PHP_EOL, $response->getName());$intent_id = $response->getName();$intent_id = explode('/',$intent_id);$intent_id = $intent_id[sizeof($intent_id)-1];
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
* By installing Google SDK (ENV var is important) :
- Install Google SDK
- Set downloaded private key JSON file in system properties/Advanced/Environment Variables/System Variables.
- To get Access Token run this ‘ gcloud auth application-default login’ with your dialogflow account service and then run ‘gcloud auth application-default print-access-token’ in CMD, you will get the token and set it in Request Header(Authorization) in ajax call
- Below are the all CRUD APIs (AJAX call)
Create New INTENT
var body = {‘displayName’: ‘Where is WORLD?’,‘priority’: 500000,‘trainingPhrases’: [{‘type’: ‘EXAMPLE’,‘parts’: [{‘text’: ‘WORLD location’}]}],‘action’: ‘start’,‘messages’: [{‘text’: {‘text’: [‘WORLD is in …..’]}}]};$.ajax({
url: ‘https://dialogflow.googleapis.com/v2/projects/ekotro-new-ahogkr/agent/intents',type: ‘POST’,beforeSend: function (xhr) {
xhr.setRequestHeader(‘Authorization’, ‘Bearer ya29.c.ElpkB8jBiV1fQrHfbcqkert6lIjRhCx2wjwZ3Ptj71wVwZ9IItyPNKjcPt0_9yvqXLAWMwof-Ek5x3WG0_x1gkAJDAXW1p0GYlAhj7Ur-Cxz4LDuTZ4wZMPI_s’);xhr.setRequestHeader(“Content-Type”, “application/json”);
},data: body,success: function () {},error: function () { },});
Update Specific INTENT
var updateBody = {‘displayName’: ‘Where was Siddharth today?’,};$.ajax({
url: ‘https://dialogflow.googleapis.com/v2/projects/ekotro-new-ahogkr/agent/intents/16c5771e-698f-47f5-9160-300012c9dfec',type: ‘PATCH’,beforeSend: function (xhr) {
xhr.setRequestHeader(‘Authorization’, ‘Bearer ya29.c.ElpkB8jBiV1fQrHfbcqk3453456lIjRhCx2wjwZ3Ptj71wVwZ9IItyPNKjcPt0_9yvqXLAWMwof-Ek5x3WG0_x1gkAJDAXW1p0GYlAhj7Ur-Cxz4LDuTZ4wZMPI_s’);xhr.setRequestHeader(“Content-Type”, “application/json”);},data:updateBody,success: function () {},error: function () { },});
List All INTENTS
$.ajax({
url: ‘https://dialogflow.googleapis.com/v2/projects/ekotro-new-ahogkr/agent/intents',type: ‘GET’,
beforeSend: function (xhr) {
xhr.setRequestHeader(‘Authorization’, ‘Bearer ya29.c.ElpkB8jBiV1fQrHfbcqk4dfdfg6lIjRhCx2wjwZ3Ptj71wVwZ9IItyPNKjcPt0_9yvqXLAWMwof-Ek5x3WG0_x1gkAJDAXW1p0GYlAhj7Ur-Cxz4LDuTZ4wZMPI_s’);xhr.setRequestHeader(“Content-Type”, “application/json”);},
success: function () {},error: function () { },});
To get specific INTENT
var body = {“queryInput”: {“text”: {“text”: “what is login?”,“languageCode”: “en”}}}$.ajax({
url: ‘https://dialogflow.googleapis.com/v2/projects/ekotro-new-ahogkr/agent/sessions/14387876443543/:detectIntent',type: ‘POST’,beforeSend: function (xhr) {xhr.setRequestHeader(‘Authorization’, ‘Bearer ya29.c.ElpwB66EhNQpZvqadsfsdfNfD3lTyk5ztPDRU-urfL9hDr0mni28BFF6pHQa-mJryCQNOH6kQzGGmCJj4S3s44Qe5bc6r-zpCIG710FJ4Fzx5c0fBZKFIABXMlOvSg’);xhr.setRequestHeader(“Content-Type”, “application/json”);},data:body,success: function (result) {
console.log(result);console.log(result.queryResult)
},error: function () { },});
To delete specific INTENT
$.ajax({url: ‘https://dialogflow.googleapis.com/v2/projects/ekotro-new-ahogkr/agent/intents/d759940d-2aee-44af-b8d8-5b0d7d1988d1',
type: ‘DELETE’,
beforeSend: function (xhr) {
xhr.setRequestHeader(‘Authorization’, ‘Bearer ya29.c.ElpkB8jBiV1fQrfddsfsdftert4OVx6lIjRhCx2wjwZ3Ptj71wVwZ9IItyPNKjcPt0_9yvqXLAWMwof-Ek5x3WG0_x1gkAJDAXW1p0GYlAhj7Ur-Cxz4LDuTZ4wZMPI_s’);xhr.setRequestHeader(“Content-Type”, “application/json”);},
success: function () {},error: function () { },});
So finally you will get the result for migrating DialogFlow V1 to V2.
This article will help you to implement using Google SDK and with/without ENV variable for libraries/packages.