Nodejs-dialogflow: Where do we need to pass the specific Dialogflow agent's Service Account info and the Google Cloud credentials into this library's sample code on this page?

Created on 3 Aug 2019  Â·  7Comments  Â·  Source: googleapis/nodejs-dialogflow

Where do we need to pass the specific Dialogflow agent's Service Account info and the Google Cloud credentials into this library's sample code on this page?
https://github.com/googleapis/nodejs-dialogflow

Hi All,

I am new to this library. After going over many posts related to this library, I decided to try this sample using this library. But here are some Q on this sample code.
https://github.com/googleapis/nodejs-dialogflow

=============
/
*

  • Send a query to the dialogflow agent, and return the query result.
  • @param {string} projectId The project to be used
    */
    async function runSample(projectId = 'your-project-id') {
    // A unique identifier for the given session

const sessionId = uuid.v4();

For the above code, I guess 'your-project-id' = the project ID of the specific agent to be use with this app.

So, where do we need to pass the specific Dialogflow agent's Service Account info downloaded and our app's Google Cloud credentials into this library's sample code on this page? Lots of researches cannot find correct answer for the above Q. The following page gives some info on this Q, but it does not confirm the correct code to be used in the above sample.
https://stackoverflow.com/questions/55286002/dialogflow-v2-client-library-not-working-error-could-not-load-the-default-cre

All suggestions will be appreciated!

question dialogflow

Most helpful comment

Greetings! This page should mostly cover it:
https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-nodejs

The TL;DR:

  • Download a service account credential file
  • export GOOGLE_APPLICATION_CREDENTIAL=/path/to/keys.json
  • npm start

Alternatively - you can always pass the keyFilename to the constructor of the Dialogflow class:

const client = new dialogflow.AgentsClient({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json',
});

Hope this helps!

All 7 comments

Greetings! This page should mostly cover it:
https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-nodejs

The TL;DR:

  • Download a service account credential file
  • export GOOGLE_APPLICATION_CREDENTIAL=/path/to/keys.json
  • npm start

Alternatively - you can always pass the keyFilename to the constructor of the Dialogflow class:

const client = new dialogflow.AgentsClient({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json',
});

Hope this helps!

@JustinBeckwith Beckwith, Thank you very much for this fast and helpful advice. I am also new with Node.js apps. Here are follow up Q:

This "client": Does this value need to be used some where in this sample code before I run this sample on Firebase platform?

# I followed the steps below to get Google Cloud credentials (Email address + Key IDs); Where should I use them in this sample code?

Select or create a Cloud Platform project.
Enable billing for your project.

Enable the Dialogflow API.

Thanks again!

Update with our experimenting with your suggestions: The auth code below is denied by Dialogflow V2 API

_Hi Justin,

Thank you for your above suggestions.

Our web app is hosted on Firebase. After many hours of experiments on the following solution, we only found this point on the following page: Google Service Account Key cannot be used in Firebase CLI yet. More info on this page: firebase/firebase-tools#787

https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-nodejs
The TL;DR:
Download a service account credential file
export GOOGLE_APPLICATION_CREDENTIAL=/path/to/keys.json
npm start
=========================_

#Then, our app tried the following option
_===============
const client = new dialogflow.AgentsClient({
projectId: 'your-project-id',
keyFilename: '/path/to/keyfile.json',
});
================_
The Error message received from Dialogflow V2 APIs is here:_

==================================
5:03:19.920 PM
dialogflowReply
Function execution started
5:03:19.925 PM
dialogflowReply
userInputEn: hi
5:03:20.820 PM
dialogflowReply
ERROR: { Error: IAM permission 'dialogflow.sessions.detectIntent' on 'projects/ourChatbotId/agent' denied.
5:03:20.820 PM
dialogflowReply
at Http2CallStream.call.on (/srv/functions/node_modules/@grpc/grpc-js/build/src/client.js:96:45)
5:03:20.820 PM
dialogflowReply
at Http2CallStream.emit (events.js:194:15)
5:03:20.820 PM
dialogflowReply
at Http2CallStream.EventEmitter.emit (domain.js:459:23)
5:03:20.820 PM
dialogflowReply
at process.nextTick (/srv/functions/node_modules/@grpc/grpc-js/build/src/call-stream.js:71:22)
5:03:20.820 PM
dialogflowReply
at process._tickCallback (internal/process/next_tick.js:61:11)
5:03:20.820 PM
dialogflowReply
code: 7,
5:03:20.820 PM
dialogflowReply
details:
5:03:20.820 PM
dialogflowReply
'IAM permission \'dialogflow.sessions.detectIntent\' on \'projects/ourChatbotId/agent\' denied.',
5:03:20.820 PM
dialogflowReply
metadata:
5:03:20.820 PM
dialogflowReply
Metadata {
5:03:20.820 PM
dialogflowReply
options: undefined,
5:03:20.820 PM
dialogflowReply
internalRepr: Map { 'grpc-server-stats-bin' => [Array] } } }
5:04:19.923 PM
dialogflowReply
Function execution took 60004 ms, finished with status: 'timeout'
==================================_

Here are the exact code in the Index.js file

Most of the following code is from the sample code on the ReadMe page on this github project.

************************
const dialogflow = require('dialogflow');
const uuid = require('uuid');

const client = new dialogflow.AgentsClient({
   projectId: 'ourChatbotID',

 //We strictly followed the steps on this page to download this private key: https://dialogflow.com/docs/reference/v2-auth-setup
 //So no issue on this private key json
  keyFilename: 'ourchatbotPrivateKeyDownloaded.json',
});


var userInputEn = 'init';
var dialogflowReplyText = express();

dialogflowReplyText.get('/:term/:langs', function (req,res)
{

    userInputEn = req.params.term;
    console.log(`userInputEn: ${userInputEn}`);
    const ChatbotId = 'ourChatbotID';

   const fulfillmentTextReply = runSample(ChatbotId)
      .then(results =>
        {

          res.send(fulfillmentText);

        })//End of .then(results =>
          .catch
          (err => {
            console.error('ERROR:', err);
          });// End of .catch

});//end of this dialogflowReply.get



/**
 * Send a query to the dialogflow agent, and return the query result.
 * @param {string} projectId The project to be used
 */
   async function runSample(projectId)
   {
     // A unique identifier for the given session
      const sessionId = uuid.v4();

    // Create a new session
     const sessionClient = new dialogflow.SessionsClient();
     const sessionPath = sessionClient.sessionPath(projectId, sessionId);

   // The text query request.
    const request =
    {
      session: sessionPath,
     queryInput:
     {
       text:
       {
        // The query to send to the dialogflow agent
        text: userInputEn,
        // The language used by the client (en-US)
        languageCode: 'en-US',
       },
     },// End queryInput:
   };// End const request

  // Send request and log result
  const responses = await sessionClient.detectIntent(request);

  const result = responses[0].queryResult;

  const fulfillmentTextReply = result.fulfillmentText;

   if (result.intent)
   {
             console.log(`  Intent: ${result.intent.displayName}`);
    } else
          {
             console.log(`  No intent matched.`);
           }


    res.send(fulfillmentText;
 }// End of this function: async function runSample
**************************`

Any advice or suggestion will be greatly appreciated! This is very urgent for me to fix the above issue. Thank you!

‘ERROR: { Error: IAM permission 'dialogflow.sessions.detectIntent' on 'projects/ourChatbotId/agent' denied.’

Did you set the proper access role in your account?

Hopefully this reference helps: https://cloud.google.com/iam/docs/permissions-reference

@eGlobeBizCom make sure you've followed this link to enable billing:

https://console.cloud.google.com/flows/enableapi?apiid=dialogflow.googleapis.com

Once you've done so, make sure you download service account credentials and point to these when running an application, like so:

https://cloud.google.com/docs/authentication/getting-started

Note the environment variable GOOGLE_APPLICATION_CREDENTIALS, let me know if this does the trick for you.

@eGlobeBizCom just checking in - did you happen to get your questions answered? Haven't heard anything in a while 🙃

Greetings! This page should mostly cover it:
https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-nodejs

The TL;DR:

  • Download a service account credential file
  • export GOOGLE_APPLICATION_CREDENTIAL=/path/to/keys.json
  • npm start

Alternatively - you can always pass the keyFilename to the constructor of the Dialogflow class:

const client = new dialogflow.AgentsClient({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json',
});

Hope this helps!
For me it was sessionClient !

const sessionClient = new dialogflow.SessionsClient({
            projectId: 'your-project-id',
           keyFilename: '/path/to/keyfile.json',
});
Was this page helpful?
0 / 5 - 0 ratings