Dialogflow v2 client library not working | Error: Could not load the default credentials - google-api

here is their sample code:
const dialogflow = require('dialogflow');
const uuid = require('uuid');
/**
* 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();
// 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: 'hello',
// 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}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
}
and this code is not working at all, giving Error: Could not load the default credentials :
2019-03-21T16:59:40.099101+00:00 app[web.1]: Message: hi Bilal
2019-03-21T16:59:40.102561+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
2019-03-21T16:59:40.102565+00:00 app[web.1]: at GoogleAuth.<anonymous> (/app/web/node_modules/google-auth-library/build/src/auth/googleauth.js:168:23)
2019-03-21T16:59:40.102568+00:00 app[web.1]: at Generator.next (<anonymous>)
2019-03-21T16:59:40.102570+00:00 app[web.1]: at fulfilled (/app/web/node_modules/google-auth-library/build/src/auth/googleauth.js:19:58)
2019-03-21T16:59:40.102572+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:68:7)
2019-03-21T16:59:40.102691+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
2019-03-21T16:59:40.102784+00:00 app[web.1]: (node:23) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2019-03-21T16:59:55.986568+00:00 app[web.1]: Message: hi Bilal
2019-03-21T16:59:55.986595+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
2019-03-21T16:59:55.986598+00:00 app[web.1]: at GoogleAuth.<anonymous> (/app/web/node_modules/google-auth-library/build/src/auth/googleauth.js:168:23)
2019-03-21T16:59:55.986600+00:00 app[web.1]: at Generator.next (<anonymous>)
2019-03-21T16:59:55.986602+00:00 app[web.1]: at fulfilled (/app/web/node_modules/google-auth-library/build/src/auth/googleauth.js:19:58)
2019-03-21T16:59:55.986605+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:68:7)
2019-03-21T16:59:55.986647+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
they have instructions how to use this library in the repo but it doesnt makes sense https://github.com/googleapis/nodejs-dialogflow
they have not described anywhere how to put credentials while calling detect intent, not eve in the example code here: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/detect.js
I have never seen such irresponsible team like dialogflow team in my life
Update:
exporting env variable solved my problem and now I am getting something back from dialogflow but not as expected, may be they have incorrect code in their repository sample code
this is the code they do have as try an example:
...
// 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}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
...
and in fact result.fulfillmentText does not exist, it is giving me undefined
Update 2
that much effort I have done(see console.logs below) just to understand that instead of responses[0].queryResult.fulfillmentText now they return responses[0].queryResult.fulfillmentMessages and it is not a text string but it is an object which have further values in it that you can see in console.logs below:
...
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
console.log("responses: ", responses)
console.log("responses[0]: ", responses[0])
console.log("responses[0].queryResult: ", responses[0].queryResult)
console.log("responses[0].queryResult.fulfillmentMessages: ", responses[0].queryResult.fulfillmentMessages)
// console.log("responses[0].queryResult.fulfillmentMessages[1]: ", responses[0].queryResult.fulfillmentMessages[1])
console.log("responses[0].queryResult.fulfillmentMessages[0]: ", responses[0].queryResult.fulfillmentMessages[0])
console.log("responses[0].queryResult.fulfillmentMessages[0].text: ", responses[0].queryResult.fulfillmentMessages[0].text)
console.log("responses[0].queryResult.fulfillmentMessages[0].text.text: ", responses[0].queryResult.fulfillmentMessages[0].text.text)
console.log("responses[0].queryResult.fulfillmentMessages[0].text.text[0]: ", responses[0].queryResult.fulfillmentMessages[0].text.text[0])
var fulfilmentText = responses[0].queryResult.fulfillmentMessages[0].text.text[0]
...

The google auth library is looking for an environment variable called
GOOGLE_APPLICATION_CREDENTIALS that points to a JSON credentials file.
You can download that file by following instructions as described in https://dialogflow.com/docs/reference/v2-auth-setup.
The link after the error message has examples of how to set that environment variable:
https://cloud.google.com/docs/authentication/getting-started

Have you tried taking a look at this? You'll need to set up authentication, create a service account key as a .json then have Google Cloud SDK handle it.
https://dialogflow.com/docs/reference/v2-auth-setup
You can also try passing in the service account like this
// Create a new session
const sessionClient = new dialogflow.SessionsClient({keyFilename: "./service_account.json"});

Related

Receiving "Phantom - RPC Error: Transaction creation failed" while building solana escrow with #solana/web3.js

I am trying to replicate https://github.com/dboures/solana-random-number-betting-game
Although when I try to initiate my the Escrow I receive the following error:
Phantom - RPC Error: Transaction creation failed.
Uncaught (in promise) {code: -32003, message: 'Transaction creation failed.'}
I am using Phantom Wallet with Solana RPC.
const transaction = new Transaction({ feePayer: initializerKey })
let recentBlockHash = await connection.getLatestBlockhash();
transaction.recentBlockhash = await recentBlockHash.blockhash;
const tempTokenAccount = Keypair.generate();
// Create Temp Token X Account
transaction.add(
SystemProgram.createAccount({
programId: TOKEN_PROGRAM_ID,
fromPubkey: initializerKey,
newAccountPubkey: tempTokenAccount.publicKey,
space: AccountLayout.span,
lamports: await connection.getMinimumBalanceForRentExemption(AccountLayout.span )
})
);
const { signature } = await wallet.signAndSendTransaction(transaction);
let txid = await connection.confirmTransaction(signature);
console.log(txid);
You're trying to create an account without signing with the keypair of that account to prove ownership.
You have to add the keypair as a signer like such:
await wallet.signAndSendTransaction(transaction, {signers: [tempTokenAccount]})
I was able to solve my problem by using the following code:
const signed = await wallet.request({
method: "signTransaction",
params: {
message: bs58.encode(transaction.serializeMessage())
}
});
const signature = bs58.decode(signed.signature)
transaction.addSignature(initializerKey, signature);
transaction.partialSign(...[tempTokenAccount]);
await connection.sendRawTransaction(transaction.serialize())
instead of:
await wallet.signAndSendTransaction(transaction, {signers: [tempTokenAccount]})
Basically at first I was using one simple function to perform all the above steps, however, for some reason it was not working and throwing the subjected error. When I used this breakdown code it worked!. The cause of the error is still mysterious to me.
Thank you.

NEAR FunctionCallError(HostError(GuestPanic { panic_msg: "panicked at 'Failed to deserialize input from JSON.: Error(\"the account ID is invalid\",

Via CLI, this works: NEAR_ENV=testnet near view dev-1643292007908-55838431863482 nft_tokens_for_owner '{"account_id": "hatchet.testnet"}' and produces the expected result.
I'm now trying to do the same thing via near-api-js but am getting:
Unhandled Runtime Error
Error: Querying [object Object] failed: wasm execution failed with error: FunctionCallError(HostError(GuestPanic { panic_msg: "panicked at 'Failed to deserialize input from JSON.: Error(\"the account ID is invalid\", line: 1, column: 17)', src/contract/nft.rs:65:1" })).
{
"error": "wasm execution failed with error: FunctionCallError(HostError(GuestPanic { panic_msg: \"panicked at 'Failed to deserialize input from JSON.: Error(\\\"the account ID is invalid\\\", line: 1, column: 17)', src/contract/nft.rs:65:1\" }))",
"logs": [],
"block_height": 81208522,
"block_hash": "5vWcrkVjshewYgLZTTHTZgLN7SF3qpYPovnPUUM1ucBt"
}
Call Stack
JsonRpcProvider.query
node_modules/near-api-js/lib/providers/json-rpc-provider.js (123:0)
async Account.viewFunction
node_modules/near-api-js/lib/account.js (366:0)
I've tried multiple totally separate approaches using near-api-js, and they both result in this error.
My current approach is:
export type NFT = Contract & {
nft_mint: (args: any, gas: any, depositAmount: any) => Promise<any>; // TODO Add types
nft_token: (args: any) => Promise<any>;
nft_tokens_for_owner: (args: any) => Promise<any>;
};
export function getNftContract(account: Account) {
const contract = new Contract(
account, // the account object that is connecting
certificateContractName,
{
viewMethods: ['nft_token', 'nft_tokens_for_owner'], // view methods do not change state but usually return a value
changeMethods: ['nft_mint'], // change methods modify state
},
);
return contract;
}
async function getCertificates(accountId: string): Promise<string[]> {
const keyStore = new BrowserLocalStorageKeyStore();
const near = await getNearConnection(keyStore);
const account = new Account(near.connection, ''); // account_id not required for 'view' call
const contract = getNftContract(account);
const response = await (contract as NFT).nft_tokens_for_owner({ account_id: accountId });
console.log({ account, accountId, response });
return []; // TODO
}
I'm using testnet, and the accountId I'm passing is hatchet.testnet.
This was a good lesson for me.
I started looking at the source code of https://docs.rs/near-sdk/3.1.0/src/near_sdk/json_types/account.rs.html#63 and https://docs.rs/near-sdk/3.1.0/src/near_sdk/environment/env.rs.html#816-843
I homed in on that "The account ID is invalid" error message.
But I knew I was passing a valid account ID.
It turns out the problem had nothing to do with NEAR. It was a Next.js / React problem:
My component's account_id was temporarily empty and trying to call nft_tokens_for_owner too soon (i.e. before account_id had been populated with a value).

AWS Textract does not run callback in error free run of analyzeDocument

CURRENTLY
I am trying to get AWS Textract working on a Lambda function and am following documentation on https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Textract.html#analyzeDocument-property
My Lambda code:
"use strict";
const AWS = require("aws-sdk");
exports.handler = async (event) => {
let params = JSON.parse(event.body);
console.log("Parse as document...");
let textract = new AWS.Textract();
let doc = params["doc"];
let config = {
Document: {
Bytes: doc,
}
};
textract.analyzeDocument(config, function (err, data) {
console.log("analyzing..."); //<-- nothing logged to console if no error
if (err) {
console.log(err, err.stack);
}
// an error occurred
else {
console.log("data:" + JSON.stringfy(data)); //<-- nothing logged to console if no error
} // successful response
});
console.log("Finished parsing as document.");
};
ISSUE
I cannot get the data back from Textract. It seems I am unable to get the callback working entirely. What's odd is if there is an error e.g. my configuration is wrong, the error handling of the callback will print the log and "analyzing..." log, but without error, none of the logs in the callback print.
Current Logs:
Parse as document...
Finished parsing as document.
Expected / Desired Logs:
Parse as document...
analyzing...
data:{textract output}
Finished parsing as document.
Please help!
NOTES
I am using a role for that Lambda that allows it to access Textract.
I get the same result whether I include the HumanLoopConfig settings or not.
Solved, apparently I needed to setup a promise:
let data = await textract.analyzeDocument(config).promise()
console.log("data:"+data );
console.log("Finished parsing as document.")

Possible unhandled promise rejection warning with useMutation

I'm getting an unhandled promise rejection error when I use useMutation with react native. Here's the code producing the issue:
const [createUser, { error, loading }] = useMutation(CREATE_USER_MUTATION);
Anytime my graphql server returns an error to the client I get an unhandled promise rejection error (screenshot below). I'm able to make it go away by adding an error handler like so, but it seems like a hack. Any thoughts? Am I doing something wrong or is this something that should be addressed by the apollo folks?
const [createUser, { error, loading }] = useMutation(CREATE_USER_MUTATION, {
onError: () => {}
});
Your createUser mutation is a promise you should handle error inside try catch block, or in upper scope inside apollo-link-error onError method.
const [createUser, { data, loading }] = useMutation(CREATE_USER_MUTATION, {
onError: (err) => {
setError(err);
}
});
With this we can access data with loading and proper error handling.

Cognito post verification lambda call causes failure

I have a lambda function that is invoked when a cognito user submits their verification code.
PostConfirmation failed with error RequestId: 3241xxxx-3cxx-11xx-aexx-8b39059xxxxx Process exited before completing request.
at constructor.e (<anonymous>:21:4685)
at constructor.callListeners (<anonymous>:21:24558)
at constructor.emit (<anonymous>:21:24267)
at constructor.emitEvent (<anonymous>:21:18671)
at constructor.a (<anonymous>:21:14521)
at d.runTo (<anonymous>:22:12444)
at <anonymous>:22:12651
at constructor.<anonymous> (<anonymous>:21:14731)
at constructor.<anonymous> (<anonymous>:21:18726)
at constructor.callListeners (<anonymous>:21:24664)
And my lambda function's job is to receive that submission and publish a message to SQS, and then continue.
module.exports.trigger_userVerified = (event, context, callback) => {
const AWS = require('aws-sdk');
var nickname = event.request.userAttributes.nickname;
var params = {
MessageBody: 'A user has registered an account and has supplied a website address.',
QueueUrl: ' https://sqs.us-east-1.amazonaws.com/xxx/my_sqs_queue',
DelaySeconds: 0,
MessageAttributes: {
'nickname': {
DataType: 'String',
StringValue: nickname
}
}
};
sqs.sendMessage(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
context.done(null, event);
});
};
Is there something wrong with the way I'm handling this lambda function that causes this error? how do I investigate further?
The error "Process exited before completing request" means that the lambda Javascript function exited before calling context.done (or context.succeed, etc.). Most of the times this means that there is an error in the function.
I'm not a Javascript expert (at all) so there may be more elegant ways to find the error but my approach has been to put a bunch of console.log messages in my code, run it, and then look at the logs. I can usually zero in on the offending line and, if I look at it long enough, I can usually figure out my mistake.
Since it's lambda:
Please check your cloudwatch logs and see if you can find more. In your place I would add some console.log statements as well.

Resources