This commit is contained in:
Chris Mullins 2018-03-08 18:15:47 -08:00 коммит произвёл Drew Marsh
Родитель 2ff35b5bfd
Коммит 71647d2d91
9 изменённых файлов: 25 добавлений и 258 удалений

Просмотреть файл

@ -1,124 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Middleware;
using Microsoft.Cognitive.LUIS;
namespace Microsoft.Bot.Builder.Ai
{
public class LuisRecognizerMiddleware : IntentRecognizerMiddleware
{
private readonly LuisClient _luisClient;
public LuisRecognizerMiddleware(string appId, string appKey) : base()
{
if (string.IsNullOrWhiteSpace(appId))
throw new ArgumentNullException(nameof(appId));
if (string.IsNullOrWhiteSpace(appKey))
throw new ArgumentNullException(nameof(appKey));
_luisClient = new LuisClient(appId, appKey);
SetupOnRecognize();
}
public LuisRecognizerMiddleware(string appId, string appKey, string baseUri) : base()
{
if (string.IsNullOrWhiteSpace(appId))
throw new ArgumentNullException(nameof(appId));
if (string.IsNullOrWhiteSpace(appKey))
throw new ArgumentNullException(nameof(appKey));
if (string.IsNullOrWhiteSpace(baseUri))
throw new ArgumentNullException(nameof(baseUri));
_luisClient = new LuisClient(appId, appKey, baseUri);
SetupOnRecognize();
}
private void SetupOnRecognize()
{
this.OnRecognize(async (context) =>
{
Intent i = await RecognizeAndMap(context.Request.AsMessageActivity()?.Text);
return new List<Intent>() { i };
});
}
private async Task<Intent> RecognizeAndMap(string utterance)
{
Intent intent = new Intent();
// LUIS client throws an exception on Predict is the utterance is null / empty
// so just skip those cases and return a non-match.
if (string.IsNullOrWhiteSpace(utterance))
{
intent.Name = string.Empty;
intent.Score = 0.0;
}
else
{
LuisResult result = await _luisClient.Predict(utterance);
if (result.TopScoringIntent == null)
{
intent.Name = string.Empty;
intent.Score = 0.0;
}
else
{
intent.Name = result.TopScoringIntent.Name;
intent.Score = result.TopScoringIntent.Score;
}
foreach (var luisEntityList in result.Entities.Values)
{
foreach (var luisEntity in luisEntityList)
{
intent.Entities.Add(new LuisEntity(luisEntity));
}
}
}
return intent;
}
}
public class LuisEntity : Entity
{
public LuisEntity()
{
}
public LuisEntity(Cognitive.LUIS.Entity luisEntity)
{
this.Type = luisEntity.Name;
this.Value = luisEntity.Value;
this.StartIndex = luisEntity.StartIndex;
this.EndIndex = luisEntity.EndIndex;
this.Resolution = new FlexObject();
if (luisEntity.Resolution != null)
{
foreach(var key in luisEntity.Resolution.Keys)
{
this.Resolution[key] = luisEntity.Resolution[key];
}
}
}
public string Type { get; set; }
public string Value { get; set; }
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public FlexObject Resolution { get; set; }
}
}

Просмотреть файл

@ -37,7 +37,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Cognitive.LUIS" Version="2.0.2" />
<PackageReference Include="Microsoft.Bot.Builder.Core" Condition=" '$(PackageVersion)' == '' " Version="4.0.0-local" />
<PackageReference Include="Microsoft.Bot.Builder.Core" Condition=" '$(PackageVersion)' != '' " Version="$(PackageVersion)" />
</ItemGroup>

Просмотреть файл

@ -169,12 +169,9 @@ namespace Microsoft.Bot.Builder.Core.Extensions
{
public static BatchOutput Batch(this IBotContext context)
{
if (!context.Has(BatchOutputMiddleware.BatchOuputKey))
throw new InvalidOperationException("No Batch Output found in Context");
BatchOutput bo = context.Get<BatchOutput>(BatchOutputMiddleware.BatchOuputKey);
if (bo == null)
throw new InvalidOperationException("Batch output found in context is invalid");
throw new InvalidOperationException("BatchOutputMiddleware does not appear to be setup.");
return bo;
}

Просмотреть файл

@ -32,7 +32,7 @@ namespace Microsoft.Bot.Builder
if (handler == null)
throw new ArgumentNullException(nameof(handler));
_onSendActivities.Add(handler);
_onSendActivities.Add(handler);
return this;
}
@ -74,13 +74,28 @@ namespace Microsoft.Bot.Builder
}
}
public async Task SendActivity(params string[] textRepliesToSend)
{
if (textRepliesToSend == null)
throw new ArgumentNullException(nameof(textRepliesToSend));
List<Activity> newActivities = new List<Activity>();
foreach (string s in textRepliesToSend)
{
if (!string.IsNullOrWhiteSpace(s))
newActivities.Add(new Activity(ActivityTypes.Message) { Text = s });
}
await SendActivity(newActivities.ToArray());
}
public async Task SendActivity(params Activity[] activities)
{
// Bind the relevant Conversation Reference properties, such as URLs and
// ChannelId's, to the activities we're about to send.
ConversationReference cr = GetConversationReference(this._request);
foreach (Activity a in activities)
{
ConversationReference cr = GetConversationReference(this._request);
{
ApplyConversationReference(a, cr);
}
@ -295,7 +310,7 @@ namespace Microsoft.Bot.Builder
lock (_services)
{
return _services.ContainsKey(key);
return _services.ContainsKey(key);
}
}

Просмотреть файл

@ -2,7 +2,7 @@
// Licensed under the MIT License.
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Middleware;
using Microsoft.Bot.Builder.Core.Extensions;
using System.Threading.Tasks;
namespace Microsoft.Bot.Samples.Echo
@ -39,7 +39,7 @@ namespace Microsoft.Bot.Samples.Echo
await _myService.DoSomethingAsync();
// return our reply to the user
context.Reply($"[{conversationState.TurnNumber}] You sent {msgActivity.Text} which was {length} characters");
context.Batch().Reply($"[{conversationState.TurnNumber}] You sent {msgActivity.Text} which was {length} characters");
}
var convUpdateActivity = context.Request.AsConversationUpdateActivity();
@ -49,7 +49,7 @@ namespace Microsoft.Bot.Samples.Echo
{
if (newMember.Id != convUpdateActivity.Recipient.Id)
{
context.Reply("Hello and welcome to the echo bot.");
context.Batch().Reply("Hello and welcome to the echo bot.");
}
}
}

Просмотреть файл

@ -6,6 +6,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Builder.Core.Extensions\Microsoft.Bot.Builder.Core.Extensions.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Builder.Core\Microsoft.Bot.Builder.Core.csproj" />
</ItemGroup>

Просмотреть файл

@ -58,7 +58,7 @@ namespace Microsoft.Bot.Builder.Core.Extensions.Tests
BatchOutput bo = new BatchOutput();
bo.Typing();
bo.EndOfConversation();
c.OnSendActivity(async (activities, next) =>
{
Assert.IsTrue(activities.Count == 2, "Incorrect Activity Count");

Просмотреть файл

@ -1,75 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Bot.Builder.Tests
{
[TestClass]
[TestCategory("ContextExtensions")]
public class ContextExtensionTests
{
[TestMethod]
public async Task ContextDelay()
{
TestAdapter adapter = new TestAdapter();
DateTime start = DateTime.Now;
await new TestFlow(adapter, async (context) =>
{
if (context.Request.AsMessageActivity().Text == "wait")
{
context
.Reply("before")
.Delay(1000)
.Reply("after");
}
else
{
context.Reply(context.Request.AsMessageActivity().Text);
}
})
.Send("wait")
.AssertReply("before")
.AssertReply("after")
.StartTest();
double duration = (DateTime.Now.Subtract(start)).TotalMilliseconds;
// The delay should have taken 1000 ms. Assert
Assert.IsTrue(duration > 500 && duration < 1500, $"Duration not in range: {duration}.");
}
[TestMethod]
public async Task ContextShowTyping()
{
TestAdapter adapter = new TestAdapter();
await new TestFlow(adapter, async (context) =>
{
if (context.Request.AsMessageActivity().Text == "typing")
{
context.ShowTyping();
context.Reply("typing done");
}
else
{
context.Reply(context.Request.AsMessageActivity().Text);
}
})
.Send("typing")
.AssertReply(
(activity) => { Assert.IsTrue(activity.Type == ActivityTypes.Typing); },
"Typing indiciator not set")
.AssertReply("typing done")
.StartTest();
}
}
}

Просмотреть файл

@ -1,46 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Builder.Middleware;
using Microsoft.Bot.Schema;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Bot.Builder.Tests
{
[TestClass]
[TestCategory("Middleware")]
public class Middleware_EchoTests
{
[TestMethod]
public async Task Middleware_Echo()
{
string messageText = Guid.NewGuid().ToString();
TestAdapter adapter = new TestAdapter()
.Use(new EchoMiddleWare());
await new TestFlow(adapter)
.Send(messageText).AssertReply(messageText)
.StartTest();
}
}
public class EchoMiddleWare : IReceiveActivity
{
public EchoMiddleWare()
{
}
public async Task ReceiveActivity(IBotContext context, MiddlewareSet.NextDelegate next)
{
var response = ((Activity)context.Request).CreateReply();
response.Text = context.Request.AsMessageActivity().Text;
context.Responses.Add(response);
await next();
}
}
}