Sie sind auf Seite 1von 45

Windows 10 and Azure IoT

Workshop

Building a Bot with Bot


Framework & LUIS

Abstract:
This Bot Builder SDK with LUIS Lab is prepared to show how to build a Bot with Bot Builder SDK
and add LUIS (Language Understanding Intelligent Service). Deploy the Bot in Bot Framework
developer portal and enable users to access the Bot via different channels (Skype, Facebook
Messenger, Slack, etc.).

Install and configure:

You will need setup your dev machine as followed to complete the lab:

Windows 10
Visual Studio 2015 (Latest update)
Azure account with an active subscription

Copyright (c) 2016 Microsoft. All rights reserved.

This document is provided "as-is." Information and views expressed in this document, including URL and other
Internet Web site references, may change without notice.
Contents
Lab Objectives........................................................................................................ 3
Section 1: Create a Bot with Bot Builder SDK ......................................................... 3
[Optional] Exercise 0: Setting up development environment.............................. 3
Exercise 1: Creating a C# Bot Application ............................................................ 4
Exercise 2: Adding Dialog .................................................................................... 6
Exercise 3: Adding FormFlow .............................................................................. 9
Exercise 4: Adding Bot State ............................................................................. 12
Section 2: Create a LUIS Application .................................................................... 16
Exercise 1: Creating your first LUIS application ................................................. 16
Exercise 2: Adding Intents ................................................................................. 18
Exercise 3: Adding Entities ................................................................................ 19
Using Bing Entities ................................................................................................................. 19
Exercise 4: Labeling utterances ......................................................................... 20
Exercise 5: Training and Publishing a model ..................................................... 23
Section 3: Smart Bots with LUIS ........................................................................... 25
Exercise 1: Bot Project with LuisDialog ............................................................. 25
Exercise 2: Handle Intents ................................................................................. 28
Exercise 3: Test bot with natural language input .............................................. 28
Exercise 4: Process Entities ............................................................................... 30
Section 4: Publish your Smart Bot ........................................................................ 31
Exercise 1: Publish project to Azure .................................................................. 32
Exercise 2: Register your Bot with Microsoft Bot Framework ........................... 36
Exercise 3: Update Bot MicrosoftAppId and MicrosoftAppPassword ................ 38
Exercise 4: Testing the connection to your bot ................................................. 39
Exercise 5: Configuring Channels ...................................................................... 40
[Optional] Exercise 6: Trying the Skype Channel ............................................... 42
Lab Objectives
This lab aims to demonstrate how to build a Bot with Microsoft Bot Framework. The framework
consists of the Bot Builder SDK, Bot Connector, Developer Portal, and Bot Directory. Theres
also an emulator that you can use to test your bot. First section will demonstrate how to build a
simple conversational bot using the Bot Builder SDK. The second and third sections will
demonstrate how to create a LUIS (language understanding intelligent services) application and
integrate with a Bot. Lastly, this lab will demonstrate how to host a Bot in the Developer Portal
and access the Bot using different channels.

Section 1: Create a Bot with Bot Builder SDK


Microsoft Bot Builder is a powerful framework for constructing bots that can handle both
freeform interactions and more guided ones where the possibilities are explicitly shown to the
user. It is easy to use and leverages C# to provide a natural way to write bots.
High Level Features:
- Powerful dialog system with dialogs that are isolated and composable.
- Built-in dialogs for simple things like Yes/No, strings, numbers, enumerations.
- Built-in dialogs that utilize powerful AI frameworks like LUIS.
- Bots are stateless which helps them scale.
- FormFlow for automatically generating a bot from a C# class for filling in the class and
that supports help, navigation, clarification and confirmation.
- SDK source code is found on http://github.com/Microsoft/botbuilder.
This section will demonstrate how to write a Bot in C# using the Bot Builder SDK.

[Optional] Exercise 0: Setting up development environment


For this lab, the development machines have installed all the required software. If you are using
your own development machine, refer to guide below:
1. Install prerequisite software
a. Visual Studio 2015 (latest update) - you can download the community version
here for free: www.visualstudio.com
b. Important: Please update all VS extensions to their latest versions Tools-
>Extensions and Updates->Updates
2. Download and install the Bot Application template here
3. Save the zip file to your Visual Studio 2015 templates directory which is traditionally in
"%USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual
C#\". Do not need to unzip.
4. Download the Bot Framework Emulator here. Install the exe.
Exercise 1: Creating a C# Bot Application
1. Open Visual Studio 2015. At the top left click on File > New > Project

2. In the New Project window, find the Bot Application under Installed > Templates >
Visual C#. Change the name to HotelSearchBot. Click OK.

3. The HotelSearchBot is created from the Bot Application template. This project is based
on .NET web application with Bot Builder SDK. The next step is to build and test the bot
app. Click the run button (Microsoft Edge) to build and start debugging the app.

4. Since the Bot Application is a web application, when the app is running we can debug
through the default browser. You will see a screen like the one below.
5. Open Bot Framework Channel Emulator tool. Make sure URL corresponds to the
endpoint in Edge. Leave the App ID and Password empty for now and click CONNECT.

6. The template is a fully functional Echo Bot that takes the user's text utterance as input
and returns it as output. Try typing in the emulator tool to test the bot. You will see a
screen like the one below.
Exercise 2: Adding Dialog
Dialogs model a conversational process, where the exchange of messages between bot and
user is the primary channel for interaction with the outside world. Each dialog is an abstraction
that encapsulates its own state in a C# class that implements IDialog.
In this example, we will implement a bot that will help users to find hotel. However, there are
many options HotelSearchBot needs to know from the user before it starts searching, such as
Check-in Date, Destination, Room, etc.
Here we use combination of two powerful conversation building blocks known as Dialog and
FormFlow, which give us flexible methods to create a dialog and get a collection of fields that
user provide.
1. Create a new C# class. Right-click on HotelSearchBot project > Add > Class
Enter HotelDialog.cs as the name of the class. Click Add to add the class.
2. We first need to import the required the namespace, add this at the top of
HotelDialog.cs:
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using System.Threading.Tasks ;

Next we need to change the C# class to represent the dialog class.


Change the public class HotelDialog {} class to the code below:
[Serializable]
public class HotelDialog : IDialog<object>
{
public async Task StartAsync(IDialogContext context)
{
//Wait for incoming message
context.Wait(MessageReceivedAsync);
}

public async Task MessageReceivedAsync(IDialogContext context,


IAwaitable<IMessageActivity> argument)
{
var message = await argument;
await context.PostAsync("Hotel Dialog: You said: " + message.Text);
context.Wait(MessageReceivedAsync);
}
}
IDialogContext dialog context maintains a stack of dialogs active in the conversation.
StartAsync implements the interface function of IDialog::StartAsync. In this dialog, we
will create a custom conversation callback function called MessageReceivedAsync to
process the messages.
3. Now that HotelDialog.cs is implementing the IDialog, we need to wire the class into
the Post method. In Controllers > MessageController.cs change the following code in
Post method.
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new HotelDialog ());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

Also add using Microsoft.Bot.Builder.Dialogs; to the top of MessageController.cs


Now when the Bot receives a user input message, the message will start HotelDialog.

[Note] Understanding the code:


When the conversation first states, there is no dialog state (the dialog stack and each
dialogs state), so the delegate passes to Conversation.SendAsync will be used to
construct a HotelDialog and its StartAsync method will be called. In this case, the
StartAsync calls the IDialogContext.Wait with the continuation delegate
(MessageReceivedAsync method) to call when there is a new message. Within
MessageReceivedAsync we wait for the message to come in and then post our response
and wait for the next message. In this case, the next message would again be processed
by the MessageReceivedAsync. Every time we call the IDialogContext.Wait our bot is
suspended and can be restarted on any machine that receives the message. The dialog
structure allows you to compose together multiple dialogs into complex conversation
without having to explicitly manage state.

4. Build and run the project. In the Bot Emulator, check the message is processed in the
HotelDialog class.
Exercise 3: Adding FormFlow
FormFlow dialog guides the user through filling in the form while providing guidance along the
way. First, we need to define a FormFlow class, HotelsQueryForm.cs.
1. Create a new C# class. Right-click on HotelSearchBot project > Add > Class
Enter HotelsQueryForm.cs as the name of the class. Click Add to add the class.
2. HotelsQueryForm.cs will define the information that we need from the User to search
for Hotel. In HotelsQueryForm.cs, copy the code below.
using System;
using Microsoft.Bot.Builder.FormFlow;

namespace HotelSearchBot
{
public enum RoomOptions
{
Single, Double, Junior, Queen
};

// The HotelsQueryForm is the simple form you want to fill out.


//It must be serializable so the bot can be stateless.
[Serializable]
public class HotelsQueryForm
{
[Prompt("Please enter your {&}")]
public string Destination { get; set; }

[Prompt("What kind of {&} would you like? {||}")]


public RoomOptions? Room;

[Prompt("When do you want to {&}?")]


public DateTime CheckIn { get; set; }

[Numeric(1, int.MaxValue)]
[Prompt("How many {&} do you want to stay?")]
public int Nights { get; set; }
}
}
3. Next, the HotelDialog needs to build the FormFlow when the user sends a message to
the bot. In HotelDialog.cs, we need to use a FormDialog.FromForm() function to build
the HotelsQueryForm FormDialog.
In HotelDialog.cs, update the MessageReceivedAsync function.
//Received message from user
public async Task MessageReceivedAsync(IDialogContext context,
IAwaitable<IMessageActivity> argument)
{
var message = await argument;
//Creates a FormDialog using FormDialog.FromForm(BuildFormDelegate<T>, ..)
//Calls the BuildHotelForm fuction
var hotelsFormDialog = FormDialog.FromForm(this.BuildHotelsForm,
FormOptions.PromptInStart);
//context.call will call the child dialog, in this case the hotelsFormDialog
//when the dialog complete, will continue to the ResumeAfterHotelsFormDialog
context.Call(hotelsFormDialog, this.ResumeAfterHotelsFormDialog);
}
Also, add the using statement to the top of the HotelDialog.cs:
using Microsoft.Bot.Builder.FormFlow;

4. When the HotelDialog receives a message, MessageReceivedAsync will add the


HotelsQueryForm FormDialog to the dialog stack.
Below the MessageReceivedAsync function, add the following code:
//Builds a FormBuilder from HotelsQueryForm
private IForm<HotelsQueryForm> BuildHotelsForm()
{
OnCompletionAsyncDelegate<HotelsQueryForm> processHotelsSearch = async
(context, state) =>
{
await context.PostAsync($"Ok. Searching for Hotels in {state.Destination}
from {state.CheckIn.ToString("MM/dd")} to
{state.CheckIn.AddDays(state.Nights).ToString("MM/dd")}");
};
return new FormBuilder<HotelsQueryForm>()
.Field(nameof(HotelsQueryForm.Destination))
.Message("Looking for hotels in {Destination}...")
.AddRemainingFields()
.OnCompletion(processHotelsSearch)
.Build();
}

//When the HotelsQueryForm FormDialog finishes, ResumeAfterHotelsFormDialog will


be called
private async Task ResumeAfterHotelsFormDialog(IDialogContext context,
IAwaitable<HotelsQueryForm> result)
{
try
{
HotelsQueryForm searchQuery = await result;
//Do something (like calling hotel booking 3rd party API)
}
finally
{
//Complete current dialog
context.Done<object>(null);
}
}

- BuildHotelsForm() :
o Returns a FormFlow:IForm object from FormBuilder.Build() by specifying
the form class HotelsQueryForm
- ResumeAfterHotelsFormDialog() :
o This is called when the FormDialog<HotelsQueryForm> completes all its
dialogs.
o After receiving the users complete input, the bot can add feature such as
calling hotel booking 3rd party API.
5. HotelDialog.cs Dialog is fully integrated with the HotelsQueryForm form. Test this in
the Bot Emulator by building and run the app. You will see the result like the one below.
a. First, greet the Bot with any text, Hello or Hi or anything. Upon receiving the
first message, the Bot will start the HotelDialog dialog.
b. Enter any destination; such as, Taipei or Taichung, any city you can think of.
c. Click on the one of the buttons Single, Double, Junior, or Queen.
d. Enter a date in English spoken language, Jan 31st or Feb 2nd.
e. Finally, enter any digit number to represent number of nights.
Exercise 4: Adding Bot State
Now that we have an example of the Bot Builder framework we are going to build on it to add
some dialog state and some commands to control that state.
1. First thing we need to do is add a state variable in the dialog class, HotelDialog.
Add the hotelHistory variable in HotelDialog.cs
public class HotelDialog : IDialog<object> {

protected string hotelHistory = "";



}
2. When user has completed the Hotel dialog inputs, the bot needs to save the input result
in the state variable, hotelHistory. Change the ResumeAfterHotelsFormDialog function to
the code below:
//When the HotelQsueryForm FormDialog finishes, ResumeAfterHotelsFormDialog will
be called
private async Task ResumeAfterHotelsFormDialog(IDialogContext context,
IAwaitable<HotelsQueryForm> result)
{
try
{
HotelsQueryForm searchQuery = await result;
//Save the HotelsQueryForm result into state variable hotelHistory
hotelHistory = ($"Destination: {searchQuery.Destination}\n\r");
hotelHistory += ($"Room Type: {searchQuery.Room.ToString()}\n\r");
hotelHistory += ($"From: {searchQuery.CheckIn.ToString("MM/dd")} \n\r");
hotelHistory += ($"To:
{searchQuery.CheckIn.AddDays(searchQuery.Nights).ToString("MM/dd")}");
}
finally
{
context.Done<object>(null);
}
}
3. We are going to allow the commands history and reset. Which will show the last
searched HotelsQueryForm history and also reset the history. In MessageReceivedAsync
we have added check to see if the input was "reset" and if that is true we use the built-
in PromptDialog.Confirm dialog to spawn a sub-dialog that asks the user if they are sure
about resetting the hotel search history. The sub-dialog has its own private state and
does not need to worry about interfering with the parent dialog. When the sub dialog is
done, it's result is then passed onto the AfterResetAsync method.
Change the MessageReceivedAsync () to the code below:
public async Task MessageReceivedAsync(IDialogContext context,
IAwaitable<IMessageActivity> argument)
{
var message = await argument;

//if "history", return the hotelHistory state variable


if (message.Text.ToLower() == "history")
{
await context.PostAsync(hotelHistory);
context.Wait(MessageReceivedAsync);
}
//if "reset", AfterResetAsync
else if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the 'Hotel Search History?'",
"Didn't get that!(please press y/n)",
promptStyle: PromptStyle.None);
}
else
{
//Creates a FormDialog from FormBuilder<HotelsQueryForm>; add it to dialog
stack
var hotelsFormDialog = FormDialog.FromForm(this.BuildHotelsForm,
FormOptions.PromptInStart);
context.Call(hotelsFormDialog, this.ResumeAfterHotelsFormDialog);
}
}
The code added some if statement to check if the users input are the commands
history or reset.
4. The AfterResetAsync function does not exists yet, add the function in the HotelDialog
class. (Below ResumeAfterHotelsFormDialog)
public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool>
argument)
{
var confirm = await argument;
if (confirm)
{
this.hotelHistory = "No record";
await context.PostAsync("Reset History.");
}
else
{
await context.PostAsync("Did not reset History.");
}
context.Wait(MessageReceivedAsync);
}

In AfterResetAsync we check on the response and perform the action including sending a
message back to the user.

5. Run the bot to test the dialog state functions.


In the Bot Emulator, start another HotelsQueryForm input. After the input, ask the bot
for history search result.
6. Run the bot and try resetting the history result. Ask the bot to reset the history.

No record response confirms that the dialog state variable has been cleared.
In this section, we have created a Bot using the FormFlow dialog from the Bot Builder SDK.
Section 2 & 3, we will be creating another Bot which will integrate with LUIS for natural
language understanding.
Section 2: Create a LUIS Application
Language Understanding Intelligent Services (LUIS) lets you build your applications by using the
LUIS web interface. A Bot with LUIS enabled will allow the bot to understand and respond to
various hypothetical commands.
LUIS is capable of interpreting a sentence and parsing out its intent and entities. An intent is
something a user want; like an action that they want to perform. An entity is the subject of the
intent. For example, if someone asks "What's the weather in Vancouver? the intent could be
check weather and the entity is Vancouver. In the application, you will bundle together the
intents and entities that are important to your task.

Exercise 1: Creating your first LUIS application


In Microsoft Edge or a browser of your choice, go to www.luis.ai and Sign Up. Follow a quick
tutorial. You will see a screen like the one below.

Click on +New App then new Application. You will see a screen like the one below.
Fill in the appropriate fields. Enter application name, WeatherBot and select the other fields
as the screen above and as preferred.
Finally click on Add App to create LUIS application. You will see the LUIS Application Editor,
like the one below.
Exercise 2: Adding Intents
Next, we will add two intents to the application. At the top left of the menu panel, you will see
an area for intents. All applications come with one pre-defined intent, None. This will recognize
user statements that have nothing to do with the application, for example if someone says,
"Get me a great cookie recipe".
Go ahead and click + next to Intents on the horizontal bar. You will see a dialog box appear to
add a new intent. Enter the intent name of "GetWeather", and the example command that
triggers the intent as "Whats the weather in Taipei". This will look like the screenshot below.

Click Save, and the utterance will be presented for labeling.


The intent GetWeather will in selected from the drop-down of intents. Click Submit.
Next, add a second intent called "GetSunsetTime", with the example command that triggers the
intent as "Whens the sunset in Taipei". Click Save, then continue by accepting the presented
utterance as a " GetSunsetTime " intent and click Submit.
In the Intents area, you should now see the two new intents.
Exercise 3: Adding Entities
On the left-hand panel, you will see an option to add entities. We'd like to be able to say which
citys weather we are interested in. In order to capture the topic of "location", let's create the
entity type: "Location". To do this, click the "+" button on the Entities bar, and fill in the
resulting text entry box by typing "Location".

You have now created a simple generic entity called "Location.

Using Bing Entities


In your app, you might want to say something like Show me tomorrows weather in Taipei.
This will require understanding date words like today, tonight, tomorrow, or next week
and so on. We can use pre-built entity model called datetime. Click the + sign on the Prebuilt
Entities horizontal bar and select datetime from the drop-down menu.
For a full list of pre-built Bing entities and their use, see Pre-built Entities.
Exercise 4: Labeling utterances
With a set of intents and entities defines, the next step is to provide more examples of
utterances that illustrates these concepts. Click on New Utterance tab at the top of the screen.
Type Get tomorrows weather in Taipei into the entry box and hit Enter. You will see a drop-
down box showing the possible intents. Select GetWeather. Click on taipei and select
Location and you will see the word taipei highlighted in yellow, indicating that you have
labeled the word taipei as a Location. You will notice the word tomorrow is highlighted in
gray. This corresponds to the datetime Pre-built Entities we added; datetime entities will be
selected automatically based on Bing Entities.
Click Submit to submit this label.
The system needs several examples for each intent, and several examples for each entity. Don't
forget to add an example or two of a None intent, for example, enter "I like ice cream". Note,
that LUIS converts all utterances to lower case.
Add the following utterances and correctly label the entities:
- [GetWeather] Will it snow next week in Boston?
- [GetWeather] Will it rain tomorrow in Tokyo?
- [GetWeather] Whats the weather for tomorrow?
- [GetWeather] Show me the weather for next week
- [GetWeather] Show me the next weeks weather in Taipei
- [GetWeather] Whats the weather in Taipei?
- [GetWeather] Whats the weather like in the afternoon?
- [GetSunsetTime] Whens the sunset in Taipei?
- [GetSunsetTime] Whens the sunset next week?
- [None] I like ice scream
- [None] How are you
You can review your labels by clicking on Review labels tab at the top of the screen, select
Show all labeled utterances from the drop-down box. You should now see all the utterances;
make sure you have several examples for each intent and entity. Check the intent is correct,
and the entities are highlighted in yellow.
Exercise 5: Training and Publishing a model
When you "train" a model, LUIS generalizes from the examples you have labeled, and develops
code to recognize the relevant intents and entities in the future. Internally, LUIS uses logistic
regression classifiers to determine intents, and conditional random fields (CRFs) to determine
the entities. The training process results in optimized classifiers and CRFs, referred to as
models, that LUIS can use in the future. To do training, just click the Train button at the left
bottom corner of the page. Training also occurs automatically with regular intervals.

The next step is to deploy the model to an HTTP endpoint that will interpret the sentences we
send it. Click the Publish button in the upper left-hand corner, and then Publish web service in
the resulting window. After a couple of moments, you will see the URL that makes your model
available as a web service. You will see a screen like the one below.

The next step is to test your Bot Application and understand the JSON response.
1. In the Timezone drop-down box select (GMT +8:00) Beijing, Perth, Singapore, Hong
Kong.
2. In the Query textbox, enter Show me tomorrows weather in Shanghai, then click
Update published application.
3. Click on the generated URL. (https://api.projectoxford.ai/luis/v2.0/apps/.... )
4. You should see the output:
{
"query": "Show me tomorrow's weather in Shanghai",
"topScoringIntent": {
"intent": "GetWeather",
"score": 0.941986561
},
"intents": [
{
"intent": " Show me tomorrow's weather in Shanghai ",
"score": 0.941986561
},
{
"intent": "None",
"score": 0.04360123
},
{
"intent": "GetSunsetTime",
"score": 4.42665238E-09
}
],
"entities": [
{
"entity": "shanghai",
"type": "Location",
"startIndex": 30,
"endIndex": 37,
"score": 0.711348057
},
{
"entity": "tomorrow",
"type": "builtin.datetime.date",
"startIndex": 8,
"endIndex": 15,
"resolution": {
"date": "2016-12-20"
}
}
]
}
5. From the output we can retrieve the following detail:

Field Json type Description of content in example

Query string Query/utterance: " Show me tomorrow's weather in Shanghai"


Field Json type Description of content in example

All intents listed (each with their highest score): "GetWeather",


Intents object
"None", "GetSunsetTime"

Confidence score, between 0 and 1. Only the highest score is listed


Score number
for each intent.

"shanghai", Type: Location.


Entities object
"tomorrow", Type: builtin.datetime.date.

Confidence score, between 0 and 1. Only the highest score is listed


Score number
for each entity.

"date" string "2016-12-20" [Note: the URL request was sent on 2016-12-19]

Section 3: Smart Bots with LUIS


The LUIS API enables you to build smart bots that are able to understand the process natural
language. This is a particularly important skill for bots as, in most cases, the interaction users
have with bots is free-form. Thus, bots must be able to understand language the way people
speak it - naturally and contextually.
In this section, you will add the new code to handle the integration with the LUIS language
model from last section.

Exercise 1: Bot Project with LuisDialog


1. In your Visual Studio solution, right click on the solution > Add > New Project. Select Bot
Application and name the application WeatherLUISBot.
2. Build and Run your application. Test it in Bot Framework Channel Emulator.

3. Create a new C# class. Right-click on WeatherLUISBot project > Add > Class...
Enter WeatherDialog.cs as the name of the class. Click Add to add the class.
4. In WeatherDialog.cs, replace the code with:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Bot.Builder.Luis.Models;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Dialogs;
using System.Threading.Tasks;

namespace WeatherLUISBot
{

[LuisModel("<YOUR_LUIS_APP_ID>", "<YOUR_LUIS_SUBSCRIPTION_KEY>")]
[Serializable]
public class WeatherDialog : LuisDialog<object>
{
//Const string to retrieve Entity based on entity type
public const string Entity_location = "Location";
public const string Entity_builtInDate = "builtin.datetime.date";
public const string Entity_builtInTime = "builtin.datetime.time";

//None intent handler


[LuisIntent("")]
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
string message = $"Sorry I did not understand: "
+ string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
context.Wait(MessageReceived);
}
}
}

5. Go back to the browser and navigate to Luis.ai. On the top left of the menu panel, click
on Publish and you will see a screen like the one below.

The URL will be in this format:


https://api.projectoxford.ai/luis/v2.0/apps/<YOUR_LUIS_APP_ID>?subscription-
key=<YOUR_LUIS_SUBSCRIPTION_KEY>&verbose=true
This URL points to the Model that LUIS published for your LUIS app.

In Visual Studio > WeatherDialog.cs > find the following line:


[LuisModel("<YOUR_LUIS_APP_ID>", "<YOUR_LUIS_SUBSCRIPTION_KEY>")]
Replace <YOUR_LUIS_APP_ID> and <YOUR_LUIS_SUBSCRIPTION_KEY> with the LUIS model
URL.
These 2 attribute values will bind the LuisDialog class to your LUIS model.
Exercise 2: Handle Intents
1. Now that the basic LUIS dialog is defined, you need to add code to handle the LUIS
intents. The LuisDialog class is specialized to handle intents and entities from LUIS. Each
intent will map to each corresponding method in the LuisDialog class.
In WeatherDialog.cs, add the following code for GetWeather and GetSunsetTime
intent.
//GetWeather intent handler
[LuisIntent("GetWeather")]
public async Task GetWeather(IDialogContext context, LuisResult result)
{
await context.PostAsync($"You asked for the weather!");
context.Wait(MessageReceived);
}

//GetSunsetTime intent handler


[LuisIntent("GetSunsetTime")]
public async Task GetSunsetTime(IDialogContext context, LuisResult result)
{
await context.PostAsync($"You asked for the sunset time!");
context.Wait(MessageReceived);
}

2. Next step is to route user input to the Luis Dialog. To do this you need to change the
code in the Post method in MessagesController to create an instance of our LUIS dialog
and send incoming messages to it. The code below creates an instance of the LuisDialog
(WeatherDialog) and Conversation.SendAsync method will process the incoming message
and pass it along to the LuisDialog.
In Controllers > MessageController.cs change the following code in Post method.
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new WeatherDialog());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

Also add using Microsoft.Bot.Builder.Dialogs; to the top of MessageController.cs


Now when the Bot receives a user input message, the message will start WeatherDialog.

Exercise 3: Test bot with natural language input


Everything should be in place to test the bot with LUIS integration.
1. In Visual Studio > right-click on WeatherLUISBot project > select Set as Startup Project
2. Run and start debugging the bot.

In Edge, you will see a screen like the one below.

3. Open Bot Framework Channel Emulator tool and try several phrases to check the LUIS
model is consistent.
- None: Hello
- GetWeather: Whats the weather like in Taipei
- GetSunsetTime: Please give me the sunset for tonight

The response from the Bot should be correctly recognized from the LUIS modal and
returned back to the user. You can rephrase each case in natural language input.
Exercise 4: Process Entities
Now that the bot understands what the users intended action is, the bot can also retrieve
entities to handle each intent.
In this example, the GetWeather intent might include the Location entity and Datetime
entity. In WeatherDialog.cs change the following code in GetWeather method.
public async Task GetWeather(IDialogContext context, LuisResult result)
{
//initialize Entity objects
EntityRecommendation locationEntity;
EntityRecommendation dateEntity;
EntityRecommendation timeEntity;

//construct return message to User


string message = "You asked for ";

//try to find entity based on entity type:


//Entity_location = Location
//Entity_builtInDate = "builtin.datetime.date"
//Entity_builtInTime = "builtin.datetime.time"
bool ifLocation = result.TryFindEntity(Entity_location, out locationEntity);
bool ifDate = result.TryFindEntity(Entity_builtInDate, out dateEntity);
bool ifTime = result.TryFindEntity(Entity_builtInTime, out timeEntity);

if (ifDate || ifTime)
{
//if date or time entity exists
if (ifDate) message += " " + dateEntity.Entity;
if (ifTime) message += " " + timeEntity.Entity;
message += "'s weather";
} else
{
message += "the weather";
}

if (ifLocation)
{
//if Location entity exists
message += " in " + locationEntity.Entity;
}

//return response message back to User


await context.PostAsync(message);
context.Wait(MessageReceived);
}

Open Bot Framework Channel Emulator tool and try the following phrases:
- Will it snow tomorrow in Vancouver?
- Is it going to rain next week?
- Weather for dec 31st in Taipei
You should see the responses like the ones below.

Intent handlers will include any entities that LUIS recognized and passed along in the args
parameter, LuisResult result. Bot Builder includes a LuisResult class, which has useful
functions and includes the following objects,

- string query
- IList<IntentRecommendation> intents
- IList<EntityRecommendation> entities

In this example, we built a weather bot that is able to understand and respond to various
hypothetical commands. The bot is using LUIS to identify the intent of the user, and reply with
the appropriate prompt. To complete this app, you may wish to hook live weather data in the
C# Bot application; when the user asks for the weather, the Bot can retrieve live weather data
from 3rd party APIs.

Section 4: Publish your Smart Bot


In this tutorial, we use Microsoft Azure to host the Bot application. To publish your Bot
Application you will need a Microsoft Azure subscription.
Exercise 1: Publish project to Azure
1. In edge, go to https://portal.azure.com/. Log in with your Microsoft account.
2. Create a Web App to host the Bot Application. On the left panel of the page, click on
button and search for Web App. Select the following Web App.

3. Click on Create button on the bottom.


4. Fill in the App name and rest of the fields, click Create at the bottom.

5. On the top right of the page, click on the button to open the Notifications panel.
Confirm the Deployment is successful. Click on the Deployments succeeded to open
the web app blade.

6. In the Web App blade, download the publish profile. Publish profiles allow you to
import the deployment credentials into Visual Studio; allowing Visual Studio to deploy
project to this Azure Web App.
Save the file somewhere on the development machine.
7. Back in Visual Studio, right click on the WeatherLUISBot project, and click Publish.
Click on Import. In the Import Publish Settings, click on Browser and go to the publish
profile file. Finally, click OK.

8. By importing the Publish Profile file, Visual Studio can retrieve all the deployment
credentials and settings. Click on Next.
9. Finally, click on Publish.
10. You will see a number of messages displayed in the Visual Studio 2015 "Output"
window.

Once publishing is complete, you will also see the web page for your Bot Application
displayed in your browser, see below.

Exercise 2: Register your Bot with Microsoft Bot Framework


Registering your Bot tells the Connector how to call your Bot's web service. Note that the
MicrosoftAppId and MicrosoftAppPassword are generated when your Bot is registered with
the Microsoft Bot Framework Connector, the MicrosoftAppId and MicrosoftAppPassword are
used to authenticate the conversation, and allows the developer to configure their Bot with the
Channels they'd like to be visible on. The BotId, which you specify, is used for the URL in the
directory and developer portal.
1. Go to the Microsoft Bot Framework portal at https://dev.botframework.com and sign
in with your Microsoft Account.
2. Click the Register a Bot button and fill out the form. Note, the Bot Handle needs to be
unique; choose a random name.

3. Use the endpoint generated from your Azure deployment; e.g.,


https://weatherluisbot.azurewebsites.net/api/messages (use HTTPS). And Click on
Create Microsoft App ID and password.
4. Another tab will open in your browser, Generate App ID and Password. Set App name
and App ID will automatically be generated. Finally, click on Generate an app password
and continue.

5. A popup dialog will appear. Copy the password and save it somewhere for later.

6. Back in register bot page, the app ID should be filled in automatically. You can click on
Register at the bottom of the page. Once the bot is created successfully, you will see the
Bot created message. Click on OK.

Exercise 3: Update Bot MicrosoftAppId and MicrosoftAppPassword


Now that the Bot is registered, you need to update the keys in web.config in your Visual
Studio project.
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<appSettings>
<!-- update these with your BotId, Microsoft App Id and your Microsoft App Password--
>
<add key="BotId" value="YourBotId" />
<add key="MicrosoftAppId" value="" />
<add key="MicrosoftAppPassword" value="" />
</appSettings>
<!

You can find the BotId, MicrosoftAppId, MicrosoftAppPassword in the developer dashboard for
your bot. In My bots page, the top left section will display the related details of your bot.

Fill in the BotId as Bot handle, and MicrosoftAppId as Microsoft App ID, and
MicrosoftAppPassword as the password you saved in previous exercise.

Build and re-publish your bot to Azure. You can re-publish by right-clicking on the project and
click Publish.

Exercise 4: Testing the connection to your bot


Back in the developer dashboard for your Bot there is a test chat window that you can use to
interact with your Bot without further configuration, and verify that the Bot Framework can
communicate with your Bot's web service.
Exercise 5: Configuring Channels
Now that you have a Bot up and running, you will want to configure it for one or more channels
your users are using. Configuring channels is a combination of Microsoft Bot Framework
workflow and conversation service workflow, and is unique for each channel you wish to
configure.
1. To configure a channel, go back to the Bot Framework portal at
https://www.botframework.com. Sign in, go to My bots tab, and go to the Channels
panel.
2. For this lab, you can test the bot using Web Chat.
[Optional]
Pick the channel you wish to configure, and click add. You will be taken to a page
of instructions for registering a Bot. In the end in most cases, you are configuring
your credentials as a developer on the target service, registering your app, and
getting a set of Oauth keys that Microsoft Bot Framework can use on your behalf.
3. Click on Get Bot embedded code.
Select the button next to Skype logo. Copy the highlighted URL in embedded
code, e.g.,
https://webchat.botframework.com/embed/helentestweatherbot?s=YOUR_SECRE
T_HERE". Replace YOUR_SECRET_HERE with the secret code. Paste the url in the
browser and you should be able to access your bot via the Web Chat channel.

The full embedded code (<iframe>) can be added to any html page or web page
to embed the Bot into any website.
4. That's the end of configuration - your Bot is ready for your users.

Publishing your bot to the Bot Directory will allow everyone to find your bot in the Bot
Directory. Make sure you take a look at our review guidelines before submitting. You may
try this on your own time.

[Optional] Exercise 6: Trying the Skype Channel


Given you have a Skype account, you can add the Bot into your Skype account and access the
Bot through Skype.
1. Go back to the Bot Framework portal at https://www.botframework.com. Sign in, go to
My bots tab, and go to the Channels panel. Click on Add to Skype button.

2. Login to your own Microsoft Account


3. You will see the screen below. The Bot has been successfully added to your bot contacts
on Skype.
You can share the URL to allow others to add your Bot to their Skype account.
4. You can test the Bot through the Web Skype. In Edge, go to https://web.skype.com/en/
and sign in to your Skype account you used in Step 2.
5. Open Contact > Bots, you can see the Bot your just added.

6. Chat with the Bot in the same manner as before.


Now the Bot can be accessed via Skype. Share your URL to others!
Show off your Skype Bot and create your own Add to Skype button.
https://www.skype.com/en/developer/create-addbot-button/

Das könnte Ihnen auch gefallen