コード例 #1
0
        public async void LuisDiscoveryTest()
        {
            // arrage
            var expectedIntent = "Sample";
            var expectedName   = "Sample";
            var expectedScore  = 100;
            var luisAppDetail  = new LuisAppDetail()
            {
                Intent = expectedIntent, Name = expectedName, Score = expectedScore
            };
            var luisDiscoveryResponse = new LuisDiscoveryResponse()
            {
                IsSucceded     = true,
                ResultId       = 100,
                LuisAppDetails = new List <LuisAppDetail>()
                {
                    luisAppDetail
                }
            };
            var jsonLuisDiscoveryResponse = JsonConvert.SerializeObject(luisDiscoveryResponse);

            var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(jsonLuisDiscoveryResponse),
            })
            .Verifiable();

            var httpClient = new HttpClient(handlerMock.Object)
            {
                BaseAddress = new Uri("http://localhost/")
            };
            var storage           = new MemoryStorage();
            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);
            var adapter           = new TestAdapter().Use(new AutoSaveStateMiddleware(conversationState));
            var dialogState       = conversationState.CreateProperty <DialogState>("dialogState");
            var dialogs           = new DialogSet(dialogState);
            var steps             = new WaterfallStep[]
            {
                async(step, cancellationToken) =>
                {
                    await step.Context.SendActivityAsync("response");

                    // act
                    ILuisRouterService luisRouterService = new LuisRouterService(httpClient, EnvironmentName, ContentRootPath, userState);
                    var result = await luisRouterService.LuisDiscoveryAsync(step, "TEXT", "APPLICATIONCODE", "ENCRYPTIONKEY");

                    var item = result.ToList().FirstOrDefault();

                    // assert
                    Assert.Equal(expectedIntent, item.Intent);
                    Assert.Equal(expectedName, item.Name);
                    Assert.Equal(expectedScore, item.Score);

                    return(Dialog.EndOfTurn);
                }
            };

            dialogs.Add(new WaterfallDialog(
                            "test",
                            steps));

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);
                await dc.ContinueDialogAsync(cancellationToken);
                if (!turnContext.Responded)
                {
                    await dc.BeginDialogAsync("test", null, cancellationToken);
                }
            })
            .Send("ask")
            .AssertReply("response")
            .StartTestAsync();
        }
コード例 #2
0
        public async Task <IActionResult> Post([FromBody] LuisDiscoveryRequest model)
        {
            // non-forced-to-disposal
            LuisDiscoveryResponse result = new LuisDiscoveryResponse
            {
                IsSucceded = true,
                ResultId   = (int)LuisDiscoveryResponseEnum.Success
            };

            // forced-to-disposal

            try
            {
                if (string.IsNullOrEmpty(model.Text))
                {
                    throw new BusinessException((int)LuisDiscoveryResponseEnum.FailedEmptyText);
                }

                // building service list
                Settings.LuisServices = new Dictionary <string, LuisRecognizer>();
                foreach (LuisAppRegistration app in Settings.LuisAppRegistrations)
                {
                    var luis = new LuisApplication(app.LuisAppId, app.LuisAuthoringKey, app.LuisEndpoint);

                    LuisPredictionOptions luisPredictionOptions = null;
                    LuisRecognizer        recognizer            = null;

                    bool needsPredictionOptions = false;
                    if ((!string.IsNullOrEmpty(model.BingSpellCheckSubscriptionKey)) || (model.EnableLuisTelemetry))
                    {
                        needsPredictionOptions = true;
                    }

                    if (needsPredictionOptions)
                    {
                        luisPredictionOptions = new LuisPredictionOptions();

                        if (model.EnableLuisTelemetry)
                        {
                            luisPredictionOptions.TelemetryClient        = telemetry;
                            luisPredictionOptions.Log                    = true;
                            luisPredictionOptions.LogPersonalInformation = true;
                        }

                        if (!string.IsNullOrEmpty(model.BingSpellCheckSubscriptionKey))
                        {
                            luisPredictionOptions.BingSpellCheckSubscriptionKey = model.BingSpellCheckSubscriptionKey;
                            luisPredictionOptions.SpellCheck        = true;
                            luisPredictionOptions.IncludeAllIntents = true;
                        }

                        recognizer = new LuisRecognizer(luis, luisPredictionOptions);
                    }
                    else
                    {
                        recognizer = new LuisRecognizer(luis);
                    }

                    Settings.LuisServices.Add(app.LuisName, recognizer);
                }

                foreach (LuisAppRegistration app in Settings.LuisAppRegistrations)
                {
                    var storage           = new MemoryStorage();
                    var conversationState = new ConversationState(storage);

                    var adapter = new TestAdapter().Use(new AutoSaveStateMiddleware(conversationState));

                    IMessageActivity msg = Activity.CreateMessageActivity();
                    msg.Id           = Guid.NewGuid().ToString();
                    msg.From         = new ChannelAccount("sip: [email protected]", "bot");
                    msg.Recipient    = new ChannelAccount("sip: [email protected]", "agent");
                    msg.Text         = model.Text;
                    msg.Locale       = "en-us";
                    msg.ServiceUrl   = "url";
                    msg.ChannelId    = Guid.NewGuid().ToString();
                    msg.Conversation = new ConversationAccount();
                    msg.Type         = ActivityTypes.Message;
                    msg.Timestamp    = DateTime.UtcNow;

                    var context = new TurnContext(adapter, (Activity)msg);

                    var recognizerResult = await Settings.LuisServices[app.LuisName].RecognizeAsync(context, new CancellationToken());
                    var topIntent        = recognizerResult?.GetTopScoringIntent();
                    if (topIntent != null && topIntent.HasValue && topIntent.Value.score >= .90 && topIntent.Value.intent != "None")
                    {
                        result.LuisAppDetails.Add(new LuisAppDetail()
                        {
                            Name = app.LuisName, Intent = topIntent.Value.intent, Score = topIntent.Value.score
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                result.IsSucceded = false;

                if (ex is BusinessException)
                {
                    result.ResultId = ((BusinessException)ex).ResultId;
                }
                else
                {
                    result.ResultId = (int)LuisDiscoveryResponseEnum.Failed;

                    this.logger.LogError($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        this.logger.LogError($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                    }
                }
            }
            finally
            {
                // clean forced-to-disposal

                GC.Collect();
            }

            string message = EnumDescription.GetEnumDescription((LuisDiscoveryResponseEnum)result.ResultId);

            this.logger.LogInformation($">> Message information: {message}");

            return((result.IsSucceded) ? (ActionResult) new OkObjectResult(result) : (ActionResult) new BadRequestObjectResult(new { message = message }));
        }