How to use botbuilder-ai - 10 common examples

To help you get started, we’ve selected a few botbuilder-ai examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / BotBuilder-Samples / samples / typescript_nodejs / 13.core-bot / src / dialogs / luisHelper.ts View on Github external
public static async executeLuisQuery(context: TurnContext): Promise {
        const bookingDetails = new BookingDetails();

        try {
            const recognizer = new LuisRecognizer({
                applicationId: process.env.LuisAppId,
                endpoint: `https://${ process.env.LuisAPIHostName }`,
                endpointKey: process.env.LuisAPIKey,
            }, {}, true);

            const recognizerResult = await recognizer.recognize(context);

            const intent = LuisRecognizer.topIntent(recognizerResult);

            bookingDetails.intent = intent;

            if (intent === 'Book_flight') {
                // We need to get the result from the LUIS JSON which at every level returns an array

                bookingDetails.destination = LuisHelper.parseCompositeEntity(recognizerResult, 'To', 'Airport');
                bookingDetails.origin = LuisHelper.parseCompositeEntity(recognizerResult, 'From', 'Airport');

                // This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
                // TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
                bookingDetails.travelDate = LuisHelper.parseDatetimeEntity(recognizerResult);
            }
        } catch (err) {
            console.warn(`LUIS Exception: ${ err } Check your LUIS configuration`);
        }
github benc-uk / smilr / botv4 / app.js View on Github external
require('dotenv').config()

const { BotStateSet, BotFrameworkAdapter, MemoryStorage, ConversationState, UserState } = require('botbuilder');
const { MessageFactory, CardFactory } = require('botbuilder');
const { LuisRecognizer } = require('botbuilder-ai');

const restify = require('restify');

// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
  console.log(`${server.name} listening to ${server.url}`);
});

const luisModel = new LuisRecognizer({
  appId: process.env.LuisAppId,
  subscriptionKey: process.env.LuisSubKey,
  serviceEndpoint: `https://${process.env.LuisRegion}.api.cognitive.microsoft.com`
});

// Create adapter
const adapter = new BotFrameworkAdapter({
  appId: process.env.MicrosoftAppId,
  appPassword: process.env.MicrosoftAppPassword
});

// Add state middleware
const storage = new MemoryStorage();
const convoState = new ConversationState(storage);
const userState = new UserState(storage);
adapter.use(new BotStateSet(convoState, userState));
github microsoft / botbuilder-js / samples / dispatch-es6 / app.js View on Github external
console.log(`${server.name} listening to ${server.url}`);
});

// Create adapter
const adapter = new BotFrameworkAdapter({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Create LuisRecognizers and QnAMaker
// The LUIS applications are public, meaning you can use your own subscription key to test the applications.
// For QnAMaker, users are required to create their own knowledge base.
// The exported LUIS applications and QnAMaker knowledge base can be found adjacent to this sample bot.

// The corresponding LUIS application JSON is `dispatchSample.json`
const dispatcher = new LuisRecognizer({
    appId: '0b18ab4f-5c3d-4724-8b0b-191015b48ea9',
    subscriptionKey: process.env.LUIS_SUBSCRIPTION_KEY,
    serviceEndpoint: 'https://westus.api.cognitive.microsoft.com/',
    verbose: true
});

// The corresponding LUIS application JSON is `homeautomation.json`
const homeAutomation = new LuisRecognizer({
    appId: 'c6d161a5-e3e5-4982-8726-3ecec9b4ed8d',
    subscriptionKey: process.env.LUIS_SUBSCRIPTION_KEY,
    serviceEndpoint: 'https://westus.api.cognitive.microsoft.com/',
    verbose: true
});

// The corresponding LUIS application JSON is `weather.json`
const weather = new LuisRecognizer({
github microsoft / botbuilder-js / samples / qna-maker-bot-es6 / app.js View on Github external
// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});

// Create adapter
const adapter = new BotFrameworkAdapter({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Add QnA Maker middleware
// The exported Knowledge Base can be found under `smartLightFAQ.tsv`.
const qnaMaker = new QnAMaker(
    {
        knowledgeBaseId: '',
        endpointKey: '',
        host: ''
    },
    {
        answerBeforeNext: true
    }
);
adapter.use(qnaMaker);

// Listen for incoming requests 
server.post('/api/messages', (req, res) => {
    // Route received request to adapter for processing
    adapter.processActivity(req, res, async (context) => {
        // If `!context.responded`, that means an answer wasn't found for the user's utterance.
github microsoft / BotBuilder-Samples / samples / javascript_nodejs / 14.nlp-with-dispatch / bots / dispatchBot.js View on Github external
constructor() {
        super();

        const dispatchRecognizer = new LuisRecognizer({
            applicationId: process.env.LuisAppId,
            endpointKey: process.env.LuisAPIKey,
            endpoint: `https://${ process.env.LuisAPIHostName }.api.cognitive.microsoft.com`
        }, {
            includeAllIntents: true,
            includeInstanceData: true
        }, true);

        const qnaMaker = new QnAMaker({
            knowledgeBaseId: process.env.QnAKnowledgebaseId,
            endpointKey: process.env.QnAEndpointKey,
            host: process.env.QnAEndpointHostName
        });

        this.dispatchRecognizer = dispatchRecognizer;
        this.qnaMaker = qnaMaker;

        this.onMessage(async (context, next) => {
            console.log('Processing Message Activity.');

            // First, we use the dispatch model to determine which cognitive service (LUIS or QnA) to use.
            const recognizerResult = await dispatchRecognizer.recognize(context);

            // Top intent tell us which cognitive service to use.
            const intent = LuisRecognizer.topIntent(recognizerResult);
github microsoft / botbuilder-js / samples / translator-es6 / app.js View on Github external
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});

// Create adapter
const adapter = new BotFrameworkAdapter({ 
    appId: process.env.MICROSOFT_APP_ID, 
    appPassword: process.env.MICROSOFT_APP_PASSWORD 
});

// Add conversation state middleware
const conversationState = new ConversationState(new MemoryStorage());
adapter.use(conversationState);

// Add language translator middleware
const languageTranslator = new LanguageTranslator({
    translatorKey: "xxxxxx",
    nativeLanguages: ['fr', 'de'] 
});
adapter.use(languageTranslator);

// Add locale converter middleware
const localeConverter = new LocaleConverter({
    toLocale: 'fr-fr',
    fromLocale: 'en-us'
})
adapter.use(localeConverter);

// Listen for incoming requests 
server.post('/api/messages', (req, res) => {
    // Route received request to adapter for processing
    adapter.processActivity(req, res, (context) => {
github microsoft / botbuilder-js / samples / translator-ts / lib / app.js View on Github external
const restify = require("restify");
// Create server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log(`${server.name} listening to ${server.url}`);
});
// Create adapter
const adapter = new botbuilder_1.BotFrameworkAdapter({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});
// Add conversation state middleware
const conversationState = new botbuilder_1.ConversationState(new botbuilder_1.MemoryStorage());
adapter.use(conversationState);
// Add language translator middleware
const languageTranslator = new botbuilder_ai_1.LanguageTranslator({
    translatorKey: "xxxxxx",
    noTranslatePatterns: new Set(),
    nativeLanguages: ['fr', 'de']
});
adapter.use(languageTranslator);
// Add locale converter middleware
const localeConverter = new botbuilder_ai_1.LocaleConverter({
    toLocale: 'fr-fr',
    fromLocale: 'en-us'
});
adapter.use(localeConverter);
// Listen for incoming requests 
server.post('/api/messages', (req, res) => {
    // Route received request to adapter for processing
    adapter.processActivity(req, res, (context) => __awaiter(this, void 0, void 0, function* () {
        if (context.activity.type === 'message') {
github microsoft / BotBuilder-Samples / samples / javascript_typescript / 13.core-bot / src / dialogs / luisHelper.ts View on Github external
public static async executeLuisQuery(logger: Logger, context: TurnContext): Promise {
        const bookingDetails = new BookingDetails();

        try {
            const recognizer = new LuisRecognizer({
                applicationId: process.env.LuisAppId,
                endpoint: `https://${ process.env.LuisAPIHostName }`,
                endpointKey: process.env.LuisAPIKey,
            }, {}, true);

            const recognizerResult = await recognizer.recognize(context);

            const intent = LuisRecognizer.topIntent(recognizerResult);

            bookingDetails.intent = intent;

            if (intent === 'Book_flight') {
                // We need to get the result from the LUIS JSON which at every level returns an array

                bookingDetails.destination = LuisHelper.parseCompositeEntity(recognizerResult, 'To', 'Airport');
                bookingDetails.origin = LuisHelper.parseCompositeEntity(recognizerResult, 'From', 'Airport');

                // This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
                // TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
                bookingDetails.travelDate = LuisHelper.parseDatetimeEntity(recognizerResult);
            }
        } catch (err) {
            logger.warn(`LUIS Exception: ${ err } Check your LUIS configuration`);
        }
github microsoft / botframework-solutions / solutions / Virtual-Assistant / src / typescript / assistant / src / dialogs / shared / enterpriseDialog.ts View on Github external
protected async onInterruptDialog(dc: DialogContext): Promise {
        const luisServiceName: string = 'general';
        // get current activity locale
        const locale: string = dc.context.activity.locale || 'en';
        const localeConfig: LocaleConfiguration | undefined = this.services.localeConfigurations.get(locale);
        // check luis intent
        const luisService: ITelemetryLuisRecognizer | undefined = localeConfig !== undefined ?
                                                                  localeConfig.luisServices.get(luisServiceName) : undefined;
        const luisResult: RecognizerResult | undefined = luisService !== undefined ?
                                                         await luisService.recognize(dc.context, true) : undefined;
        const intent: string = LuisRecognizer.topIntent(luisResult);
        // PENDING: Evolve this pattern
        if (luisResult && luisResult.intents[intent].score > 0.5) {
            // Add the luis result (intent and entities) for further processing in the derived dialog
            dc.context.turnState.set(this.luisResultKey, luisResult);
            switch (intent) {
                case 'Cancel': {
                    return this.onCancel(dc);
                }
                case 'Help': {
                    return this.onHelp(dc);
                }
                default:
            }
        }

        return InterruptionAction.NoAction;
github microsoft / BotBuilder-Samples / samples / javascript_nodejs / 51.cafe-bot / dialogs / shared / prompts / getUserNamePrompt.js View on Github external
// See if we have card input. This would come in through onTurnProperty
        const onTurnProperty = await this.onTurnAccessor.get(context);
        if (onTurnProperty !== undefined) {
            if (onTurnProperty.entities.length !== 0) {
                // find user name in on turn property
                const userNameInOnTurnProperty = onTurnProperty.entities.find(item => item.entityName === USER_NAME);
                if (userNameInOnTurnProperty !== undefined) {
                    await this.updateUserProfileProperty(userNameInOnTurnProperty.entityValue, context);
                    return await super.continueDialog(dc);
                }
            }
        }

        // call LUIS and get results
        const LUISResults = await this.luisRecognizer.recognize(context);
        let topIntent = LuisRecognizer.topIntent(LUISResults);
        if (Object.keys(LUISResults.intents).length === 0) {
            // go with intent in onTurnProperty
            topIntent = (onTurnProperty.intent || 'None');
        }
        // Did user ask for help or said they are not going to give us the name?
        switch (topIntent) {
        case NO_NAME_INTENT: {
            // set user name in profile to Human
            await this.userProfileAccessor.set(context, new UserProfile('Human'));
            return await this.endGetUserNamePrompt(dc);
        }
        case GET_USER_NAME_INTENT: {
            // Find the user's name from LUIS entities list.
            if (USER_NAME in LUISResults.entities) {
                await this.updateUserProfileProperty(LUISResults.entities[USER_NAME][0], context);
                return await super.continueDialog(dc);