How to create the intent via code in dialogflow? - nlp

I am beginner in dialogflow and trying to create intent and context through code, but i am unable to achieve it.This is the code i am using,
i referred the below link also but no help,
https://cloud.google.com/dialogflow/es/docs/how/manage-intents#create_intent
but getting below error:
function main(
projectId = 'trainer-gulw',
displayName = 'intent_001',
trainingPhrasesParts = [
'Hello, What is weather today?',
'How is the weather today?',
],
messageTexts = ['Rainy', 'Sunny']
) {
const dialogflow = require('#google-cloud/dialogflow');
// Instantiates the Intent Client
const intentsClient = new dialogflow.IntentsClient();
async function createIntent() {
// Construct request
// The path to identify the agent that owns the created intent.
const agentPath = intentsClient.projectAgentPath(projectId);
const trainingPhrases = [];
trainingPhrasesParts.forEach(trainingPhrasesPart => {
const part = {
text: trainingPhrasesPart,
};
// Here we create a new training phrase for each provided part.
const trainingPhrase = {
type: 'EXAMPLE',
parts: [part],
};
trainingPhrases.push(trainingPhrase);
});
const messageText = {
text: messageTexts,
};
const message = {
text: messageText,
};
const intent = {
displayName: displayName,
trainingPhrases: trainingPhrases,
messages: [message],
};
const createIntentRequest = {
parent: agentPath,
intent: intent,
};
// Create the intent
const [response] = await intentsClient.createIntent(createIntentRequest);
console.log(`Intent ${response.name} created`);
}
createIntent();
// [END dialogflow_create_intent]
}
TIA

From the screen shot, it looks like you're running this on your local machine. The error message suggests that the environment variables that point to your credentials isn't setup.
See the Before you Begin section of the library documentation for how to setup that environment. One of the steps includes setting up authentication by downloading credentials and setting an environment variable to point to them. This will also set the project ID you're working with.

Related

Create and handle multiple session for multiple users while making web socket connection in Microsoft Bot Builder

I am new to Microsoft Bot Framework .I have created a bot using Microsoft Bot Framework. How do I create a session for individual user. Currently the problem I am facing is whenever multiple users are creating connection, the values in the variables are getting over written thus giving wrong values to the users.
Here is the code
if (turnContext.activity.text === 'CCP') {
const url = await this.connectToAgent(members);
const initialMessage = {
topic: "aws/subscribe",
content: {
topics: ["aws/chat"]
}
};
ws = new WebSocket(url[1]);
ws.addEventListener("open", () => {
ws.send(JSON.stringify(initialMessage));
});
await turnContext.sendActivity("Please wait while we connect you to an agent.");
conversationReferences[currentUser] = TurnContext.getConversationReference(turnContext.activity);
adapter = turnContext.adapter;
ws.addEventListener('message', async function (event) {
const msg = JSON.parse(event.data);
});
let sendChatHistory = (function() {
let executed = false;
return function() {
if (!executed) {
executed = true;
const param = {
ConnectionToken: connectionToken, /* required */
Content: sendHistory, /* required */
ContentType: 'text/plain', /* required */
};
connectparticipant.sendMessage(param,async function (err, data) {
chatHistory = '';
sendHistory = '';
if (err) {
errorMsg = "Error while sending a message";
}
});
}
};
})();
sendChatHistory();
}
According to the official documentation we have the procedure of StateClient where we can give separate activity holder for individual users. This works when we are creating multiple users with multiple connections.
StateClient sc = activity.GetStateClient();
userData.SetProperty<string>("MyDetails", < some value >);
// How to save the BotUserData
await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
// Getting User data from bot
BotData userData = await sc.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
As this is a parallel operation, the method Async is required to get the data of user simultaneously.

How to solve , Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information

I am implementing google automl in NodeJS to predict the image level. I have created model, level and uploaded images manually. Now I want to predict level of an image using NodeJS.
I wrote a function but always getting the below error,
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information
the code is below-
async function addfile() {
console.log("add file called")
const projectId = "project-name";
const computeRegion = "us-central1";
const modelId = "modelid";
const filePath = "./src/assets/uploads/micro.jpeg";
const scoreThreshold = "0.9";
const client = new automl.PredictionServiceClient();
const modelFullId = client.modelPath(projectId, computeRegion, modelId);
try {
const content = fs.readFileSync(filePath, 'base64');
const params = {};
if (scoreThreshold) {
params.score_threshold = scoreThreshold;
}
const payload = {};
payload.image = { imageBytes: content };
console.log("try block is running")
var [response] = await client.predict({
name: modelFullId,
payload: payload,
params: params,
keyFilename: "./src/assets/uploads/service_account_key.json"
});
console.log('Prediction results: ' + JSON.stringify(response));
response.payload.forEach(result => {
console.log('Predicted class name: ${result.displayName}');
console.log('Predicted class score: ${result.classification.score}');
});
} catch (exception) {
console.log("exception occur = " + exception);
}
}
Any solution for that will be appreciated.
As mentioned by #Rakesh Saini , this error occurs when environment variables are not set or missing.The environment can be set by adding application credentials in the project and adding other required environment variables like Project ID and location.

Unable to update an item in CosmosDB using the replace method with JavaScript

I am trying to create a basic REST API using Azure functions and the cosmosDB client for JavaScript. I have been successful with all the actions except the UPDATE. The cosmosDB client uses conainter.item(id,category).replace(newObject) I am unable to get the container.item().replace method to work. When I test the function in the portal or using Postman, I get a 500 error and in the portal, I get the error: Result: Failure Exception: Error: invalid input: input is not string Stack: Error: invalid input: input is not string at trimSlashFromLeftAndRight.
Example of my basic document/item properties
{
id:002,
project:"Skip rope",
category:"task",
completed: false
}
const config = require("../sharedCode/config");
const { CosmosClient } = require("#azure/cosmos");
module.exports = async function (context, req) {
const endpoint = config.endpoint;
const key = config.key;
const client = new CosmosClient({ endpoint, key });
const database = client.database(config.databaseId);
const container = database.container(config.containerId);
const theId = req.params.id;
// I am retrieving the document/item that I want to update
const { resource: docToUpdate } = await container.item(theId).read();
// I am pulling the id and category properties from the retrieved document/item
// they are used as part of the replace method
const { id, category } = docToUpdate;
// I am updating the project property of the docToUpdate document/item
docToUpdate.project = "Go fly a kite";
// I am replacing the item referred to with the ID with the updated docToUpdate object
const { resource: updatedItem } = await container
.item(id, category)
.replace(docToUpdate);
const responseMessage = {
status: 200,
message: res.message,
data: updatedItem,
};
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage,
};
};
I Googled the heck out of this and been through the Microsoft Azure CosmosDB documents from top-to-bottom, but I can't figure out how to get this to work. I can get the other CRUD operations to work based on the examples Microsoft docs provide, but not this. Any help would be greatly appreciated.
I believe the reason you’re getting this error is because the data type of your “id” field is numeric. The data type of “id” field should be string.
UPDATE
So I tried your code and was able to run it successfully. There was one issue I noticed in your code though:
const { resource: docToUpdate } = await container.item(theId).read();
In the above line of code, you are not specifying the partition key value. If you don't specify the value, then your docToUpdate would come as undefined. In my code I used task as partition key value (I created a container with /category as the partition key).
This is the code I wrote:
const { CosmosClient } = require("#azure/cosmos");
const endpoint = 'https://account.documents.azure.com:443/';
const key = 'accountkey==';
const databaseId = 'database-name';
const containerId = 'container-name';
// const docToUpdate = {
// 'id':'e067cbae-1700-4016-bc56-eb609fa8189f',
// 'project':"Skip rope",
// 'category':"task",
// 'completed': false
// };
async function readAndUpdateDocument() {
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);
const container = database.container(containerId);
const theId = 'e067cbae-1700-4016-bc56-eb609fa8189f';
const { resource: docToUpdate } = await container.item(theId, 'task').read();
console.log(docToUpdate);
console.log('==============================');
const { id, category } = docToUpdate;
docToUpdate.project = "Go fly a kite";
console.log(docToUpdate);
console.log('==============================');
const { resource: updatedItem } = await container
.item(id, category)
.replace(docToUpdate);
console.log(updatedItem);
console.log('==============================');
}
readAndUpdateDocument();
Can you try by using this code?

Google Dialogflow doesn't utilize my changes

I'm trying to create a simple AI chatbot command for my discord bot and it's working out, however, my Dialogflow doesn't seem to utilize any changes that I made like new intents or different responses. it always just returns the text from before the changes or just doesn't return anything at all.
I might be really stupid.
This is my code:
const Discord = require("discord.js")
const axios = require('axios');
const uuid = require('uuid');
const dialogflow = require('#google-cloud/dialogflow');
require("dotenv").config();
const projectId = "mydialogprojectid";
console.log(process.env.GOOGLE_APPLICATION_CREDENTIALS)
const config = require(`../config.json`)
exports.run = async(client, message, args) => {
message.channel.startTyping();
// A unique identifier for the given session
const sessionId = uuid.v4();
console.log(sessionId)
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: args.join(' '),
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
console.log(result)
message.channel.stopTyping();
return message.channel.send(result.fulfillmentText ? result.fulfillmentText : "Something went wrong, forgive me please! I'm still in beta.")
}
I have the same issue it works on the Dialogflow console etc but when using it in discord it wouldnt find the intent etc like you described.
At first i thought this was just some cache issue. I will update this if i find a solution.

Bot Framework v4 Node.js Location

I'm in the process of designing a chat bot and trying to find some Node.js sample code and/or documentation on how to implement the Azure Maps service as part of Bot Framework V4. There are many examples of how this is accomplished in V3, but there seems to be no examples of a V4 solution for Node.js. I'm looking to create a step in my botbuilder-dialog flow that would launch a simple "where do we ship it too" location dialog that would guide the user through the dialog and store the address results as part of that users profile. Any help or advice on this would be appreciated.
Yes, this is doable. I created a class (probably overkill, but oh well) in which I make my API call, with my supplied parameters, to get the map. I decided to use Azure Maps (vs Bing Maps) only because I was curious in how it differed. There isn't any reason you couldn't do this with Bing Maps, as well.
In the bot, I am using a component dialog because of how I have the rest of my bot designed. When the dialog ends, it will fall off the stack and return to the parent dialog.
In my scenario, the bot presents the user with a couple choices. "Send me a map" generates a map and sends it in an activity to the client/user. Anything else sends the user onward ending the dialog.
You will need to decide how you are getting the user's location. I developed this with Web Chat in mind, so I am getting the geolocation from the browser and returning it to the bot to be used when getMap() is called.
const { ActivityTypes, InputHints } = require('botbuilder');
const fetch = require('node-fetch');
class MapHelper {
async getMap(context, latitude, longitude) {
var requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow'
};
const result = await fetch(`https://atlas.microsoft.com/map/static/png?subscription-key=${ process.env.AZURE_MAPS_KEY }&api-version=1.0&layer=basic&zoom=13&center=${ longitude },${ latitude }&language=en-US&pins=default|al.67|la12 3|lc000000||'You!'${ longitude } ${ latitude }&format=png`, requestOptions)
.then(response => response.arrayBuffer())
.then(async result => {
const bufferedData = Buffer.from(result, 'binary');
const base64 = bufferedData.toString('base64');
const reply = { type: ActivityTypes.Message };
const attachment = {
contentType: 'image/png',
contentUrl: `data:image/png;base64,${ base64 }`
};
reply.attachments = [attachment];
await context.sendActivity(reply, null, InputHints.IgnoringInput);
})
.catch(error => {
if (error) throw new Error(error);
});
return result;
};
};
module.exports.MapHelper = MapHelper;
const { ChoicePrompt, ChoiceFactory, ComponentDialog, ListStyle, WaterfallDialog } = require('botbuilder-dialogs');
const { MapHelper } = require('./mapHelper');
const CONFIRM_LOCALE_DIALOG = 'confirmLocaleDialog';
const CHOICE_PROMPT = 'confirmPrompt';
class ConfirmLocaleDialog extends ComponentDialog {
constructor() {
super(CONFIRM_LOCALE_DIALOG);
this.addDialog(new ChoicePrompt(CHOICE_PROMPT))
.addDialog(new WaterfallDialog(CONFIRM_LOCALE_DIALOG, [
this.askLocationStep.bind(this),
this.getMapStep.bind(this)
]));
this.initialDialogId = CONFIRM_LOCALE_DIALOG;
}
async askLocationStep(stepContext) {
const choices = ['Send me a map', "I'll have none of this nonsense!"];
return await stepContext.prompt(CHOICE_PROMPT, {
prompt: 'Good sir, may I pinpoint you on a map?',
choices: ChoiceFactory.toChoices(choices),
style: ListStyle.suggestedAction
});
}
async getMapStep(stepContext) {
const { context, context: { activity } } = stepContext;
const text = activity.text.toLowerCase();
if (text === 'send me a map') {
const { latitude, longitude } = activity.channelData;
const mapHelper = new MapHelper();
await mapHelper.getMap(context, latitude, longitude);
const message = 'Thanks for sharing!';
await stepContext.context.sendActivity(message);
return await stepContext.endDialog();
} else {
await stepContext.context.sendActivity('No map for you!');
return await stepContext.endDialog();
}
}
}
module.exports.ConfirmLocaleDialog = ConfirmLocaleDialog;
module.exports.CONFIRM_LOCALE_DIALOG = CONFIRM_LOCALE_DIALOG;
Hope of help!
---- EDIT ----
Per request, location data can be obtained from the browser using the below method. It is, of course, dependent on the user granting access to location data.
navigator.geolocation.getCurrentPosition( async (position) => {
const { latitude, longitude } = position.coords;
// Do something with the data;
console.log(latitude, longitude)
})

Resources