Skip to content

Commit ac4fa17

Browse files
authored
Merge pull request #219 from microsoft/tiens
initial django core-bot sample
2 parents 5c1169c + 5ca3949 commit ac4fa17

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1535
-205
lines changed
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
# Setting up LUIS via CLI:
2+
3+
This README contains information on how to create and deploy a LUIS application. When the bot is ready to be deployed to production, we recommend creating a LUIS Endpoint Resource for usage with your LUIS App.
4+
5+
> _For instructions on how to create a LUIS Application via the LUIS portal, see these Quickstart steps:_
6+
> 1. _[Quickstart: Create a new app in the LUIS portal][Quickstart-create]_
7+
> 2. _[Quickstart: Deploy an app in the LUIS portal][Quickstart-deploy]_
8+
9+
[Quickstart-create]: https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-build-app
10+
[Quickstart-deploy]:https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-deploy-app
11+
12+
## Table of Contents:
13+
14+
- [Prerequisites](#Prerequisites)
15+
- [Import a new LUIS Application using a local LUIS application](#Import-a-new-LUIS-Application-using-a-local-LUIS-application)
16+
- [How to create a LUIS Endpoint resource in Azure and pair it with a LUIS Application](#How-to-create-a-LUIS-Endpoint-resource-in-Azure-and-pair-it-with-a-LUIS-Application)
17+
18+
___
19+
20+
## [Prerequisites](#Table-of-Contents):
21+
22+
#### Install Azure CLI >=2.0.61:
23+
24+
Visit the following page to find the correct installer for your OS:
25+
- https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest
26+
27+
#### Install LUIS CLI >=2.4.0:
28+
29+
Open a CLI of your choice and type the following:
30+
31+
```bash
32+
npm i -g luis-apis@^2.4.0
33+
```
34+
35+
#### LUIS portal account:
36+
37+
You should already have a LUIS account with either https://luis.ai, https://eu.luis.ai, or https://au.luis.ai. To determine where to create a LUIS account, consider where you will deploy your LUIS applications, and then place them in [the corresponding region][LUIS-Authoring-Regions].
38+
39+
After you've created your account, you need your [Authoring Key][LUIS-AKey] and a LUIS application ID.
40+
41+
[LUIS-Authoring-Regions]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-reference-regions#luis-authoring-regions]
42+
[LUIS-AKey]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-concept-keys#authoring-key
43+
44+
___
45+
46+
## [Import a new LUIS Application using a local LUIS application](#Table-of-Contents)
47+
48+
### 1. Import the local LUIS application to luis.ai
49+
50+
```bash
51+
luis import application --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appName "FlightBooking" --in "./cognitiveModels/FlightBooking.json"
52+
```
53+
54+
Outputs the following JSON:
55+
56+
```json
57+
{
58+
"id": "########-####-####-####-############",
59+
"name": "FlightBooking",
60+
"description": "A LUIS model that uses intent and entities.",
61+
"culture": "en-us",
62+
"usageScenario": "",
63+
"domain": "",
64+
"versionsCount": 1,
65+
"createdDateTime": "2019-03-29T18:32:02Z",
66+
"endpoints": {},
67+
"endpointHitsCount": 0,
68+
"activeVersion": "0.1",
69+
"ownerEmail": "[email protected]",
70+
"tokenizerVersion": "1.0.0"
71+
}
72+
```
73+
74+
For the next step, you'll need the `"id"` value for `--appId` and the `"activeVersion"` value for `--versionId`.
75+
76+
### 2. Train the LUIS Application
77+
78+
```bash
79+
luis train version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --wait
80+
```
81+
82+
### 3. Publish the LUIS Application
83+
84+
```bash
85+
luis publish version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --publishRegion "LuisAppPublishRegion"
86+
```
87+
88+
> `--region` corresponds to the region you _author_ your application in. The regions available for this are "westus", "westeurope" and "australiaeast". <br/>
89+
> These regions correspond to the three available portals, https://luis.ai, https://eu.luis.ai, or https://au.luis.ai. <br/>
90+
> `--publishRegion` corresponds to the region of the endpoint you're publishing to, (e.g. "westus", "southeastasia", "westeurope", "brazilsouth"). <br/>
91+
> See the [reference docs][Endpoint-API] for a list of available publish/endpoint regions.
92+
93+
[Endpoint-API]: https://westus.dev.cognitive.microsoft.com/docs/services/5819c76f40a6350ce09de1ac/operations/5819c77140a63516d81aee78
94+
95+
Outputs the following:
96+
97+
```json
98+
{
99+
"versionId": "0.1",
100+
"isStaging": false,
101+
"endpointUrl": "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/########-####-####-####-############",
102+
"region": "westus",
103+
"assignedEndpointKey": null,
104+
"endpointRegion": "westus",
105+
"failedRegions": "",
106+
"publishedDateTime": "2019-03-29T18:40:32Z",
107+
"directVersionPublish": false
108+
}
109+
```
110+
111+
To see how to create an LUIS Cognitive Service Resource in Azure, please see [the next README][README-LUIS]. This Resource should be used when you want to move your bot to production. The instructions will show you how to create and pair the resource with a LUIS Application.
112+
113+
[README-LUIS]: ./README-LUIS.md
114+
115+
___
116+
117+
## [How to create a LUIS Endpoint resource in Azure and pair it with a LUIS Application](#Table-of-Contents)
118+
119+
### 1. Create a new LUIS Cognitive Services resource on Azure via Azure CLI
120+
121+
> _Note:_ <br/>
122+
> _If you don't have a Resource Group in your Azure subscription, you can create one through the Azure portal or through using:_
123+
> ```bash
124+
> az group create --subscription "AzureSubscriptionGuid" --location "westus" --name "ResourceGroupName"
125+
> ```
126+
> _To see a list of valid locations, use `az account list-locations`_
127+
128+
129+
```bash
130+
# Use Azure CLI to create the LUIS Key resource on Azure
131+
az cognitiveservices account create --kind "luis" --name "NewLuisResourceName" --sku "S0" --location "westus" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
132+
```
133+
134+
The command will output a response similar to the JSON below:
135+
136+
```json
137+
{
138+
"endpoint": "https://westus.api.cognitive.microsoft.com/luis/v2.0",
139+
"etag": "\"########-####-####-####-############\"",
140+
"id": "/subscriptions/########-####-####-####-############/resourceGroups/ResourceGroupName/providers/Microsoft.CognitiveServices/accounts/NewLuisResourceName",
141+
"internalId": "################################",
142+
"kind": "luis",
143+
"location": "westus",
144+
"name": "NewLuisResourceName",
145+
"provisioningState": "Succeeded",
146+
"resourceGroup": "ResourceGroupName",
147+
"sku": {
148+
"name": "S0",
149+
"tier": null
150+
},
151+
"tags": null,
152+
"type": "Microsoft.CognitiveServices/accounts"
153+
}
154+
```
155+
156+
157+
158+
Take the output from the previous command and create a JSON file in the following format:
159+
160+
```json
161+
{
162+
"azureSubscriptionId": "00000000-0000-0000-0000-000000000000",
163+
"resourceGroup": "ResourceGroupName",
164+
"accountName": "NewLuisResourceName"
165+
}
166+
```
167+
168+
### 2. Retrieve ARM access token via Azure CLI
169+
170+
```bash
171+
az account get-access-token --subscription "AzureSubscriptionGuid"
172+
```
173+
174+
This will return an object that looks like this:
175+
176+
```json
177+
{
178+
"accessToken": "eyJ0eXAiOiJKVtokentokentokentokentokeng1dCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyIsItokenI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuY29yZS53aW5kb3dzLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTUzODc3MTUwLCJuYmYiOjE1NTM4NzcxNTAsImV4cCI6MTU1Mzg4MTA1MCwiX2NsYWltX25hbWVzIjp7Imdyb3VwcyI6InNyYzEifSwiX2NsYWltX3NvdXJjZXMiOnsic3JjMSI6eyJlbmRwb2ludCI6Imh0dHBzOi8vZ3JhcGgud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3L3VzZXJzL2ZmZTQyM2RkLWJhM2YtNDg0Ny04NjgyLWExNTI5MDA4MjM4Ny9nZXRNZW1iZXJPYmplY3RzIn19LCJhY3IiOiIxIiwiYWlvIjoiQVZRQXEvOEtBQUFBeGVUc201NDlhVH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zvSbl-RY6sAadpOgNHtGvz3Rc6FZRITfkckSLmsKAOFoh-aWC6tFKG8P52rtB0qVVRz9tovBeNqkMYL49s9ypduygbXNVwSQhm5JszeWDgrFuVFHBUP_iENCQYGQpEZf_KvjmX1Ur1F9Eh9nb4yI2gFlKncKNsQl-tokenK7-tokentokentokentokentokentokenatoken",
179+
"expiresOn": "2200-12-31 23:59:59.999999",
180+
"subscription": "AzureSubscriptionGuid",
181+
"tenant": "tenant-guid",
182+
"tokenType": "Bearer"
183+
}
184+
```
185+
186+
The value needed for the next step is the `"accessToken"`.
187+
188+
### 3. Use `luis add appazureaccount` to pair your LUIS resource with a LUIS Application
189+
190+
```bash
191+
luis add appazureaccount --in "path/to/created/requestBody.json" --appId "LuisAppId" --authoringKey "LuisAuthoringKey" --armToken "accessToken"
192+
```
193+
194+
If successful, it should yield a response like this:
195+
196+
```json
197+
{
198+
"code": "Success",
199+
"message": "Operation Successful"
200+
}
201+
```
202+
203+
### 4. See the LUIS Cognitive Services' keys
204+
205+
```bash
206+
az cognitiveservices account keys list --name "NewLuisResourceName" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
207+
```
208+
209+
This will return an object that looks like this:
210+
211+
```json
212+
{
213+
"key1": "9a69####dc8f####8eb4####399f####",
214+
"key2": "####f99e####4b1a####fb3b####6b9f"
215+
}
216+
```
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# CoreBot
2+
3+
Bot Framework v4 core bot sample.
4+
5+
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to:
6+
7+
- Use [LUIS](https://www.luis.ai) to implement core AI capabilities
8+
- Implement a multi-turn conversation using Dialogs
9+
- Handle user interruptions for such things as `Help` or `Cancel`
10+
- Prompt for and validate requests for information from the user
11+
12+
## Prerequisites
13+
14+
This sample **requires** prerequisites in order to run.
15+
16+
### Overview
17+
18+
This bot uses [LUIS](https://www.luis.ai), an AI based cognitive service, to implement language understanding.
19+
20+
### Install Python 3.6
21+
22+
23+
### Create a LUIS Application to enable language understanding
24+
25+
LUIS language model setup, training, and application configuration steps can be found [here](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=cs).
26+
27+
If you wish to create a LUIS application via the CLI, these steps can be found in the [README-LUIS.md](README-LUIS.md).
28+
29+
30+
### Configure your bot to use your LUIS app
31+
32+
Update config.py with your newly imported LUIS app id, LUIS API key from https://<LUIS portal>/user/settings, LUIS API host name, ie <your authoring region>.api.cognitive.microsoft.com. LUIS authoring region is listed on https://<LUIS portal>/user/settings.
33+
34+
35+
## Testing the bot using Bot Framework Emulator
36+
37+
[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
38+
39+
- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
40+
41+
### Connect to the bot using Bot Framework Emulator
42+
43+
- Launch Bot Framework Emulator
44+
- File -> Open Bot
45+
- Enter a Bot URL of `http://localhost:3978/api/messages`
46+
47+
48+
## Further reading
49+
50+
- [Bot Framework Documentation](https://docs.botframework.com)
51+
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
52+
- [Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
53+
- [Gathering Input Using Prompts](https://docs.microsoft.com/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
54+
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
55+
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
56+
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
57+
- [.NET Core CLI tools](https://docs.microsoft.com/dotnet/core/tools/?tabs=netcore2x)
58+
- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
59+
- [Azure Portal](https://portal.azure.com)
60+
- [Language Understanding using LUIS](https://docs.microsoft.com/azure/cognitive-services/luis/)
61+
- [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
"""Booking detail."""
5+
class BookingDetails:
6+
"""Booking detail implementation"""
7+
def __init__(self, destination: str = None, origin: str = None, travel_date: str = None):
8+
self.destination = destination
9+
self.origin = origin
10+
self.travel_date = travel_date
11+
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
"""bots module."""
4+
5+
from .dialog_bot import DialogBot
6+
from .dialog_and_welcome_bot import DialogAndWelcomeBot
7+
8+
__all__ = [
9+
'DialogBot',
10+
'DialogAndWelcomeBot']
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
""" Bot initialization """
5+
# pylint: disable=line-too-long
6+
import sys
7+
from django.apps import AppConfig
8+
from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext, ConversationState, MemoryStorage, UserState)
9+
from dialogs import MainDialog
10+
from bots import DialogAndWelcomeBot
11+
import config
12+
13+
class BotConfig(AppConfig):
14+
""" Bot initialization """
15+
name = 'bots'
16+
appConfig = config.DefaultConfig
17+
18+
SETTINGS = BotFrameworkAdapterSettings(appConfig.APP_ID, appConfig.APP_PASSWORD)
19+
ADAPTER = BotFrameworkAdapter(SETTINGS)
20+
21+
# Create MemoryStorage, UserState and ConversationState
22+
memory = MemoryStorage()
23+
user_state = UserState(memory)
24+
conversation_state = ConversationState(memory)
25+
26+
dialog = MainDialog(appConfig)
27+
bot = DialogAndWelcomeBot(conversation_state, user_state, dialog)
28+
29+
async def on_error(self, context: TurnContext, error: Exception):
30+
"""
31+
Catch-all for errors.
32+
This check writes out errors to console log
33+
NOTE: In production environment, you should consider logging this to Azure
34+
application insights.
35+
"""
36+
print(f'\n [on_turn_error]: { error }', file=sys.stderr)
37+
# Send a message to the user
38+
await context.send_activity('Oops. Something went wrong!')
39+
# Clear out state
40+
await self.conversation_state.delete(context)
41+
42+
def ready(self):
43+
self.ADAPTER.on_turn_error = self.on_error
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
"""Main dialog to welcome users."""
4+
import json
5+
import os.path
6+
from typing import List
7+
from botbuilder.core import TurnContext
8+
from botbuilder.schema import Activity, Attachment, ChannelAccount
9+
from helpers.activity_helper import create_activity_reply
10+
from .dialog_bot import DialogBot
11+
12+
class DialogAndWelcomeBot(DialogBot):
13+
"""Main dialog to welcome users implementation."""
14+
15+
async def on_members_added_activity(self, members_added: List[ChannelAccount],
16+
turn_context: TurnContext):
17+
for member in members_added:
18+
# Greet anyone that was not the target (recipient) of this message.
19+
# To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards
20+
# for more details.
21+
if member.id != turn_context.activity.recipient.id:
22+
welcome_card = self.create_adaptive_card_attachment()
23+
response = self.create_response(turn_context.activity, welcome_card)
24+
await turn_context.send_activity(response)
25+
26+
def create_response(self, activity: Activity, attachment: Attachment):
27+
"""Create an attachment message response."""
28+
response = create_activity_reply(activity)
29+
response.attachments = [attachment]
30+
return response
31+
32+
# Load attachment from file.
33+
def create_adaptive_card_attachment(self):
34+
"""Create an adaptive card."""
35+
relative_path = os.path.abspath(os.path.dirname(__file__))
36+
path = os.path.join(relative_path, "resources/welcomeCard.json")
37+
with open(path) as card_file:
38+
card = json.load(card_file)
39+
40+
return Attachment(
41+
content_type="application/vnd.microsoft.card.adaptive",
42+
content=card)

0 commit comments

Comments
 (0)