diff --git a/libraries/bot-ai-qna/src/main/java/com/microsoft/bot/ai/qna/dialogs/QnAMakerDialog.java b/libraries/bot-ai-qna/src/main/java/com/microsoft/bot/ai/qna/dialogs/QnAMakerDialog.java index 6459b2d7..959a39ef 100644 --- a/libraries/bot-ai-qna/src/main/java/com/microsoft/bot/ai/qna/dialogs/QnAMakerDialog.java +++ b/libraries/bot-ai-qna/src/main/java/com/microsoft/bot/ai/qna/dialogs/QnAMakerDialog.java @@ -9,6 +9,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.HashMap; import java.util.concurrent.CompletableFuture; import javax.annotation.Nullable; @@ -438,6 +439,19 @@ public class QnAMakerDialog extends WaterfallDialog { this.rankerType = withRankerType; } + /** + * Initializes a new instance of the @{link QnAMakerDialog} class. + */ + public QnAMakerDialog() { + super("QnAMakerDialog", null); + + // add waterfall steps + this.addStep(this::callGenerateAnswer); + this.addStep(this::callTrain); + this.addStep(this::checkForMultiTurnPrompt); + this.addStep(this::displayQnAResult); + } + /** * Initializes a new instance of the @{link QnAMakerDialog} class. * @@ -570,7 +584,7 @@ public class QnAMakerDialog extends WaterfallDialog { @Nullable OkHttpClient withHttpClient ) { this( - QnAMakerDialog.class.getName(), + "QnAMakerDialog", withKnowledgeBaseId, withEndpointKey, withHostName, @@ -613,15 +627,12 @@ public class QnAMakerDialog extends WaterfallDialog { QnAMakerOptions qnAMakerOptions = this.getQnAMakerOptions(dc).join(); QnADialogResponseOptions qnADialogResponseOptions = this.getQnAResponseOptions(dc).join(); - QnAMakerDialogOptions dialogOptions = new QnAMakerDialogOptions() { - { - setQnAMakerOptions(qnAMakerOptions); - setResponseOptions(qnADialogResponseOptions); - } - }; + QnAMakerDialogOptions dialogOptions = new QnAMakerDialogOptions(); + dialogOptions.setQnAMakerOptions(qnAMakerOptions); + dialogOptions.setResponseOptions(qnADialogResponseOptions); if (options != null) { - dialogOptions = (QnAMakerDialogOptions) ObjectPath.assign(dialogOptions, options); + dialogOptions = ObjectPath.assign(dialogOptions, options); } ObjectPath.setPathValue(dc.getActiveDialog().getState(), OPTIONS, dialogOptions); @@ -706,13 +717,10 @@ public class QnAMakerDialog extends WaterfallDialog { return CompletableFuture.completedFuture(qnaClient); } - QnAMakerEndpoint endpoint = new QnAMakerEndpoint() { - { - setEndpointKey(endpointKey); - setHost(hostName); - setKnowledgeBaseId(knowledgeBaseId); - } - }; + QnAMakerEndpoint endpoint = new QnAMakerEndpoint(); + endpoint.setEndpointKey(endpointKey); + endpoint.setHost(hostName); + endpoint.setKnowledgeBaseId(knowledgeBaseId); return this.getQnAMakerOptions( dc @@ -729,17 +737,15 @@ public class QnAMakerDialog extends WaterfallDialog { * task is successful, the result contains the QnA Maker options to use. */ protected CompletableFuture getQnAMakerOptions(DialogContext dc) { - return CompletableFuture.completedFuture(new QnAMakerOptions() { - { - setScoreThreshold(threshold); - setStrictFilters(strictFilters); - setTop(top); - setContext(new QnARequestContext()); - setQnAId(0); - setRankerType(rankerType); - setIsTest(isTest); - } - }); + QnAMakerOptions options = new QnAMakerOptions(); + options.setScoreThreshold(threshold); + options.setStrictFilters(strictFilters); + options.setTop(top); + options.setContext(new QnARequestContext()); + options.setQnAId(0); + options.setRankerType(rankerType); + options.setIsTest(isTest); + return CompletableFuture.completedFuture(options); } /** @@ -750,16 +756,15 @@ public class QnAMakerDialog extends WaterfallDialog { * successful, the result contains the response options to use. */ protected CompletableFuture getQnAResponseOptions(DialogContext dc) { - return CompletableFuture.completedFuture(new QnADialogResponseOptions() { - { - setNoAnswer(noAnswer.bind(dc, dc.getState()).join()); - setActiveLearningCardTitle( - activeLearningCardTitle != null ? activeLearningCardTitle : DEFAULT_CARD_TITLE - ); - setCardNoMatchText(cardNoMatchText != null ? cardNoMatchText : DEFAULT_CARD_NO_MATCH_TEXT); - setCardNoMatchResponse(cardNoMatchResponse.bind(dc, null).join()); - } - }); + QnADialogResponseOptions options = new QnADialogResponseOptions(); + options.setNoAnswer(noAnswer.bind(dc, dc.getState()).join()); + options.setActiveLearningCardTitle( + activeLearningCardTitle != null ? activeLearningCardTitle : DEFAULT_CARD_TITLE + ); + options.setCardNoMatchText(cardNoMatchText != null ? cardNoMatchText : DEFAULT_CARD_NO_MATCH_TEXT); + options.setCardNoMatchResponse(cardNoMatchResponse.bind(dc, null).join()); + + return CompletableFuture.completedFuture(options); } /** @@ -816,16 +821,18 @@ public class QnAMakerDialog extends WaterfallDialog { // -Check if previous context is present, if yes then put it with the query // -Check for id if query is present in reverse index. Map previousContextData = - ObjectPath.getPathValue(dc.getActiveDialog().getState(), QNA_CONTEXT_DATA, Map.class); + ObjectPath.getPathValue( + dc.getActiveDialog().getState(), + QNA_CONTEXT_DATA, + Map.class, + new HashMap()); Integer previousQnAId = ObjectPath.getPathValue(dc.getActiveDialog().getState(), PREVIOUS_QNA_ID, Integer.class, 0); if (previousQnAId > 0) { - dialogOptions.getQnAMakerOptions().setContext(new QnARequestContext() { - { - setPreviousQnAId(previousQnAId); - } - }); + QnARequestContext context = new QnARequestContext(); + context.setPreviousQnAId(previousQnAId); + dialogOptions.getQnAMakerOptions().setContext(context); Integer currentQnAId = previousContextData.get(dc.getContext().getActivity().getText()); if (currentQnAId != null) { @@ -921,19 +928,13 @@ public class QnAMakerDialog extends WaterfallDialog { if (qnaResult != null) { List queryResultArr = new ArrayList(); stepContext.getValues().put(ValueProperty.QNA_DATA, queryResultArr.add(qnaResult)); - FeedbackRecord record = new FeedbackRecord() { - { - setUserId(stepContext.getContext().getActivity().getId()); - setUserQuestion(currentQuery); - setQnaId(qnaResult.getId()); - } - }; + FeedbackRecord record = new FeedbackRecord(); + record.setUserId(stepContext.getContext().getActivity().getId()); + record.setUserQuestion(currentQuery); + record.setQnaId(qnaResult.getId()); FeedbackRecord[] records = {record}; - FeedbackRecords feedbackRecords = new FeedbackRecords() { - { - setRecords(records); - } - }; + FeedbackRecords feedbackRecords = new FeedbackRecords(); + feedbackRecords.setRecords(records); // Call Active Learning Train API return this.getQnAMakerClient(stepContext).thenCompose(qnaClient -> { try { diff --git a/samples/49.qnamaker-all-features/LICENSE b/samples/49.qnamaker-all-features/LICENSE new file mode 100644 index 00000000..21071075 --- /dev/null +++ b/samples/49.qnamaker-all-features/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/samples/49.qnamaker-all-features/README.md b/samples/49.qnamaker-all-features/README.md new file mode 100644 index 00000000..46331b35 --- /dev/null +++ b/samples/49.qnamaker-all-features/README.md @@ -0,0 +1,126 @@ +๏ปฟ# QnA Maker + +Bot Framework v4 QnA Maker bot sample. This sample shows how to integrate Multiturn and Active learning in a QnA Maker bot with Java. Click [here][72] to know more about using follow-up prompts to create multiturn conversation. To know more about how to enable and use active learning, click [here][71]. + +This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a bot that uses the [QnA Maker Cognitive AI](https://www.qnamaker.ai) service. + +The [QnA Maker Service](https://www.qnamaker.ai) enables you to build, train and publish a simple question and answer bot based on FAQ URLs, structured documents or editorial content in minutes. In this sample, we demonstrate how to use the QnA Maker service to answer questions based on a FAQ text file used as input. + +## Concepts introduced in this sample +The [QnA Maker Service][7] enables you to build, train and publish a simple question and answer bot based on FAQ URLs, structured documents or editorial content in minutes. +In this sample, we demonstrate +- how to use the Active Learning to generate suggestions for knowledge base. +- how to use the Multiturn experience for the knowledge base. + +# Prerequisites +- Follow instructions [here](https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/set-up-qnamaker-service-azure) to create a QnA Maker service. +- Follow instructions [here](https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/multiturn-conversation) to create multiturn experience. +- Follow instructions [here](https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/quickstarts/create-publish-knowledge-base) to import and publish your newly created QnA Maker service. +- Update [application.properties](src/main/resources/application.properties) with your kbid (KnowledgeBase Id), endpointKey and endpointHost. You may also change the default answer by updating `DefaultAnswer` (optional) field. QnA knowledge base setup and application configuration steps can be found [here](https://aka.ms/qna-instructions). +- (Optional) Follow instructions [here](https://github.com/microsoft/botframework-cli/tree/main/packages/qnamaker) to set up the + QnA Maker CLI to deploy the model. + + +### Create a QnAMaker Application to enable QnA Knowledge Bases + +QnA knowledge base setup and application configuration steps can be found [here](https://aka.ms/qna-instructions). + +# Configure Cognitive Service Model +- Create a Knowledge Base in QnAMaker Portal. +- Import "smartLightFAQ.tsv" file, in QnAMaker Portal. +- Save and Train the model. +- Create Bot from Publish page. +- Test bot with Web Chat. +- Capture values of settings like "QnAAuthKey" from "Configuration" page of created bot, in Azure Portal. +- Updated application.properties with values as needed. +- Use value of "QnAAuthKey" for setting "QnAEndpointKey". +- Capture KnowledgeBase Id, HostName and EndpointKey current published app + +# Try Active Learning +- Once your QnA Maker service is up and you have published the sample KB, try the following queries to trigger the Train API on the bot. +- Sample query: "light" +- You can observe that, Multiple answers are returned with high score. + +# Try Multi-turn prompt +- Once your QnA Maker service is up and you have published the sample KB, try the following queries to trigger the Train API on the bot. +- Sample query: "won't turn on" +- You can notice a prompt, included as part of answer to query. + +## To try this sample + +- From the root of this project folder: + - Build the sample using `mvn package` + - Run it by using `java -jar .\target\bot-qnamaker-all-features-sample.jar` + +##### Microsoft Teams channel group chat fix +- Goto `QnABot.java` +- Add References +- Modify `onTurn` function as: + ```java + @Override + public CompletableFuture onTurn(TurnContext turnContext) { + // Teams group chat + if (turnContext.getActivity().getChannelId().equals(Channels.MSTEAMS)) { + turnContext.getActivity().setText(turnContext.getActivity().removeRecipientMention()); + } + + return super.onTurn(turnContext) + // Save any state changes that might have occurred during the turn. + .thenCompose(turnResult -> conversationState.saveChanges(turnContext, false)) + .thenCompose(saveResult -> userState.saveChanges(turnContext, false)); + } + ``` + +## 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 Bot Framework Emulator version 4.3.0 or greater 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 +See [Deploy your Java bot to Azure][50] for instructions. + +The deployment process assumes you have an account on Microsoft Azure and are able to log into the [Microsoft Azure Portal][60]. + +If you are new to Microsoft Azure, please refer to [Getting started with Azure][70] for guidance on how to get started on Azure. + +# Further reading +- [Active learning Documentation][40] +- [Bot Framework Documentation][80] +- [Bot Basics][90] +- [Azure Bot Service Introduction][100] +- [Azure Bot Service Documentation][110] +- [QnA Maker CLI][170] +- [BF-CLI][130] +- [Azure Portal][140] +- [Spring Boot][160] + +[1]: https://dev.botframework.com +[4]: https://docs.microsoft.com/en-us/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0 +[5]: https://github.com/microsoft/botframework-emulator +[6]: https://aka.ms/botframeworkemulator +[7]: https://www.qnamaker.ai + +[40]: https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/improve-knowledge-base +[50]: https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0 +[60]: https://portal.azure.com +[70]: https://azure.microsoft.com/get-started/ +[80]: https://docs.botframework.com +[90]: https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0 +[100]: https://docs.microsoft.com/en-us/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0 +[110]: https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0 +[120]: https://docs.microsoft.com/en-us/cli/azure/?view=azure-cli-latest +[130]: https://github.com/microsoft/botframework-cli +[140]: https://portal.azure.com +[150]: https://www.luis.ai +[160]: https://spring.io/projects/spring-boot +[170]: https://github.com/microsoft/botframework-cli/tree/main/packages/qnamaker + +[71]: https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/improve-knowledge-base +[72]: https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/multiturn-conversation diff --git a/samples/49.qnamaker-all-features/deploymentTemplates/template-with-new-rg.json b/samples/49.qnamaker-all-features/deploymentTemplates/template-with-new-rg.json new file mode 100644 index 00000000..ec2460d3 --- /dev/null +++ b/samples/49.qnamaker-all-features/deploymentTemplates/template-with-new-rg.json @@ -0,0 +1,291 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupLocation": { + "defaultValue": "", + "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": { + "defaultValue": "S1", + "type": "string", + "metadata": { + "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1." + } + }, + "newAppServicePlanName": { + "defaultValue": "", + "type": "string", + "metadata": { + "description": "The name of the App Service Plan." + } + }, + "newAppServicePlanSku": { + "type": "object", + "defaultValue": { + "name": "P1v2", + "tier": "PremiumV2", + "size": "P1v2", + "family": "Pv2", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "newAppServicePlanLocation": { + "defaultValue": "", + "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": { + "perSiteScaling": false, + "maximumElasticWorkerCount": 1, + "isSpot": false, + "reserved": true, + "isXenon": false, + "hyperV": false, + "targetWorkerCount": 0, + "targetWorkerSizeId": 0 + } + }, + { + "comments": "Create a Web App using a Linux App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2018-11-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')]", + "reserved": true, + "isXenon": false, + "hyperV": false, + "scmSiteAlsoStopped": false, + "clientAffinityEnabled": true, + "clientCertEnabled": false, + "hostNamesDisabled": false, + "containerSize": 0, + "dailyMemoryTimeQuota": 0, + "httpsOnly": false, + "redundancyMode": "None", + "siteConfig": { + "appSettings": [ + { + "name": "JAVA_OPTS", + "value": "-Dserver.port=80" + }, + { + "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": "2018-11-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", + "linuxFxVersion": "JAVA|8-jre8", + "requestTracingEnabled": false, + "remoteDebuggingEnabled": false, + "httpLoggingEnabled": false, + "logsDirectorySizeLimit": 35, + "detailedErrorLoggingEnabled": false, + "publishingUsername": "[variables('publishingUsername')]", + "scmType": "None", + "use32BitWorkerProcess": true, + "webSocketsEnabled": false, + "alwaysOn": true, + "managedPipelineMode": "Integrated", + "virtualApplications": [ + { + "virtualPath": "/", + "physicalPath": "site\\wwwroot", + "preloadEnabled": true + } + ], + "loadBalancing": "LeastRequests", + "experiments": { + "rampUpRules": [] + }, + "autoHealEnabled": false, + "localMySqlEnabled": false, + "ipSecurityRestrictions": [ + { + "ipAddress": "Any", + "action": "Allow", + "priority": 1, + "name": "Allow all", + "description": "Allow all access" + } + ], + "scmIpSecurityRestrictions": [ + { + "ipAddress": "Any", + "action": "Allow", + "priority": 1, + "name": "Allow all", + "description": "Allow all access" + } + ], + "scmIpSecurityRestrictionsUseMain": false, + "http20Enabled": false, + "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": {} + } + } + } + ] +} diff --git a/samples/49.qnamaker-all-features/deploymentTemplates/template-with-preexisting-rg.json b/samples/49.qnamaker-all-features/deploymentTemplates/template-with-preexisting-rg.json new file mode 100644 index 00000000..024dcf08 --- /dev/null +++ b/samples/49.qnamaker-all-features/deploymentTemplates/template-with-preexisting-rg.json @@ -0,0 +1,259 @@ +{ + "$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. Defaults to \"\"." + } + }, + "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": "S1", + "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": "P1v2", + "tier": "PremiumV2", + "size": "P1v2", + "family": "Pv2", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "appServicePlanLocation": { + "type": "string", + "defaultValue": "", + "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", + "condition": "[not(variables('useExistingAppServicePlan'))]", + "name": "[variables('servicePlanName')]", + "apiVersion": "2018-02-01", + "location": "[variables('resourcesLocation')]", + "sku": "[parameters('newAppServicePlanSku')]", + "kind": "linux", + "properties": { + "perSiteScaling": false, + "maximumElasticWorkerCount": 1, + "isSpot": false, + "reserved": true, + "isXenon": false, + "hyperV": false, + "targetWorkerCount": 0, + "targetWorkerSizeId": 0 + } + }, + { + "comments": "Create a Web App using a Linux App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2018-11-01", + "location": "[variables('resourcesLocation')]", + "kind": "app,linux", + "dependsOn": [ + "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]" + ], + "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": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]", + "reserved": true, + "isXenon": false, + "hyperV": false, + "scmSiteAlsoStopped": false, + "clientAffinityEnabled": true, + "clientCertEnabled": false, + "hostNamesDisabled": false, + "containerSize": 0, + "dailyMemoryTimeQuota": 0, + "httpsOnly": false, + "redundancyMode": "None", + "siteConfig": { + "appSettings": [ + { + "name": "JAVA_OPTS", + "value": "-Dserver.port=80" + }, + { + "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": "2018-11-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", + "linuxFxVersion": "JAVA|8-jre8", + "requestTracingEnabled": false, + "remoteDebuggingEnabled": false, + "httpLoggingEnabled": false, + "logsDirectorySizeLimit": 35, + "detailedErrorLoggingEnabled": false, + "publishingUsername": "[variables('publishingUsername')]", + "scmType": "None", + "use32BitWorkerProcess": true, + "webSocketsEnabled": false, + "alwaysOn": true, + "managedPipelineMode": "Integrated", + "virtualApplications": [ + { + "virtualPath": "/", + "physicalPath": "site\\wwwroot", + "preloadEnabled": true + } + ], + "loadBalancing": "LeastRequests", + "experiments": { + "rampUpRules": [] + }, + "autoHealEnabled": false, + "localMySqlEnabled": false, + "ipSecurityRestrictions": [ + { + "ipAddress": "Any", + "action": "Allow", + "priority": 1, + "name": "Allow all", + "description": "Allow all access" + } + ], + "scmIpSecurityRestrictions": [ + { + "ipAddress": "Any", + "action": "Allow", + "priority": 1, + "name": "Allow all", + "description": "Allow all access" + } + ], + "scmIpSecurityRestrictionsUseMain": false, + "http20Enabled": false, + "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'))]" + ] + } + ] +} diff --git a/samples/49.qnamaker-all-features/pom.xml b/samples/49.qnamaker-all-features/pom.xml new file mode 100644 index 00000000..d0045273 --- /dev/null +++ b/samples/49.qnamaker-all-features/pom.xml @@ -0,0 +1,244 @@ + + + + 4.0.0 + + com.microsoft.bot.sample + bot-qnamaker-all-features + sample + jar + + ${project.groupId}:${project.artifactId} + This package contains a Java QnAMaker Bot sample using Spring Boot. + http://maven.apache.org + + + org.springframework.boot + spring-boot-starter-parent + 2.4.0 + + + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + + + + + + Bot Framework Development + + Microsoft + https://dev.botframework.com/ + + + + + 1.8 + 1.8 + 1.8 + com.microsoft.bot.sample.qnamaker.all.features.Application + + + + + org.springframework.boot + spring-boot-starter-test + 2.4.0 + test + + + junit + junit + 4.13.1 + test + + + org.junit.vintage + junit-vintage-engine + test + + + + com.microsoft.bot + bot-ai-qna + 4.6.0-preview9 + + + + org.slf4j + slf4j-api + + + org.apache.logging.log4j + log4j-api + 2.11.0 + + + org.apache.logging.log4j + log4j-core + 2.13.2 + + + + com.microsoft.bot + bot-integration-spring + 4.6.0-preview9 + compile + + + + + + build + + true + + + + + src/main/resources + false + + + + + maven-compiler-plugin + 3.8.1 + + + maven-war-plugin + 3.2.3 + + src/main/webapp + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.microsoft.bot.sample.qnamaker.all.features.Application + + + + + + com.microsoft.azure + azure-webapp-maven-plugin + 1.12.0 + + V2 + ${groupname} + ${botname} + + + JAVA_OPTS + -Dserver.port=80 + + + + linux + Java 8 + Java SE + + + + + ${project.basedir}/target + + *.jar + + + + + + + + + + + + publish + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + maven-war-plugin + 3.2.3 + + src/main/webapp + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + true + ossrh + https://oss.sonatype.org/ + true + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + 8 + false + + + + attach-javadocs + + jar + + + + + + + + + diff --git a/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/Application.java b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/Application.java new file mode 100644 index 00000000..10e036ab --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/Application.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.qnamaker.all.features; + +import com.microsoft.bot.builder.Bot; +import com.microsoft.bot.builder.ConversationState; +import com.microsoft.bot.builder.UserState; +import com.microsoft.bot.integration.AdapterWithErrorHandler; +import com.microsoft.bot.integration.BotFrameworkHttpAdapter; +import com.microsoft.bot.integration.Configuration; +import com.microsoft.bot.integration.spring.BotController; +import com.microsoft.bot.integration.spring.BotDependencyConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; + +/** + * This is the starting point of the Sprint Boot Bot application. + */ +@SpringBootApplication + +// Use the default BotController to receive incoming Channel messages. A custom +// controller could be used by eliminating this import and creating a new +// org.springframework.web.bind.annotation.RestController. +// The default controller is created by the Spring Boot container using +// dependency injection. The default route is /api/messages. +@Import({BotController.class}) + +/** + * This class extends the BotDependencyConfiguration which provides the default + * implementations for a Bot application. The Application class should + * override methods in order to provide custom implementations. + */ +public class Application extends BotDependencyConfiguration { + + /** + * The start method. + * + * @param args The args. + */ + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + /** + * Returns the Bot for this application. + * + *

+ * The @Component annotation could be used on the Bot class instead of this method + * with the @Bean annotation. + *

+ * + * @return The Bot implementation for this application. + */ + @Bean + public Bot getBot( + Configuration configuration, + UserState userState, + ConversationState conversationState + ) { + BotServices services = new BotServicesImpl(configuration); + RootDialog dialog = new RootDialog(services, configuration); + return new QnABot<>(conversationState, userState, dialog); + } + + /** + * Returns a custom Adapter that provides error handling. + * + * @param configuration The Configuration object to use. + * @return An error handling BotFrameworkHttpAdapter. + */ + @Override + public BotFrameworkHttpAdapter getBotFrameworkHttpAdaptor(Configuration configuration) { + return new AdapterWithErrorHandler(configuration); + } +} diff --git a/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/BotServices.java b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/BotServices.java new file mode 100644 index 00000000..0a907362 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/BotServices.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.qnamaker.all.features; + +import com.microsoft.bot.ai.qna.QnAMaker; + +/** + * Interface which contains the QnAMaker application. + */ +public interface BotServices { + + /** + * Get QnAMaker application. + * + * @return QnAMaker application + */ + QnAMaker getQnAMakerService(); +} diff --git a/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/BotServicesImpl.java b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/BotServicesImpl.java new file mode 100644 index 00000000..6d2d0e33 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/BotServicesImpl.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.qnamaker.all.features; + +import com.microsoft.bot.ai.qna.QnAMaker; +import com.microsoft.bot.ai.qna.QnAMakerEndpoint; +import com.microsoft.bot.integration.Configuration; +import org.apache.commons.lang3.StringUtils; + +/** + * Class which implements the BotService interface to handle + * the services attached to the bot. + */ +public class BotServicesImpl implements BotServices { + + private QnAMaker qnAMakerService; + + /** + * Initializes a new instance of the {@link BotServicesImpl} class. + * + * @param configuration A {@link Configuration} which contains the properties of the application.properties + */ + public BotServicesImpl(Configuration configuration) { + QnAMakerEndpoint qnAMakerEndpoint = new QnAMakerEndpoint(); + qnAMakerEndpoint.setKnowledgeBaseId(configuration.getProperty("QnAKnowledgebaseId")); + qnAMakerEndpoint.setHost(getHostname(configuration.getProperty("QnAEndpointHostName"))); + qnAMakerEndpoint.setEndpointKey(getEndpointKey(configuration)); + QnAMaker qnAMaker = new QnAMaker(qnAMakerEndpoint, null); + this.qnAMakerService = qnAMaker; + } + + /** + * {@inheritDoc} + */ + @Override + public QnAMaker getQnAMakerService() { + return qnAMakerService; + } + + /** + * Get the URL with the hostname value. + * + * @param hostname The hostname value + * @return The URL with the hostname value + */ + private static String getHostname(String hostname) { + if (!hostname.startsWith("https://")) { + hostname = "https://".concat(hostname); + } + + if (!hostname.contains("/v5.0") && !hostname.endsWith("/qnamaker")) { + hostname = hostname.concat("/qnamaker"); + } + + return hostname; + } + + /** + * Get the endpointKey. + * + * @param configuration A {@link Configuration} populated with the application.properties file + * @return The endpointKey + */ + private static String getEndpointKey(Configuration configuration) { + String endpointKey = configuration.getProperty("QnAEndpointKey"); + + if (StringUtils.isBlank(endpointKey)) { + // This features sample is copied as is for "azure bot service" default "createbot" template. + // Post this sample change merged into "azure bot service" template repo, "Azure Bot Service" + // will make the web app config change to use "QnAEndpointKey".But, the the old "QnAAuthkey" + // required for backward compact. This is a requirement from docs to keep app setting name + // consistent with "QnAEndpointKey". This is tracked in Github issue: + // https://github.com/microsoft/BotBuilder-Samples/issues/2532 + + endpointKey = configuration.getProperty("QnAAuthKey"); + } + + return endpointKey; + } +} diff --git a/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/QnABot.java b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/QnABot.java new file mode 100644 index 00000000..3bfed648 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/QnABot.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.qnamaker.all.features; + +import com.microsoft.bot.builder.ActivityHandler; +import com.microsoft.bot.builder.BotState; +import com.microsoft.bot.builder.ConversationState; +import com.microsoft.bot.builder.MessageFactory; +import com.microsoft.bot.builder.TurnContext; +import com.microsoft.bot.builder.UserState; +import com.microsoft.bot.dialogs.Dialog; +import com.microsoft.bot.schema.ChannelAccount; + +import java.util.List; +import java.util.concurrent.CompletableFuture; + +/** + * A simple bot that responds to utterances with answers from QnA Maker. + * If an answer is not found for an utterance, the bot responds with help. + * + * @param A {@link Dialog} + */ +public class QnABot extends ActivityHandler { + + private final BotState conversationState; + private final Dialog dialog; + private final BotState userState; + + /** + * Initializes a new instance of the {@link QnABot} class. + * + * @param withConversationState A {@link ConversationState} + * @param withUserState A {@link UserState} + * @param withDialog A {@link Dialog} + */ + public QnABot(ConversationState withConversationState, UserState withUserState, T withDialog) { + this.conversationState = withConversationState; + this.userState = withUserState; + this.dialog = withDialog; + } + + /** + * {@inheritDoc} + */ + @Override + public CompletableFuture onTurn(TurnContext turnContext) { + return super.onTurn(turnContext) + // Save any state changes that might have occurred during the turn. + .thenCompose(turnResult -> conversationState.saveChanges(turnContext, false)) + .thenCompose(saveResult -> userState.saveChanges(turnContext, false)); + } + + /** + * {@inheritDoc} + */ + @Override + protected CompletableFuture onMessageActivity(TurnContext turnContext) { + // Run the Dialog with the new message Activity. + return Dialog.run( + this.dialog, + turnContext, + this.conversationState.createProperty("DialogState")); + } + + /** + * {@inheritDoc} + */ + @Override + protected CompletableFuture onMembersAdded(List membersAdded, TurnContext turnContext) { + for (ChannelAccount member: membersAdded) { + if (!member.getId().equals(turnContext.getActivity().getRecipient().getId())) { + turnContext.sendActivity(MessageFactory.text("Hello and welcome!")).thenApply(result -> null); + } + } + + return CompletableFuture.completedFuture(null); + } +} diff --git a/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/QnAMakerBaseDialog.java b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/QnAMakerBaseDialog.java new file mode 100644 index 00000000..8f03cab7 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/QnAMakerBaseDialog.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.qnamaker.all.features; + +import com.microsoft.bot.ai.qna.QnADialogResponseOptions; +import com.microsoft.bot.ai.qna.QnAMakerClient; +import com.microsoft.bot.ai.qna.QnAMakerOptions; +import com.microsoft.bot.ai.qna.dialogs.QnAMakerDialog; +import com.microsoft.bot.builder.MessageFactory; +import com.microsoft.bot.dialogs.DialogContext; +import com.microsoft.bot.integration.Configuration; +import com.microsoft.bot.schema.Activity; +import org.apache.commons.lang3.StringUtils; + +import java.util.concurrent.CompletableFuture; + +/** + * QnAMaker action builder class. + */ +public class QnAMakerBaseDialog extends QnAMakerDialog { + + // Dialog Options parameters + private final String defaultCardTitle = "Did you mean:"; + private final String defaultCardNoMatchText = "None of the above."; + private final String defaultCardNoMatchResponse = "Thanks for the feedback."; + + private final BotServices services; + private String defaultAnswer = "No QnAMaker answer found."; + + /** + * Initializes a new instance of the {@link QnAMakerBaseDialog} class. + * Dialog helper to generate dialogs. + * + * @param withServices Bot Services + * @param configuration A {@link Configuration} which contains the properties of the application.properties + */ + public QnAMakerBaseDialog(BotServices withServices, Configuration configuration) { + super(); + this.services = withServices; + if (StringUtils.isNotBlank(configuration.getProperty("DefaultAnswer"))) { + this.defaultAnswer = configuration.getProperty("DefaultAnswer"); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected CompletableFuture getQnAMakerClient(DialogContext dc) { + return CompletableFuture.completedFuture(this.services.getQnAMakerService()); + } + + /** + * {@inheritDoc} + */ + @Override + protected CompletableFuture getQnAMakerOptions(DialogContext dc) { + QnAMakerOptions options = new QnAMakerOptions(); + options.setScoreThreshold(DEFAULT_THRESHOLD); + options.setTop(DEFAULT_TOP_N); + options.setQnAId(0); + options.setRankerType("Default"); + options.setIsTest(false); + return CompletableFuture.completedFuture(options); + } + + /** + * {@inheritDoc} + */ + @Override + protected CompletableFuture getQnAResponseOptions(DialogContext dc) { + Activity defaultAnswerActivity = MessageFactory.text(this.defaultAnswer); + + Activity cardNoMatchResponse = MessageFactory.text(this.defaultCardNoMatchResponse); + + QnADialogResponseOptions responseOptions = new QnADialogResponseOptions(); + responseOptions.setActiveLearningCardTitle(this.defaultCardTitle); + responseOptions.setCardNoMatchText(this.defaultCardNoMatchText); + responseOptions.setNoAnswer(defaultAnswerActivity); + responseOptions.setCardNoMatchResponse(cardNoMatchResponse); + + return CompletableFuture.completedFuture(responseOptions); + } +} diff --git a/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/RootDialog.java b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/RootDialog.java new file mode 100644 index 00000000..d2f7dc85 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/RootDialog.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.qnamaker.all.features; + +import com.microsoft.bot.dialogs.ComponentDialog; +import com.microsoft.bot.dialogs.DialogTurnResult; +import com.microsoft.bot.dialogs.WaterfallDialog; +import com.microsoft.bot.dialogs.WaterfallStep; +import com.microsoft.bot.dialogs.WaterfallStepContext; +import com.microsoft.bot.integration.Configuration; + +import java.util.Arrays; +import java.util.concurrent.CompletableFuture; + +/** + * This is an example root dialog. Replace this with your applications. + */ +public class RootDialog extends ComponentDialog { + + /** + * QnA Maker initial dialog. + */ + private final String initialDialog = "initial-dialog"; + + /** + * Root dialog for this bot. Creates a QnAMakerDialog. + * + * @param services A {@link BotServices} which contains the applications + * @param configuration A {@link Configuration} populated with the application.properties file + */ + public RootDialog(BotServices services, Configuration configuration) { + super("root"); + + this.addDialog(new QnAMakerBaseDialog(services, configuration)); + + WaterfallStep[] waterfallSteps = { + this::initialStep + }; + WaterfallDialog waterfallDialog = new WaterfallDialog(initialDialog, Arrays.asList(waterfallSteps)); + this.addDialog(waterfallDialog); + + // The initial child Dialog to run. + this.setInitialDialogId(initialDialog); + } + + /** + * This is the first step of the WaterfallDialog. + * It kicks off the dialog with the QnA Maker with provided options. + * + * @param stepContext A {@link WaterfallStepContext} + * @return A {@link DialogTurnResult} + */ + private CompletableFuture initialStep(WaterfallStepContext stepContext) { + return stepContext.beginDialog("QnAMakerDialog", null); + } +} diff --git a/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/package-info.java b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/package-info.java new file mode 100644 index 00000000..b4c44859 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/java/com/microsoft/bot/sample/qnamaker/all/features/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. + +/** + * This package contains the classes for the qnamaker-all-features sample. + */ +package com.microsoft.bot.sample.qnamaker.all.features; diff --git a/samples/49.qnamaker-all-features/src/main/resources/application.properties b/samples/49.qnamaker-all-features/src/main/resources/application.properties new file mode 100644 index 00000000..9598d9ac --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/resources/application.properties @@ -0,0 +1,7 @@ +MicrosoftAppId= +MicrosoftAppPassword= +QnAKnowledgebaseId= +QnAEndpointKey= +QnAEndpointHostName= +DefaultAnswer= +server.port=3978 diff --git a/samples/49.qnamaker-all-features/src/main/resources/log4j2.json b/samples/49.qnamaker-all-features/src/main/resources/log4j2.json new file mode 100644 index 00000000..67c0ad53 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/resources/log4j2.json @@ -0,0 +1,18 @@ +{ + "configuration": { + "name": "Default", + "appenders": { + "Console": { + "name": "Console-Appender", + "target": "SYSTEM_OUT", + "PatternLayout": {"pattern": "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"} + } + }, + "loggers": { + "root": { + "level": "debug", + "appender-ref": {"ref": "Console-Appender","level": "debug"} + } + } + } +} diff --git a/samples/49.qnamaker-all-features/src/main/resources/smartLightFAQ.tsv b/samples/49.qnamaker-all-features/src/main/resources/smartLightFAQ.tsv new file mode 100644 index 00000000..ae131259 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/resources/smartLightFAQ.tsv @@ -0,0 +1,23 @@ +๏ปฟQuestion Answer Source Metadata SuggestedQuestions IsContextOnly Prompts QnaId +My Contoso smart light won't turn on. 1. The simplest way to troubleshoot your smart light is to turn it off and on.\n2. Check the connection to the wall outlet to make sure it's plugged in properly. dina-kb-9.tsv [] false [{"displayOrder":0,"qnaId":91,"displayText":"Stopped"}] 90 +Light won't turn on. 1. The simplest way to troubleshoot your smart light is to turn it off and on.\n2. Check the connection to the wall outlet to make sure it's plugged in properly. dina-kb-9.tsv [] false [{"displayOrder":0,"qnaId":91,"displayText":"Stopped"}] 90 +Doesn't work 1. The simplest way to troubleshoot your smart light is to turn it off and on.\n2. Check the connection to the wall outlet to make sure it's plugged in properly. dina-kb-9.tsv [] false [{"displayOrder":0,"qnaId":91,"displayText":"Stopped"}] 90 +My smart light app stopped responding. 1. Restart the app.ย \n2. If the problem persists, contact support. dina-kb-9.tsv [] false [{"displayOrder":0,"qnaId":95,"displayText":"support"}] 91 +I upgraded the app and it doesn't work anymore. When you upgrade, you need to:\n\n1. Disable Bluetooth, then re-enable it\n2. After reenable, repair your light with the app. dina-kb-9.tsv [] false [] 92 +Light doesn't work after upgrade. When you upgrade, you need to:\n\n1. Disable Bluetooth, then re-enable it\n2. After reenable, repair your light with the app. dina-kb-9.tsv [] false [] 92 +light When you upgrade, you need to:\n\n1. Disable Bluetooth, then re-enable it\n2. After reenable, repair your light with the app. dina-kb-9.tsv [] false [] 92 +How long does the light's battery last for? The battery will last approximately 10 - 12 weeks with regular use. dina-kb-9.tsv [] false [] 93 +What type of light bulb do I need? A 26-Watt compact fluorescent light bulb that features both energy savings and long-life performance. dina-kb-9.tsv [] false [] 94 +Contact customer support Email us at service@contoso.com or call us at (202) 555-0164 dina-kb-9.tsv [] false [] 95 +I need help Email us at service@contoso.com or call us at (202) 555-0164 dina-kb-9.tsv [] false [] 95 +Help! Email us at service@contoso.com or call us at (202) 555-0164 dina-kb-9.tsv [] false [] 95 +How do I contact support? Email us at service@contoso.com or call us at (202) 555-0164 dina-kb-9.tsv [] false [] 95 +Who should I contact for customer service? Email us at service@contoso.com or call us at (202) 555-0164 dina-kb-9.tsv [] false [] 95 +Troubleshooting Enter a question to search the knowledge base. dina-kb-9.tsv category:troubleshooting [] false [] 96 +Hi Welcome to the **Smart lightbulb** bot. ๐Ÿ˜Ž dina-kb-9.tsv category:chitchat [] false [] 97 +Hello Welcome to the **Smart lightbulb** bot. ๐Ÿ˜Ž dina-kb-9.tsv category:chitchat [] false [] 97 +Start Welcome to the **Smart lightbulb** bot. ๐Ÿ˜Ž dina-kb-9.tsv category:chitchat [] false [] 97 +Begin Welcome to the **Smart lightbulb** bot. ๐Ÿ˜Ž dina-kb-9.tsv category:chitchat [] false [] 97 +Bye ๐Ÿ˜Ž dina-kb-9.tsv category:chitchat [] false [] 98 +End ๐Ÿ˜Ž dina-kb-9.tsv category:chitchat [] false [] 98 +Good bye ๐Ÿ˜Ž dina-kb-9.tsv category:chitchat [] false [] 98 \ No newline at end of file diff --git a/samples/49.qnamaker-all-features/src/main/webapp/META-INF/MANIFEST.MF b/samples/49.qnamaker-all-features/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 00000000..254272e1 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/samples/49.qnamaker-all-features/src/main/webapp/WEB-INF/web.xml b/samples/49.qnamaker-all-features/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000..383c1900 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,12 @@ + + + dispatcher + + org.springframework.web.servlet.DispatcherServlet + + + contextConfigLocation + /WEB-INF/spring/dispatcher-config.xml + + 1 + \ No newline at end of file diff --git a/samples/49.qnamaker-all-features/src/main/webapp/index.html b/samples/49.qnamaker-all-features/src/main/webapp/index.html new file mode 100644 index 00000000..e570d548 --- /dev/null +++ b/samples/49.qnamaker-all-features/src/main/webapp/index.html @@ -0,0 +1,420 @@ +๏ปฟ + + + + + + QnAMakerBot + + + + + +
+
+
+
QnAMakerBot Bot
+
+
+
+
+
Your bot is ready!
+
You can test your bot in the Bot Framework Emulator
+ by connecting to http://localhost:3978/api/messages.
+ +
Visit Azure + Bot Service to register your bot and add it to
+ various channels. The bot's endpoint URL typically looks + like this:
+
https://your_bots_hostname/api/messages
+
+
+
+
+ +
+ + + diff --git a/samples/49.qnamaker-all-features/src/test/java/com/microsoft/bot/sample/qnamaker/all/features/ApplicationTest.java b/samples/49.qnamaker-all-features/src/test/java/com/microsoft/bot/sample/qnamaker/all/features/ApplicationTest.java new file mode 100644 index 00000000..4933b87c --- /dev/null +++ b/samples/49.qnamaker-all-features/src/test/java/com/microsoft/bot/sample/qnamaker/all/features/ApplicationTest.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.bot.sample.qnamaker.all.features; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTest { + + @Test + public void contextLoads() { + } + +}