Commit 12566a39 authored by dasharatha.vamshi's avatar dasharatha.vamshi

init

parent 2ae83cb3
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.7" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyChainedComparisonsInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoreConstantInTheMiddle" value="true" />
</inspection_tool>
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="56">
<item index="0" class="java.lang.String" itemvalue="scikit-image" />
<item index="1" class="java.lang.String" itemvalue="scipy" />
<item index="2" class="java.lang.String" itemvalue="opencv-python" />
<item index="3" class="java.lang.String" itemvalue="torch" />
<item index="4" class="java.lang.String" itemvalue="torchvision" />
<item index="5" class="java.lang.String" itemvalue="absl-py" />
<item index="6" class="java.lang.String" itemvalue="protobuf" />
<item index="7" class="java.lang.String" itemvalue="rsa" />
<item index="8" class="java.lang.String" itemvalue="tensorflow-estimator" />
<item index="9" class="java.lang.String" itemvalue="opt-einsum" />
<item index="10" class="java.lang.String" itemvalue="python-dateutil" />
<item index="11" class="java.lang.String" itemvalue="cycler" />
<item index="12" class="java.lang.String" itemvalue="gast" />
<item index="13" class="java.lang.String" itemvalue="numpy" />
<item index="14" class="java.lang.String" itemvalue="pyasn1" />
<item index="15" class="java.lang.String" itemvalue="requests" />
<item index="16" class="java.lang.String" itemvalue="importlib-metadata" />
<item index="17" class="java.lang.String" itemvalue="pyasn1-modules" />
<item index="18" class="java.lang.String" itemvalue="requests-oauthlib" />
<item index="19" class="java.lang.String" itemvalue="tensorflow" />
<item index="20" class="java.lang.String" itemvalue="tensorboard-plugin-wit" />
<item index="21" class="java.lang.String" itemvalue="zipp" />
<item index="22" class="java.lang.String" itemvalue="oauthlib" />
<item index="23" class="java.lang.String" itemvalue="astunparse" />
<item index="24" class="java.lang.String" itemvalue="urllib3" />
<item index="25" class="java.lang.String" itemvalue="pyparsing" />
<item index="26" class="java.lang.String" itemvalue="Cython" />
<item index="27" class="java.lang.String" itemvalue="Markdown" />
<item index="28" class="java.lang.String" itemvalue="google-auth-oauthlib" />
<item index="29" class="java.lang.String" itemvalue="Werkzeug" />
<item index="30" class="java.lang.String" itemvalue="kiwisolver" />
<item index="31" class="java.lang.String" itemvalue="tqdm" />
<item index="32" class="java.lang.String" itemvalue="yolov5processor" />
<item index="33" class="java.lang.String" itemvalue="tensorboard" />
<item index="34" class="java.lang.String" itemvalue="future" />
<item index="35" class="java.lang.String" itemvalue="matplotlib" />
<item index="36" class="java.lang.String" itemvalue="cachetools" />
<item index="37" class="java.lang.String" itemvalue="grpcio" />
<item index="38" class="java.lang.String" itemvalue="Keras" />
<item index="39" class="java.lang.String" itemvalue="google-auth" />
<item index="40" class="java.lang.String" itemvalue="idna" />
<item index="41" class="java.lang.String" itemvalue="Pillow" />
<item index="42" class="java.lang.String" itemvalue="cython" />
<item index="43" class="java.lang.String" itemvalue="keras" />
<item index="44" class="java.lang.String" itemvalue="imgaug" />
<item index="45" class="java.lang.String" itemvalue="opencv-contrib-python" />
<item index="46" class="java.lang.String" itemvalue="paho-mqtt" />
<item index="47" class="java.lang.String" itemvalue="pymongo" />
<item index="48" class="java.lang.String" itemvalue="fbprophet" />
<item index="49" class="java.lang.String" itemvalue="scikit-learn" />
<item index="50" class="java.lang.String" itemvalue="sklearn" />
<item index="51" class="java.lang.String" itemvalue="statsmodels" />
<item index="52" class="java.lang.String" itemvalue="python-dotenv" />
<item index="53" class="java.lang.String" itemvalue="pystan" />
<item index="54" class="java.lang.String" itemvalue="Cerberus" />
<item index="55" class="java.lang.String" itemvalue="tenacity" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N802" />
<option value="N806" />
<option value="N801" />
<option value="N803" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="cv2.imresize" />
<option value="detectron2.model_zoo.get_config_file" />
<option value="detectron2.model_zoo.get_checkpoint_url" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/13.core-bot.iml" filepath="$PROJECT_DIR$/.idea/13.core-bot.iml" />
</modules>
</component>
</project>
\ No newline at end of file
| python:S2737N"XAdd logic to this except clause or eliminate it and rethrow the exception automatically.(8񽱞/
\ No newline at end of file
= python:S125'"Remove this commented out code.(šÚ8’Ю­ž/
\ No newline at end of file
U python:S112">Replace this generic exception class with a more specific one.(̲
Z python:S112">Replace this generic exception class with a more specific one.(
U python:S112">Replace this generic exception class with a more specific one.(
\ No newline at end of file
B python:S125<"Remove this commented out code.(Ќ8Ξ/
B python:S1255"Remove this commented out code.(ۗ8Ξ/
\ No newline at end of file
Q
!dialogs/cancel_and_help_dialog.py,6\1\6140e9b9e511b5d6f440d5eca2528ee9627a1af6
@
requirements.txt,1\9\19359a61ae2446b51b549167b014da2fcf265768
>
README-LUIS.md,1\4\1449ae3f4f647618ba83227baf9fb4dbbf58245f
9
README.md,8\e\8ec9a00bfd09b3190ac6b22251dbb1aa95a0579d
9
config.py,1\a\1a1b9769344cb239f2e540e1e6ee1efa2d3034ea
B
booking_details.py,c\5\c566138b481f48e9d3cc5cc83ef5c38c9d0f5a70
F
helpers/luis_helper.py,f\5\f51fa6ddbfa2b03f4a8442b7f93900dfece1687a
L
flight_booking_recognizer.py,e\c\ec68e1438304b7300dd6e364e5ddbc72720551e9
J
helpers/activity_helper.py,d\7\d7382871cefd6ede357ebb670fcb5859ce709072
H
helpers/dialog_helper.py,f\7\f7ef765f9a76af08545b3be173d3edd722741e2a
M
adapter_with_error_handler.py,b\6\b6d46fb98b99de9c079df05b69f9c361e2fa4512
N
bots/dialog_and_welcome_bot.py,1\c\1ca5ae5500a8a0924c8bfcd0f448bf1eb2f384e3
B
bots/dialog_bot.py,2\0\201ee0952c37e7c687b77f5bd90d12185076a39b
F
cards/welcomeCard.json,c\e\ceb799efbfae978ac560580847d723be33c77fe7
R
"cognitiveModels/FlightBooking.json,1\2\1294e7bf56fb1482758ba54663f9fbf5cf1d5160
C
dialogs/__init__.py,5\f\5f8757606256e9f4337b404b7eb71e0390193b1f
F
dialogs/main_dialog.py,3\e\3e76f1a41b8ae527f00ef5bbe8be28ac14ac8426
6
app.py,1\3\13cce7fd076299c81b4986166f3d822791c9490e
J
dialogs/safetychecklist.py,c\f\cf2ba69327064c3df67b735119face2546699049
]
-deploymentTemplates/template-with-new-rg.json,f\3\f3104ef68c55408b4c75835d5834adbdc9088a06
e
5deploymentTemplates/template-with-preexisting-rg.json,2\0\206e1a0f86f5e0aab92e438e9cb37f73288f02a1
?
cards/task.json,b\0\b0d96616dc72a17df804968fcc74cf65e1082d25
=
train_luis.py,4\0\40be1e14310658249586b6506773aeaacfa01dcc
>
dialogs/faq.py,c\8\c8559fd2b847b14b05c7a7c363c1f8ced563117c
\ No newline at end of file
# Setting up LUIS via CLI:
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.
> _For instructions on how to create a LUIS Application via the LUIS portal, see these Quickstart steps:_
> 1. _[Quickstart: Create a new app in the LUIS portal][Quickstart-create]_
> 2. _[Quickstart: Deploy an app in the LUIS portal][Quickstart-deploy]_
[Quickstart-create]: https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-build-app
[Quickstart-deploy]:https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-deploy-app
## Table of Contents:
- [Prerequisites](#Prerequisites)
- [Import a new LUIS Application using a local LUIS application](#Import-a-new-LUIS-Application-using-a-local-LUIS-application)
- [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)
___
## [Prerequisites](#Table-of-Contents):
#### Install Azure CLI >=2.0.61:
Visit the following page to find the correct installer for your OS:
- https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest
#### Install LUIS CLI >=2.4.0:
Open a CLI of your choice and type the following:
```bash
npm i -g luis-apis@^2.4.0
```
#### LUIS portal account:
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].
After you've created your account, you need your [Authoring Key][LUIS-AKey] and a LUIS application ID.
[LUIS-Authoring-Regions]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-reference-regions#luis-authoring-regions]
[LUIS-AKey]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-concept-keys#authoring-key
___
## [Import a new LUIS Application using a local LUIS application](#Table-of-Contents)
### 1. Import the local LUIS application to luis.ai
```bash
luis import application --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appName "FlightBooking" --in "./cognitiveModels/FlightBooking.json"
```
Outputs the following JSON:
```json
{
"id": "########-####-####-####-############",
"name": "FlightBooking",
"description": "A LUIS model that uses intent and entities.",
"culture": "en-us",
"usageScenario": "",
"domain": "",
"versionsCount": 1,
"createdDateTime": "2019-03-29T18:32:02Z",
"endpoints": {},
"endpointHitsCount": 0,
"activeVersion": "0.1",
"ownerEmail": "bot@contoso.com",
"tokenizerVersion": "1.0.0"
}
```
For the next step, you'll need the `"id"` value for `--appId` and the `"activeVersion"` value for `--versionId`.
### 2. Train the LUIS Application
```bash
luis train version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --wait
```
### 3. Publish the LUIS Application
```bash
luis publish version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --publishRegion "LuisAppPublishRegion"
```
> `--region` corresponds to the region you _author_ your application in. The regions available for this are "westus", "westeurope" and "australiaeast". <br/>
> These regions correspond to the three available portals, https://luis.ai, https://eu.luis.ai, or https://au.luis.ai. <br/>
> `--publishRegion` corresponds to the region of the endpoint you're publishing to, (e.g. "westus", "southeastasia", "westeurope", "brazilsouth"). <br/>
> See the [reference docs][Endpoint-API] for a list of available publish/endpoint regions.
[Endpoint-API]: https://westus.dev.cognitive.microsoft.com/docs/services/5819c76f40a6350ce09de1ac/operations/5819c77140a63516d81aee78
Outputs the following:
```json
{
"versionId": "0.1",
"isStaging": false,
"endpointUrl": "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/########-####-####-####-############",
"region": "westus",
"assignedEndpointKey": null,
"endpointRegion": "westus",
"failedRegions": "",
"publishedDateTime": "2019-03-29T18:40:32Z",
"directVersionPublish": false
}
```
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.
[README-LUIS]: ./README-LUIS.md
___
## [How to create a LUIS Endpoint resource in Azure and pair it with a LUIS Application](#Table-of-Contents)
### 1. Create a new LUIS Cognitive Services resource on Azure via Azure CLI
> _Note:_ <br/>
> _If you don't have a Resource Group in your Azure subscription, you can create one through the Azure portal or through using:_
> ```bash
> az group create --subscription "AzureSubscriptionGuid" --location "westus" --name "ResourceGroupName"
> ```
> _To see a list of valid locations, use `az account list-locations`_
```bash
# Use Azure CLI to create the LUIS Key resource on Azure
az cognitiveservices account create --kind "luis" --name "NewLuisResourceName" --sku "S0" --location "westus" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
```
The command will output a response similar to the JSON below:
```json
{
"endpoint": "https://westus.api.cognitive.microsoft.com/luis/v2.0",
"etag": "\"########-####-####-####-############\"",
"id": "/subscriptions/########-####-####-####-############/resourceGroups/ResourceGroupName/providers/Microsoft.CognitiveServices/accounts/NewLuisResourceName",
"internalId": "################################",
"kind": "luis",
"location": "westus",
"name": "NewLuisResourceName",
"provisioningState": "Succeeded",
"resourceGroup": "ResourceGroupName",
"sku": {
"name": "S0",
"tier": null
},
"tags": null,
"type": "Microsoft.CognitiveServices/accounts"
}
```
Take the output from the previous command and create a JSON file in the following format:
```json
{
"azureSubscriptionId": "00000000-0000-0000-0000-000000000000",
"resourceGroup": "ResourceGroupName",
"accountName": "NewLuisResourceName"
}
```
### 2. Retrieve ARM access token via Azure CLI
```bash
az account get-access-token --subscription "AzureSubscriptionGuid"
```
This will return an object that looks like this:
```json
{
"accessToken": "eyJ0eXAiOiJKVtokentokentokentokentokeng1dCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyIsItokenI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuY29yZS53aW5kb3dzLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTUzODc3MTUwLCJuYmYiOjE1NTM4NzcxNTAsImV4cCI6MTU1Mzg4MTA1MCwiX2NsYWltX25hbWVzIjp7Imdyb3VwcyI6InNyYzEifSwiX2NsYWltX3NvdXJjZXMiOnsic3JjMSI6eyJlbmRwb2ludCI6Imh0dHBzOi8vZ3JhcGgud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3L3VzZXJzL2ZmZTQyM2RkLWJhM2YtNDg0Ny04NjgyLWExNTI5MDA4MjM4Ny9nZXRNZW1iZXJPYmplY3RzIn19LCJhY3IiOiIxIiwiYWlvIjoiQVZRQXEvOEtBQUFBeGVUc201NDlhVHg4RE1mMFlRVnhGZmxxOE9RSC9PODR3QktuSmRqV1FqTkkwbmxLYzB0bHJEZzMyMFZ5bWZGaVVBSFBvNUFFUTNHL0FZNDRjdk01T3M0SEt0OVJkcE5JZW9WU0dzd0kvSkk9IiwiYW1yIjpbIndpYSIsIm1mYSJdLCJhcHBpZCI6IjA0YjA3Nzk1LThkZGItNDYxYS1iYmVlLTAyZjllMWJmN2I0NiIsImFwcGlkYWNyIjoiMCIsImRldmljZWlkIjoiNDhmNDVjNjEtMTg3Zi00MjUxLTlmZWItMTllZGFkZmMwMmE3IiwiZmFtaWx5X25hbWUiOiJHdW0iLCJnaXZlbl9uYW1lIjoiU3RldmVuIiwiaXBhZGRyIjoiMTY3LjIyMC4yLjU1IiwibmFtZSI6IlN0ZXZlbiBHdW0iLCJvaWQiOiJmZmU0MjNkZC1iYTNmLTQ4NDctODY4Mi1hMTUyOTAwODIzODciLCJvbnByZW1fc2lkIjoiUy0xLTUtMjEtMjEyNzUyMTE4NC0xNjA0MDEyOTIwLTE4ODc5Mjc1MjctMjYwOTgyODUiLCJwdWlkIjoiMTAwMzdGRkVBMDQ4NjlBNyIsInJoIjoiSSIsInNjcCI6InVzZXJfaW1wZXJzb25hdGlvbiIsInN1YiI6Ik1rMGRNMWszN0U5ckJyMjhieUhZYjZLSU85LXVFQVVkZFVhNWpkSUd1Nk0iLCJ0aWQiOiI3MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDciLCJ1bmlxdWVfbmFtZSI6InN0Z3VtQG1pY3Jvc29mdC5jb20iLCJ1cG4iOiJzdGd1bUBtaWNyb3NvZnQuY29tIiwidXRpIjoiT2w2NGN0TXY4RVNEQzZZQWRqRUFtokenInZlciI6IjEuMCJ9.kFAsEilE0mlS1pcpqxf4rEnRKeYsehyk-gz-zJHUrE__oad3QjgDSBDPrR_ikLdweynxbj86pgG4QFaHURNCeE6SzrbaIrNKw-n9jrEtokenlosOxg_0l2g1LeEUOi5Q4gQREAU_zvSbl-RY6sAadpOgNHtGvz3Rc6FZRITfkckSLmsKAOFoh-aWC6tFKG8P52rtB0qVVRz9tovBeNqkMYL49s9ypduygbXNVwSQhm5JszeWDgrFuVFHBUP_iENCQYGQpEZf_KvjmX1Ur1F9Eh9nb4yI2gFlKncKNsQl-tokenK7-tokentokentokentokentokentokenatoken",
"expiresOn": "2200-12-31 23:59:59.999999",
"subscription": "AzureSubscriptionGuid",
"tenant": "tenant-guid",
"tokenType": "Bearer"
}
```
The value needed for the next step is the `"accessToken"`.
### 3. Use `luis add appazureaccount` to pair your LUIS resource with a LUIS Application
```bash
luis add appazureaccount --in "path/to/created/requestBody.json" --appId "LuisAppId" --authoringKey "LuisAuthoringKey" --armToken "accessToken"
```
If successful, it should yield a response like this:
```json
{
"code": "Success",
"message": "Operation Successful"
}
```
### 4. See the LUIS Cognitive Services' keys
```bash
az cognitiveservices account keys list --name "NewLuisResourceName" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
```
This will return an object that looks like this:
```json
{
"key1": "9a69####dc8f####8eb4####399f####",
"key2": "####f99e####4b1a####fb3b####6b9f"
}
```
\ No newline at end of file
# CoreBot
Bot Framework v4 core bot sample.
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to:
- Use [LUIS](https://www.luis.ai) to implement core AI capabilities
- Implement a multi-turn conversation using Dialogs
- Handle user interruptions for such things as `Help` or `Cancel`
- Prompt for and validate requests for information from the user
## Prerequisites
This sample **requires** prerequisites in order to run.
### Overview
This bot uses [LUIS](https://www.luis.ai), an AI based cognitive service, to implement language understanding.
### Create a LUIS Application to enable language understanding
The LUIS model for this example can be found under `CognitiveModels/FlightBooking.json` and the LUIS language model setup, training, and application configuration steps can be found [here](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=cs).
Once you created the LUIS model, update `config.py` with your `LuisAppId`, `LuisAPIKey` and `LuisAPIHostName`.
```json
"LuisAppId": "Your LUIS App Id",
"LuisAPIKey": "Your LUIS Subscription key here",
"LuisAPIHostName": "Your LUIS App region here (i.e: westus.api.cognitive.microsoft.com)"
```
## To try this sample
- Clone the repository
```bash
git clone https://github.com/Microsoft/botbuilder-samples.git
```
- In a terminal, navigate to `botbuilder-samples\samples\python\13.core-bot` folder
- Activate your desired virtual environment
- In the terminal, type `pip install -r requirements.txt`
- Run your bot with `python app.py`
## Testing the bot using Bot Framework Emulator
[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.
- Install the latest Bot Framework Emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
### Connect to the bot using Bot Framework Emulator
- Launch Bot Framework Emulator
- File -> Open Bot
- Enter a Bot URL of `http://localhost:3978/api/messages`
## Deploy the bot to Azure
To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.
## Further reading
- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Dialogs](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
- [Gathering Input Using Prompts](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
- [Azure Portal](https://portal.azure.com)
- [Language Understanding using LUIS](https://docs.microsoft.com/en-us/azure/cognitive-services/luis/)
- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
import traceback
from datetime import datetime
from botbuilder.core import (
BotFrameworkAdapter,
BotFrameworkAdapterSettings,
ConversationState,
TurnContext,
)
from botbuilder.schema import ActivityTypes, Activity
class AdapterWithErrorHandler(BotFrameworkAdapter):
def __init__(
self,
settings: BotFrameworkAdapterSettings,
conversation_state: ConversationState,
):
super().__init__(settings)
self._conversation_state = conversation_state
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
traceback.print_exc()
# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
# Clear out state
nonlocal self
await self._conversation_state.delete(context)
self.on_turn_error = on_error
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
This sample shows how to create a bot that demonstrates the following:
- Use [LUIS](https://www.luis.ai) to implement core AI capabilities.
- Implement a multi-turn conversation using Dialogs.
- Handle user interruptions for such things as `Help` or `Cancel`.
- Prompt for and validate requests for information from the user.
"""
from http import HTTPStatus
from aiohttp import web
from aiohttp.web import Request, Response, json_response
from botbuilder.core import (
BotFrameworkAdapterSettings,
ConversationState,
MemoryStorage,
UserState,
)
from botbuilder.core.integration import aiohttp_error_middleware
from botbuilder.schema import Activity
from config import DefaultConfig
from dialogs import MainDialog, safetychecklist, faq
from bots import DialogAndWelcomeBot
from adapter_with_error_handler import AdapterWithErrorHandler
from flight_booking_recognizer import FlightBookingRecognizer
CONFIG = DefaultConfig()
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
# Create MemoryStorage, UserState and ConversationState
MEMORY = MemoryStorage()
USER_STATE = UserState(MEMORY)
CONVERSATION_STATE = ConversationState(MEMORY)
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)
# Create dialogs and Bot
RECOGNIZER = FlightBookingRecognizer(CONFIG)
safetychecklist = safetychecklist()
faq = faq()
DIALOG = MainDialog(RECOGNIZER, safetychecklist, faq)
BOT = DialogAndWelcomeBot(CONVERSATION_STATE, USER_STATE, DIALOG)
# Listen for incoming requests on /api/messages.
async def messages(req: Request) -> Response:
# Main bot message handler.
if "application/json" in req.headers["Content-Type"]:
body = await req.json()
else:
return Response(status=HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
activity = Activity().deserialize(body)
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
if response:
return json_response(data=response.body, status=response.status)
return Response(status=HTTPStatus.OK)
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
if __name__ == "__main__":
try:
web.run_app(APP, host="localhost", port=CONFIG.PORT)
except Exception as error:
raise error
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class BookingDetails:
def __init__(
self,
destination: str = None,
origin: str = None,
travel_date: str = None,
unsupported_airports=None,
):
if unsupported_airports is None:
unsupported_airports = []
self.destination = destination
self.origin = origin
self.travel_date = travel_date
self.unsupported_airports = unsupported_airports
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .dialog_bot import DialogBot
from .dialog_and_welcome_bot import DialogAndWelcomeBot
__all__ = ["DialogBot", "DialogAndWelcomeBot"]
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import os.path
from typing import List
from botbuilder.core import (
ConversationState,
MessageFactory,
UserState,
TurnContext,
)
from botbuilder.dialogs import Dialog
from botbuilder.schema import Attachment, ChannelAccount
from helpers.dialog_helper import DialogHelper
from .dialog_bot import DialogBot
class DialogAndWelcomeBot(DialogBot):
def __init__(
self,
conversation_state: ConversationState,
user_state: UserState,
dialog: Dialog,
):
super(DialogAndWelcomeBot, self).__init__(
conversation_state, user_state, dialog
)
async def on_members_added_activity(
self, members_added: List[ChannelAccount], turn_context: TurnContext
):
for member in members_added:
# Greet anyone that was not the target (recipient) of this message.
# To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
if member.id != turn_context.activity.recipient.id:
# welcome_card = self.create_adaptive_card_attachment()
# response = MessageFactory.attachment(welcome_card)
# await turn_context.send_activity(response)
await DialogHelper.run_dialog(
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState"),
)
# Load attachment from file.
def create_adaptive_card_attachment(self):
relative_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(relative_path, "../cards/welcomeCard.json")
with open(path) as in_file:
card = json.load(in_file)
return Attachment(
content_type="application/vnd.microsoft.card.adaptive", content=card
)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import ActivityHandler, ConversationState, UserState, TurnContext
from botbuilder.dialogs import Dialog
from helpers.dialog_helper import DialogHelper
class DialogBot(ActivityHandler):
def __init__(
self,
conversation_state: ConversationState,
user_state: UserState,
dialog: Dialog,
):
if conversation_state is None:
raise Exception(
"[DialogBot]: Missing parameter. conversation_state is required"
)
if user_state is None:
raise Exception("[DialogBot]: Missing parameter. user_state is required")
if dialog is None:
raise Exception("[DialogBot]: Missing parameter. dialog is required")
self.conversation_state = conversation_state
self.user_state = user_state
self.dialog = dialog
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)
# Save any state changes that might have occurred during the turn.
await self.conversation_state.save_changes(turn_context, False)
await self.user_state.save_changes(turn_context, False)
async def on_message_activity(self, turn_context: TurnContext):
await DialogHelper.run_dialog(
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState"),
)
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "TextBlock",
"spacing": "Medium",
"size": "default",
"weight": "Bolder",
"text": "Task Details",
"wrap": true,
"maxLines": 0
},
{
"type": "TextBlock",
"size": "default",
"isSubtle": true,
"text": "STEPS TO COMPLETE THE TASK",
"wrap": true,
"maxLines": 0
},
{
"type": "TextBlock",
"size": "Medium",
"isSubtle": true,
"text": "a. Safety Checklist",
"wrap": true,
"maxLines": 1,
"fontType": "Monospace",
"weight": "Bolder"
},
{
"type": "TextBlock",
"size": "Medium",
"isSubtle": true,
"text": "b. Visual Inspection",
"wrap": true,
"maxLines": 1,
"fontType": "Monospace",
"weight": "Bolder"
}
]
}
\ No newline at end of file
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "Image",
"url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU",
"size": "stretch"
},
{
"type": "TextBlock",
"spacing": "medium",
"size": "default",
"weight": "bolder",
"text": "Welcome to Bot Framework!",
"wrap": true,
"maxLines": 0
},
{
"type": "TextBlock",
"size": "default",
"isSubtle": "true",
"text": "Now that you have successfully run your bot, follow the links in this Adaptive Card to expand your knowledge of Bot Framework.",
"wrap": true,
"maxLines": 0
}
],
"actions": [
{
"type": "Action.OpenUrl",
"title": "Get an overview",
"url": "https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0"
},
{
"type": "Action.OpenUrl",
"title": "Ask a question",
"url": "https://stackoverflow.com/questions/tagged/botframework"
},
{
"type": "Action.OpenUrl",
"title": "Learn how to deploy",
"url": "https://docs.microsoft.com/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
}
]
}
\ No newline at end of file
{
"luis_schema_version": "7.0.0",
"intents": [
{
"name": "None",
"features": []
},
{
"name": "qna",
"features": []
},
{
"name": "quality",
"features": []
},
{
"name": "safety",
"features": []
}
],
"entities": [],
"hierarchicals": [],
"composites": [],
"closedLists": [],
"prebuiltEntities": [
{
"name": "dimension",
"roles": []
},
{
"name": "number",
"roles": []
},
{
"name": "percentage",
"roles": []
},
{
"name": "temperature",
"roles": []
}
],
"utterances": [
{
"text": "can you answer some of my questions",
"intent": "qna",
"entities": []
},
{
"text": "i have few questions",
"intent": "qna",
"entities": []
},
{
"text": "i want to check my safety gear",
"intent": "safety",
"entities": []
},
{
"text": "i want to do a quality inspection",
"intent": "quality",
"entities": []
},
{
"text": "i want to take a safety inspection",
"intent": "safety",
"entities": []
},
{
"text": "quality inspection",
"intent": "quality",
"entities": []
},
{
"text": "questions",
"intent": "qna",
"entities": []
},
{
"text": "safety inspection",
"intent": "safety",
"entities": []
}
],
"versionId": "0.1",
"name": "ilens-assistant-luis",
"desc": "ilens-assistant-luis",
"culture": "en-us",
"tokenizerVersion": "1.0.0",
"patternAnyEntities": [],
"regex_entities": [],
"phraselists": [],
"regex_features": [],
"patterns": [],
"settings": []
}
\ No newline at end of file
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
""" Bot Configuration """
class DefaultConfig:
""" Bot Configuration """
PORT = 3978
APP_ID = os.environ.get("MicrosoftAppId", "")
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
LUIS_APP_ID = os.environ.get("LuisAppId", "45646243-2016-4f0a-9145-e93a7f58e355")
LUIS_API_KEY = os.environ.get("LuisAPIKey", "f19be164fbfc49a3972f940835820d7e")
# LUIS endpoint host name, ie "westus.api.cognitive.microsoft.com"
LUIS_API_HOST_NAME = os.environ.get("LuisAPIHostName", "westus.api.cognitive.microsoft.com")
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"groupLocation": {
"type": "string",
"metadata": {
"description": "Specifies the location of the Resource Group."
}
},
"groupName": {
"type": "string",
"metadata": {
"description": "Specifies the name of the Resource Group."
}
},
"appId": {
"type": "string",
"metadata": {
"description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
}
},
"appSecret": {
"type": "string",
"metadata": {
"description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings."
}
},
"botId": {
"type": "string",
"metadata": {
"description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
}
},
"botSku": {
"type": "string",
"metadata": {
"description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
}
},
"newAppServicePlanName": {
"type": "string",
"metadata": {
"description": "The name of the App Service Plan."
}
},
"newAppServicePlanSku": {
"type": "object",
"defaultValue": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
},
"metadata": {
"description": "The SKU of the App Service Plan. Defaults to Standard values."
}
},
"newAppServicePlanLocation": {
"type": "string",
"metadata": {
"description": "The location of the App Service Plan. Defaults to \"westus\"."
}
},
"newWebAppName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
}
}
},
"variables": {
"appServicePlanName": "[parameters('newAppServicePlanName')]",
"resourcesLocation": "[parameters('newAppServicePlanLocation')]",
"webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
"siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
"botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]",
"publishingUsername": "[concat('$', parameters('newWebAppName'))]",
"resourceGroupId": "[concat(subscription().id, '/resourceGroups/', parameters('groupName'))]"
},
"resources": [
{
"name": "[parameters('groupName')]",
"type": "Microsoft.Resources/resourceGroups",
"apiVersion": "2018-05-01",
"location": "[parameters('groupLocation')]",
"properties": {}
},
{
"type": "Microsoft.Resources/deployments",
"apiVersion": "2018-05-01",
"name": "storageDeployment",
"resourceGroup": "[parameters('groupName')]",
"dependsOn": [
"[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
],
"properties": {
"mode": "Incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {},
"resources": [
{
"comments": "Create a new Linux App Service Plan if no existing App Service Plan name was passed in.",
"type": "Microsoft.Web/serverfarms",
"name": "[variables('appServicePlanName')]",
"apiVersion": "2018-02-01",
"location": "[variables('resourcesLocation')]",
"sku": "[parameters('newAppServicePlanSku')]",
"kind": "linux",
"properties": {
"name": "[variables('appServicePlanName')]",
"perSiteScaling": false,
"reserved": true,
"targetWorkerCount": 0,
"targetWorkerSizeId": 0
}
},
{
"comments": "Create a Web App using a Linux App Service Plan",
"type": "Microsoft.Web/sites",
"apiVersion": "2015-08-01",
"location": "[variables('resourcesLocation')]",
"kind": "app,linux",
"dependsOn": [
"[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/serverfarms/', variables('appServicePlanName'))]"
],
"name": "[variables('webAppName')]",
"properties": {
"name": "[variables('webAppName')]",
"hostNameSslStates": [
{
"name": "[concat(parameters('newWebAppName'), '.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Standard"
},
{
"name": "[concat(parameters('newWebAppName'), '.scm.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Repository"
}
],
"serverFarmId": "[variables('appServicePlanName')]",
"siteConfig": {
"appSettings": [
{
"name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
"value": "true"
},
{
"name": "MicrosoftAppId",
"value": "[parameters('appId')]"
},
{
"name": "MicrosoftAppPassword",
"value": "[parameters('appSecret')]"
}
],
"cors": {
"allowedOrigins": [
"https://botservice.hosting.portal.azure.net",
"https://hosting.onecloud.azure-test.net/"
]
}
}
}
},
{
"type": "Microsoft.Web/sites/config",
"apiVersion": "2016-08-01",
"name": "[concat(variables('webAppName'), '/web')]",
"location": "[variables('resourcesLocation')]",
"dependsOn": [
"[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/sites/', variables('webAppName'))]"
],
"properties": {
"numberOfWorkers": 1,
"defaultDocuments": [
"Default.htm",
"Default.html",
"Default.asp",
"index.htm",
"index.html",
"iisstart.htm",
"default.aspx",
"index.php",
"hostingstart.html"
],
"netFrameworkVersion": "v4.0",
"phpVersion": "",
"pythonVersion": "",
"nodeVersion": "",
"linuxFxVersion": "PYTHON|3.7",
"requestTracingEnabled": false,
"remoteDebuggingEnabled": false,
"remoteDebuggingVersion": "VS2017",
"httpLoggingEnabled": true,
"logsDirectorySizeLimit": 35,
"detailedErrorLoggingEnabled": false,
"publishingUsername": "[variables('publishingUsername')]",
"scmType": "None",
"use32BitWorkerProcess": true,
"webSocketsEnabled": false,
"alwaysOn": false,
"appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
"managedPipelineMode": "Integrated",
"virtualApplications": [
{
"virtualPath": "/",
"physicalPath": "site\\wwwroot",
"preloadEnabled": false,
"virtualDirectories": null
}
],
"winAuthAdminState": 0,
"winAuthTenantState": 0,
"customAppPoolIdentityAdminState": false,
"customAppPoolIdentityTenantState": false,
"loadBalancing": "LeastRequests",
"routingRules": [],
"experiments": {
"rampUpRules": []
},
"autoHealEnabled": false,
"vnetName": "",
"minTlsVersion": "1.2",
"ftpsState": "AllAllowed",
"reservedInstanceCount": 0
}
},
{
"apiVersion": "2017-12-01",
"type": "Microsoft.BotService/botServices",
"name": "[parameters('botId')]",
"location": "global",
"kind": "bot",
"sku": {
"name": "[parameters('botSku')]"
},
"properties": {
"name": "[parameters('botId')]",
"displayName": "[parameters('botId')]",
"endpoint": "[variables('botEndpoint')]",
"msaAppId": "[parameters('appId')]",
"developerAppInsightsApplicationId": null,
"developerAppInsightKey": null,
"publishingCredentials": null,
"storageResourceId": null
},
"dependsOn": [
"[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/sites/', variables('webAppName'))]"
]
}
],
"outputs": {}
}
}
}
]
}
\ No newline at end of file
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"appId": {
"type": "string",
"metadata": {
"description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
}
},
"appSecret": {
"type": "string",
"metadata": {
"description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings."
}
},
"botId": {
"type": "string",
"metadata": {
"description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
}
},
"botSku": {
"defaultValue": "F0",
"type": "string",
"metadata": {
"description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
}
},
"newAppServicePlanName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The name of the new App Service Plan."
}
},
"newAppServicePlanSku": {
"type": "object",
"defaultValue": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
},
"metadata": {
"description": "The SKU of the App Service Plan. Defaults to Standard values."
}
},
"appServicePlanLocation": {
"type": "string",
"metadata": {
"description": "The location of the App Service Plan."
}
},
"existingAppServicePlan": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "Name of the existing App Service Plan used to create the Web App for the bot."
}
},
"newWebAppName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
}
}
},
"variables": {
"defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]",
"useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
"servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), parameters('newAppServicePlanName'))]",
"publishingUsername": "[concat('$', parameters('newWebAppName'))]",
"resourcesLocation": "[parameters('appServicePlanLocation')]",
"webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
"siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
"botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
},
"resources": [
{
"comments": "Create a new Linux App Service Plan if no existing App Service Plan name was passed in.",
"type": "Microsoft.Web/serverfarms",
"apiVersion": "2016-09-01",
"name": "[variables('servicePlanName')]",
"location": "[variables('resourcesLocation')]",
"sku": "[parameters('newAppServicePlanSku')]",
"kind": "linux",
"properties": {
"name": "[variables('servicePlanName')]",
"perSiteScaling": false,
"reserved": true,
"targetWorkerCount": 0,
"targetWorkerSizeId": 0
}
},
{
"comments": "Create a Web App using a Linux App Service Plan",
"type": "Microsoft.Web/sites",
"apiVersion": "2016-08-01",
"name": "[variables('webAppName')]",
"location": "[variables('resourcesLocation')]",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]"
],
"kind": "app,linux",
"properties": {
"enabled": true,
"hostNameSslStates": [
{
"name": "[concat(parameters('newWebAppName'), '.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Standard"
},
{
"name": "[concat(parameters('newWebAppName'), '.scm.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Repository"
}
],
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]",
"reserved": true,
"scmSiteAlsoStopped": false,
"clientAffinityEnabled": false,
"clientCertEnabled": false,
"hostNamesDisabled": false,
"containerSize": 0,
"dailyMemoryTimeQuota": 0,
"httpsOnly": false,
"siteConfig": {
"appSettings": [
{
"name": "MicrosoftAppId",
"value": "[parameters('appId')]"
},
{
"name": "MicrosoftAppPassword",
"value": "[parameters('appSecret')]"
},
{
"name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
"value": "true"
}
],
"cors": {
"allowedOrigins": [
"https://botservice.hosting.portal.azure.net",
"https://hosting.onecloud.azure-test.net/"
]
}
}
}
},
{
"type": "Microsoft.Web/sites/config",
"apiVersion": "2016-08-01",
"name": "[concat(variables('webAppName'), '/web')]",
"location": "[variables('resourcesLocation')]",
"dependsOn": [
"[resourceId('Microsoft.Web/sites', variables('webAppName'))]"
],
"properties": {
"numberOfWorkers": 1,
"defaultDocuments": [
"Default.htm",
"Default.html",
"Default.asp",
"index.htm",
"index.html",
"iisstart.htm",
"default.aspx",
"index.php",
"hostingstart.html"
],
"netFrameworkVersion": "v4.0",
"phpVersion": "",
"pythonVersion": "",
"nodeVersion": "",
"linuxFxVersion": "PYTHON|3.7",
"requestTracingEnabled": false,
"remoteDebuggingEnabled": false,
"remoteDebuggingVersion": "VS2017",
"httpLoggingEnabled": true,
"logsDirectorySizeLimit": 35,
"detailedErrorLoggingEnabled": false,
"publishingUsername": "[variables('publishingUsername')]",
"scmType": "None",
"use32BitWorkerProcess": true,
"webSocketsEnabled": false,
"alwaysOn": false,
"appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
"managedPipelineMode": "Integrated",
"virtualApplications": [
{
"virtualPath": "/",
"physicalPath": "site\\wwwroot",
"preloadEnabled": false,
"virtualDirectories": null
}
],
"winAuthAdminState": 0,
"winAuthTenantState": 0,
"customAppPoolIdentityAdminState": false,
"customAppPoolIdentityTenantState": false,
"loadBalancing": "LeastRequests",
"routingRules": [],
"experiments": {
"rampUpRules": []
},
"autoHealEnabled": false,
"vnetName": "",
"minTlsVersion": "1.2",
"ftpsState": "AllAllowed",
"reservedInstanceCount": 0
}
},
{
"apiVersion": "2017-12-01",
"type": "Microsoft.BotService/botServices",
"name": "[parameters('botId')]",
"location": "global",
"kind": "bot",
"sku": {
"name": "[parameters('botSku')]"
},
"properties": {
"name": "[parameters('botId')]",
"displayName": "[parameters('botId')]",
"endpoint": "[variables('botEndpoint')]",
"msaAppId": "[parameters('appId')]",
"developerAppInsightsApplicationId": null,
"developerAppInsightKey": null,
"publishingCredentials": null,
"storageResourceId": null
},
"dependsOn": [
"[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
]
}
]
}
\ No newline at end of file
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .cancel_and_help_dialog import CancelAndHelpDialog
from .safetychecklist import safetychecklist
from .main_dialog import MainDialog
from .faq import faq
__all__ = ["CancelAndHelpDialog", "MainDialog","safetychecklist","faq"]
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs import (
ComponentDialog,
DialogContext,
DialogTurnResult,
DialogTurnStatus,
)
from botbuilder.schema import ActivityTypes, InputHints
from botbuilder.core import MessageFactory
class CancelAndHelpDialog(ComponentDialog):
def __init__(self, dialog_id: str):
super(CancelAndHelpDialog, self).__init__(dialog_id)
async def on_continue_dialog(self, inner_dc: DialogContext) -> DialogTurnResult:
result = await self.interrupt(inner_dc)
if result is not None:
return result
return await super(CancelAndHelpDialog, self).on_continue_dialog(inner_dc)
async def interrupt(self, inner_dc: DialogContext) -> DialogTurnResult:
if inner_dc.context.activity.type == ActivityTypes.message:
text = inner_dc.context.activity.text.lower()
help_message_text = "Show Help..."
help_message = MessageFactory.text(
help_message_text, help_message_text, InputHints.expecting_input
)
if text in ("help", "?"):
await inner_dc.context.send_activity(help_message)
return DialogTurnResult(DialogTurnStatus.Waiting)
cancel_message_text = "Cancelling"
cancel_message = MessageFactory.text(
cancel_message_text, cancel_message_text, InputHints.ignoring_input
)
if text in ("cancel", "quit"):
await inner_dc.context.send_activity(cancel_message)
return await inner_dc.cancel_all_dialogs()
return None
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from datatypes_date_time.timex import Timex
from botbuilder.dialogs import WaterfallDialog, WaterfallStepContext, DialogTurnResult
from botbuilder.dialogs.prompts import ConfirmPrompt, TextPrompt, PromptOptions
from botbuilder.core import MessageFactory
from botbuilder.schema import InputHints
from .cancel_and_help_dialog import CancelAndHelpDialog
from botbuilder.schema import ChannelAccount, CardAction, ActionTypes, SuggestedActions
class faq(CancelAndHelpDialog):
def __init__(self, dialog_id: str = None):
super(faq, self).__init__(dialog_id or faq.__name__)
self.add_dialog(TextPrompt(TextPrompt.__name__))
self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
self.add_dialog(
WaterfallDialog(
WaterfallDialog.__name__,
[
self.first_step, self.final_step, self.end_step
],
)
)
self.initial_dialog_id = WaterfallDialog.__name__
async def first_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
Complete the interaction and end the dialog.
:param step_context:
:return DialogTurnResult:
"""
reply = MessageFactory.text("please ask your question")
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=reply)
)
async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
Complete the interaction and end the dialog.
:param step_context:
:return DialogTurnResult:
"""
await step_context.context.send_activity(self.api_hit(str(step_context.result)))
reply = MessageFactory.text("are there any other questions I should answer?")
reply.suggested_actions = SuggestedActions(
actions=[
CardAction(
title="Yes",
type=ActionTypes.im_back,
value='yes'
),
CardAction(
title="No",
type=ActionTypes.im_back,
value='no'
)
]
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=reply)
)
async def end_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
Complete the interaction and end the dialog.
:param step_context:
:return DialogTurnResult:
"""
if str(step_context.result).lower() == 'yes':
return await step_context.replace_dialog(self.id)
await step_context.context.send_activity("hope I was able to answer all your questions")
return await step_context.end_dialog()
def is_ambiguous(self, timex: str) -> bool:
timex_property = Timex(timex)
return "definite" not in timex_property.types
def api_hit(self, question):
import requests
url = "https://ilens-assistant-qna.azurewebsites.net/qnamaker/knowledgebases/0697399a-4050-4f19-80ce-4ad8dae41b6a/generateAnswer"
payload = "{\"question\":\"" + question + "\"}"
print(payload)
headers = {
'Authorization': 'EndpointKey 031de099-2a8b-4b27-af84-2a5e15b35413',
'Content-Type': 'application/json',
'Cookie': 'ARRAffinity=05b4cef5a3f30849a8768536ff665c720ef1b15f35ff9c5d7fa3f54b9d6f9375; ARRAffinitySameSite=05b4cef5a3f30849a8768536ff665c720ef1b15f35ff9c5d7fa3f54b9d6f9375'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
my_ans = response.json()
print(my_ans["answers"][0]["answer"])
return str(my_ans["answers"][0]["answer"])
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs import (
ComponentDialog,
WaterfallDialog,
WaterfallStepContext,
DialogTurnResult,
)
from botbuilder.dialogs.prompts import TextPrompt, PromptOptions
from botbuilder.core import MessageFactory, TurnContext
from botbuilder.schema import InputHints
from booking_details import BookingDetails
from flight_booking_recognizer import FlightBookingRecognizer
from helpers.luis_helper import LuisHelper, Intent
from .safetychecklist import safetychecklist
from .faq import faq
from botbuilder.schema import ChannelAccount, CardAction, ActionTypes, SuggestedActions
from botbuilder.dialogs.prompts import ConfirmPrompt, ChoicePrompt, PromptOptions
from botbuilder.dialogs.choices import Choice
class MainDialog(ComponentDialog):
def __init__(
self, luis_recognizer: FlightBookingRecognizer, safetychecklist: safetychecklist, faq: faq
):
super(MainDialog, self).__init__(MainDialog.__name__)
self._luis_recognizer = luis_recognizer
self.safetychecklist_id = safetychecklist.id
self.faq_id = faq.id
self.add_dialog(TextPrompt(TextPrompt.__name__))
self.add_dialog(safetychecklist)
self.add_dialog(faq)
self.add_dialog(
WaterfallDialog(
"WFDialog", [self.intro_step, self.act_step, self.final_step]
)
)
self.initial_dialog_id = "WFDialog"
async def intro_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
if not self._luis_recognizer.is_configured:
await step_context.context.send_activity(
MessageFactory.text(
"NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and "
"'LuisAPIHostName' to the appsettings.json file.",
input_hint=InputHints.ignoring_input,
)
)
return await step_context.next(None)
reply = MessageFactory.text("Hi Welcome to iLens Assistant!! please select any option to proceed forward")
reply.suggested_actions = SuggestedActions(
actions=[
CardAction(
title="Task Details",
type=ActionTypes.im_back,
value="Task Details"
),
CardAction(
title="FAQ's",
type=ActionTypes.im_back,
value="FAQ's"
)
]
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=reply)
)
async def act_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
if not self._luis_recognizer.is_configured:
await step_context.context.send_activity("luis is not there")
# LUIS is not configured, we just run the BookingDialog path with an empty BookingDetailsInstance.
return await step_context.begin_dialog(
self._booking_dialog_id, BookingDetails()
)
# Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
intent, luis_result = await LuisHelper.execute_luis_query(
self._luis_recognizer, step_context.context
)
print(intent)
if intent == Intent.task.value:
return await step_context.begin_dialog(self.safetychecklist_id, luis_result)
elif intent == Intent.qna.value:
return await step_context.begin_dialog(self.faq_id, luis_result)
else:
didnt_understand_text = (
"Sorry, I didn't get that. Please try asking in a different way"
)
didnt_understand_message = MessageFactory.text(
didnt_understand_text, didnt_understand_text, InputHints.ignoring_input
)
await step_context.context.send_activity(didnt_understand_message)
return await step_context.next(None)
async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
# If the child dialog ("BookingDialog") was cancelled or the user failed to confirm,
# the Result here will be null.
prompt_message = "What else can I do for you?"
return await step_context.replace_dialog(self.id, prompt_message)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from datatypes_date_time.timex import Timex
from botbuilder.dialogs import WaterfallDialog, WaterfallStepContext, DialogTurnResult
from botbuilder.dialogs.prompts import ConfirmPrompt, TextPrompt, PromptOptions
from botbuilder.core import MessageFactory
from botbuilder.schema import InputHints
from .cancel_and_help_dialog import CancelAndHelpDialog
import os
import json
from botbuilder.schema import Attachment, ChannelAccount
from botbuilder.schema import ChannelAccount, CardAction, ActionTypes, SuggestedActions
from botbuilder.dialogs.prompts import ConfirmPrompt, ChoicePrompt, PromptOptions
from botbuilder.dialogs.choices import Choice
class safetychecklist(CancelAndHelpDialog):
def __init__(self, dialog_id: str = None):
super(safetychecklist, self).__init__(dialog_id or safetychecklist.__name__)
self.add_dialog(TextPrompt(TextPrompt.__name__))
self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
self.add_dialog(ChoicePrompt(ChoicePrompt.__name__))
self.yes_no = [
"Yes",
"No"
]
self.DONE_OPTION = "done"
# self.add_dialog(
# WaterfallDialog(
# WaterfallDialog.__name__,
# [
# self.final_step, self.second_step, self.third_step, self.fourth_step, self.fifth_step, self.end_step
# ],
# )
# )
self.add_dialog(
WaterfallDialog(
WaterfallDialog.__name__,
[
self.create_method("first"),self.create_method("second")
],
)
)
self.initial_dialog_id = WaterfallDialog.__name__
def create_method(self, type_):
if type_ == 'first':
async def foo(step_context: WaterfallStepContext) -> DialogTurnResult:
message_text = "hi"
prompt_message = MessageFactory.text(
message_text, message_text, InputHints.expecting_input
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=prompt_message)
)
else:
async def foo(step_context: WaterfallStepContext) -> DialogTurnResult:
message_text = step_context.result
prompt_message = MessageFactory.text(
message_text, message_text, InputHints.expecting_input
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=prompt_message)
)
return foo
# async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
# """
# Complete the interaction and end the dialog.
# :param step_context:
# :return DialogTurnResult:
# """
# task_card = self.create_adaptive_card_attachment()
# response = MessageFactory.attachment(task_card)
# await step_context.context.send_activity(response)
# await step_context.context.send_activity("Now starting STEP 1 of 2 Safety checklist")
# options = self.yes_no.copy()
# # return await step_context.prompt(ChoicePrompt.__name__)
# prompt_options = PromptOptions(
# prompt=MessageFactory.text("Are you wearing safety helmet?"),
# retry_prompt=MessageFactory.text("Please choose an option from the list."),
# choices=self._to_choices(options),
# )
# return await step_context.prompt(ChoicePrompt.__name__, prompt_options)
# # reply = MessageFactory.text("Are you wearing safety helmet?")
# #
# # reply.suggested_actions = SuggestedActions(
# # actions=[
# # CardAction(
# # title="Yes",
# # type=ActionTypes.im_back,
# # value='yes'
# # ),
# # CardAction(
# # title="No",
# # type=ActionTypes.im_back,
# # value='no'
# # )
# # ]
# # )
# # return await step_context.prompt(
# # TextPrompt.__name__, PromptOptions(prompt=reply)
# # )
#
# async def second_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
# """
# Complete the interaction and end the dialog.
# :param step_context:
# :return DialogTurnResult:
# """
# print(step_context.result)
# reply = MessageFactory.text("Are you wearing safety goggles?")
# reply.suggested_actions = SuggestedActions(
# actions=[
# CardAction(
# title="Yes",
# type=ActionTypes.im_back,
# value='yes'
# ),
# CardAction(
# title="No",
# type=ActionTypes.im_back,
# value='no'
# )
# ]
# )
# return await step_context.prompt(
# TextPrompt.__name__, PromptOptions(prompt=reply)
# )
#
# async def third_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
# """
# Complete the interaction and end the dialog.
# :param step_context:
# :return DialogTurnResult:
# """
# await step_context.context.send_activity("Now starting STEP 2 of 2 Visual Inspection")
# reply = MessageFactory.text("Observations*")
#
# reply.suggested_actions = SuggestedActions(
# actions=[
# CardAction(
# title="Dicoloration",
# type=ActionTypes.im_back,
# value='Dicoloration'
# ),
# CardAction(
# title="change in sound",
# type=ActionTypes.im_back,
# value='change in sound'
# ),
# CardAction(
# title="Visible leak",
# type=ActionTypes.im_back,
# value='Visible leak'
# )
# ]
# )
# return await step_context.prompt(
# TextPrompt.__name__, PromptOptions(prompt=reply)
# )
#
# async def fourth_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
# """
# Complete the interaction and end the dialog.
# :param step_context:
# :return DialogTurnResult:
# """
# reply = MessageFactory.text("Bushing Conditions*")
#
# reply.suggested_actions = SuggestedActions(
# actions=[
# CardAction(
# title="Good",
# type=ActionTypes.im_back,
# value='good'
# ),
# CardAction(
# title="Fair",
# type=ActionTypes.im_back,
# value='fair'
# ),
# CardAction(
# title="Poor",
# type=ActionTypes.im_back,
# value='poor'
# )
# ]
# )
# return await step_context.prompt(
# TextPrompt.__name__, PromptOptions(prompt=reply)
# )
#
# async def fifth_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
# """
# Complete the interaction and end the dialog.
# :param step_context:
# :return DialogTurnResult:
# """
# reply = MessageFactory.text("Mechanical Seal for Leakage *")
#
# reply.suggested_actions = SuggestedActions(
# actions=[
# CardAction(
# title="Safe",
# type=ActionTypes.im_back,
# value='safe'
# ),
# CardAction(
# title="At risk",
# type=ActionTypes.im_back,
# value='risk'
# ),
# CardAction(
# title="Not applicable",
# type=ActionTypes.im_back,
# value='not applicable'
# )
# ]
# )
# return await step_context.prompt(
# TextPrompt.__name__, PromptOptions(prompt=reply)
# )
#
# async def end_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
# await step_context.context.send_activity("Thank you for completing your tasks")
# return await step_context.end_dialog()
#
# def is_ambiguous(self, timex: str) -> bool:
# timex_property = Timex(timex)
# return "definite" not in timex_property.types
#
# def create_adaptive_card_attachment(self):
# relative_path = os.path.abspath(os.path.dirname(__file__))
# path = os.path.join(relative_path, "../cards/task.json")
# with open(path) as in_file:
# card = json.load(in_file)
#
# return Attachment(
# content_type="application/vnd.microsoft.card.adaptive", content=card
# )
#
# def _to_choices(self, choices: [str]) -> List[Choice]:
# choice_list: List[Choice] = []
# for choice in choices:
# choice_list.append(Choice(value=choice))
# return choice_list
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.ai.luis import LuisApplication, LuisRecognizer
from botbuilder.core import Recognizer, RecognizerResult, TurnContext
from config import DefaultConfig
class FlightBookingRecognizer(Recognizer):
def __init__(self, configuration: DefaultConfig):
self._recognizer = None
luis_is_configured = (
configuration.LUIS_APP_ID
and configuration.LUIS_API_KEY
and configuration.LUIS_API_HOST_NAME
)
if luis_is_configured:
# Set the recognizer options depending on which endpoint version you want to use e.g v2 or v3.
# More details can be found in https://docs.microsoft.com/azure/cognitive-services/luis/luis-migration-api-v3
luis_application = LuisApplication(
configuration.LUIS_APP_ID,
configuration.LUIS_API_KEY,
"https://" + configuration.LUIS_API_HOST_NAME,
)
self._recognizer = LuisRecognizer(luis_application)
@property
def is_configured(self) -> bool:
# Returns true if luis is configured in the config.py and initialized.
return self._recognizer is not None
async def recognize(self, turn_context: TurnContext) -> RecognizerResult:
return await self._recognizer.recognize(turn_context)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from . import activity_helper, luis_helper, dialog_helper
__all__ = ["activity_helper", "dialog_helper", "luis_helper"]
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from datetime import datetime
from botbuilder.schema import (
Activity,
ActivityTypes,
ChannelAccount,
ConversationAccount,
)
def create_activity_reply(activity: Activity, text: str = None, locale: str = None):
return Activity(
type=ActivityTypes.message,
timestamp=datetime.utcnow(),
from_property=ChannelAccount(
id=getattr(activity.recipient, "id", None),
name=getattr(activity.recipient, "name", None),
),
recipient=ChannelAccount(
id=activity.from_property.id, name=activity.from_property.name
),
reply_to_id=activity.id,
service_url=activity.service_url,
channel_id=activity.channel_id,
conversation=ConversationAccount(
is_group=activity.conversation.is_group,
id=activity.conversation.id,
name=activity.conversation.name,
),
text=text or "",
locale=locale or "",
attachments=[],
entities=[],
)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import StatePropertyAccessor, TurnContext
from botbuilder.dialogs import Dialog, DialogSet, DialogTurnStatus
class DialogHelper:
@staticmethod
async def run_dialog(
dialog: Dialog, turn_context: TurnContext, accessor: StatePropertyAccessor
):
dialog_set = DialogSet(accessor)
dialog_set.add(dialog)
dialog_context = await dialog_set.create_context(turn_context)
results = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
await dialog_context.begin_dialog(dialog.id)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from enum import Enum
from typing import Dict
from botbuilder.ai.luis import LuisRecognizer
from botbuilder.core import IntentScore, TopIntent, TurnContext
from booking_details import BookingDetails
class Intent(Enum):
NONE_INTENT = "None"
safety = "safety"
qna = "qna"
task = "task"
def top_intent(intents: Dict[Intent, dict]) -> TopIntent:
max_intent = Intent.NONE_INTENT
max_value = 0.0
for intent, value in intents:
intent_score = IntentScore(value)
if intent_score.score > max_value:
max_intent, max_value = intent, intent_score.score
return TopIntent(max_intent, max_value)
class LuisHelper:
@staticmethod
async def execute_luis_query(
luis_recognizer: LuisRecognizer, turn_context: TurnContext
) -> (Intent, object):
"""
Returns an object with preformatted LUIS results for the bot's dialogs to consume.
"""
result = None
intent = None
try:
recognizer_result = await luis_recognizer.recognize(turn_context)
intent = (
sorted(
recognizer_result.intents,
key=recognizer_result.intents.get,
reverse=True,
)[:1][0]
if recognizer_result.intents
else None
)
except Exception as exception:
print(exception)
return intent, result
botbuilder-integration-aiohttp>=4.13.0
botbuilder-dialogs>=4.13.0
botbuilder-ai>=4.13.0
datatypes-date-time>=1.0.0.a2
########### Python 3.6 #############
#
# This quickstart shows how to add utterances to a LUIS model using the REST APIs.
#
import requests
try:
##########
# Values to modify.
# YOUR-APP-ID: The App ID GUID found on the www.luis.ai Application Settings page.
appId = "45646243-2016-4f0a-9145-e93a7f58e355"
# YOUR-AUTHORING-KEY: Your LUIS authoring key, 32 character value.
authoring_key = "f19be164fbfc49a3972f940835820d7e"
# YOUR-AUTHORING-ENDPOINT: Replace this with your authoring key endpoint.
# For example, "https://your-resource-name.cognitiveservices.azure.com/"
authoring_endpoint = "https://westus.api.cognitive.microsoft.com"
# The version number of your LUIS app
app_version = "0.1"
##########
# The headers to use in this REST call.
headers = {'Ocp-Apim-Subscription-Key': authoring_key}
# The URL parameters to use in this REST call.
params ={
#'timezoneOffset': '0',
#'verbose': 'true',
#'show-all-intents': 'true',
#'spellCheck': 'false',
#'staging': 'false'
}
# List of example utterances to send to the LUIS app.
data = """[
{
'text': 'give me the list of my task details',
'intentName': 'task'
}
]
"""
# Make the REST call to POST the list of example utterances.
response = requests.post(f'{authoring_endpoint}luis/authoring/v3.0-preview/apps/{appId}/versions/{app_version}/examples',
headers=headers, params=params, data=data)
# Display the results on the console.
print('Add the list of utterances:')
print(response.json())
# Make the REST call to initiate a training session.
response = requests.post(f'{authoring_endpoint}luis/authoring/v3.0-preview/apps/{appId}/versions/{app_version}/train',
headers=headers, params=params, data=None)
# Display the results on the console.
print('Request training:')
print(response.json())
# Make the REST call to request the status of training.
response = requests.get(f'{authoring_endpoint}luis/authoring/v3.0-preview/apps/{appId}/versions/{app_version}/train',
headers=headers, params=params, data=None)
# Display the results on the console.
print('Request training status:')
print(response.json())
except Exception as e:
# Display the error string.
print(f'{e}')
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment