forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLuisActionDialog.cs
389 lines (318 loc) · 17.5 KB
/
LuisActionDialog.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
namespace Microsoft.Cognitive.LUIS.ActionBinding.Bot
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Internals.Fibers;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Connector;
public delegate Task LuisActionHandler(IDialogContext context, object actionResult);
public delegate Task LuisActionActivityHandler(IDialogContext context, IAwaitable<IMessageActivity> message, object actionResult);
[Serializable]
public class LuisActionDialog<TResult> : LuisDialog<TResult>
{
private readonly LuisActionResolver actionResolver;
private readonly Action<ILuisAction, object> onContextCreation;
public LuisActionDialog(IEnumerable<Assembly> assemblies, params ILuisService[] services) : this(assemblies, null, services)
{
}
public LuisActionDialog(IEnumerable<Assembly> assemblies, Action<ILuisAction, object> onContextCreation, params ILuisService[] services) : base(services)
{
if (assemblies == null)
{
throw new ArgumentNullException(nameof(assemblies));
}
this.onContextCreation = onContextCreation;
this.actionResolver = new LuisActionResolver(assemblies.ToArray());
}
protected override async Task MessageReceived(IDialogContext context, IAwaitable<IMessageActivity> item)
{
var message = await item;
var messageText = await GetLuisQueryTextAsync(context, message);
var tasks = this.services.Select(s => s.QueryAsync(messageText, context.CancellationToken)).ToArray();
var results = await Task.WhenAll(tasks);
var winners = from result in results.Select((value, index) => new { value, index })
let resultWinner = this.BestIntentFrom(result.value)
where resultWinner != null
select new LuisServiceResult(result.value, resultWinner, this.services[result.index]);
var winner = this.BestResultFrom(winners);
if (winner == null)
{
throw new InvalidOperationException("No winning intent selected from Luis results.");
}
var intentName = default(string);
var luisAction = this.actionResolver.ResolveActionFromLuisIntent(winner.Result, out intentName);
if (luisAction != null)
{
var executionContextChain = new List<ActionExecutionContext> { new ActionExecutionContext(intentName, luisAction) };
while (LuisActionResolver.IsContextualAction(luisAction))
{
var luisActionDefinition = default(LuisActionBindingAttribute);
if (!LuisActionResolver.CanStartWithNoContextAction(luisAction, out luisActionDefinition))
{
await context.PostAsync($"Cannot start contextual action '{luisActionDefinition.FriendlyName}' without a valid context.");
return;
}
luisAction = LuisActionResolver.BuildContextForContextualAction(luisAction, out intentName);
if (luisAction != null)
{
this.onContextCreation?.Invoke(luisAction, context);
executionContextChain.Insert(0, new ActionExecutionContext(intentName, luisAction));
}
}
var validationResults = default(ICollection<ValidationResult>);
if (!luisAction.IsValid(out validationResults))
{
var childDialog = new LuisActionMissingEntitiesDialog(winner.LuisService, executionContextChain);
context.Call(childDialog, this.LuisActionMissingDialogFinished);
}
else
{
await this.DispatchToLuisActionActivityHandler(context, item, intentName, luisAction);
}
}
}
protected virtual IDictionary<string, LuisActionActivityHandler> GetActionHandlersByIntent()
{
return LuisActionDialogHelper.EnumerateHandlers(this).ToDictionary(kv => kv.Key, kv => kv.Value);
}
protected virtual async Task<object> PerformActionFulfillment(IDialogContext context, IAwaitable<IMessageActivity> item, ILuisAction luisAction)
{
return await luisAction.FulfillAsync();
}
protected virtual async Task DispatchToLuisActionActivityHandler(IDialogContext context, IAwaitable<IMessageActivity> item, string intentName, ILuisAction luisAction)
{
var actionHandlerByIntent = new Dictionary<string, LuisActionActivityHandler>(this.GetActionHandlersByIntent());
var handler = default(LuisActionActivityHandler);
if (!actionHandlerByIntent.TryGetValue(intentName, out handler))
{
handler = actionHandlerByIntent[string.Empty];
}
if (handler != null)
{
await handler(context, item, await this.PerformActionFulfillment(context, item, luisAction));
}
else
{
throw new Exception($"No default intent handler found.");
}
}
protected virtual async Task LuisActionMissingDialogFinished(IDialogContext context, IAwaitable<ActionExecutionContext> executionContext)
{
var messageActivity = (IMessageActivity)context.Activity;
var executionContextResult = await executionContext;
await this.DispatchToLuisActionActivityHandler(context, Awaitable.FromItem(messageActivity), executionContextResult.Intent, executionContextResult.Action);
}
internal static class LuisActionDialogHelper
{
public static IEnumerable<KeyValuePair<string, LuisActionActivityHandler>> EnumerateHandlers(object dialog)
{
var type = dialog.GetType();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var method in methods)
{
var intents = method.GetCustomAttributes<LuisIntentAttribute>(inherit: true).ToArray();
LuisActionActivityHandler intentHandler = null;
try
{
intentHandler = (LuisActionActivityHandler)Delegate.CreateDelegate(typeof(LuisActionActivityHandler), dialog, method, throwOnBindFailure: false);
}
catch (ArgumentException)
{
// "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
// https://github.com/Microsoft/BotBuilder/issues/634
// https://github.com/Microsoft/BotBuilder/issues/435
}
// fall back for compatibility
if (intentHandler == null)
{
try
{
var handler = (LuisActionHandler)Delegate.CreateDelegate(typeof(LuisActionHandler), dialog, method, throwOnBindFailure: false);
if (handler != null)
{
// thunk from new to old delegate type
intentHandler = (context, message, result) => handler(context, result);
}
}
catch (ArgumentException)
{
// "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
// https://github.com/Microsoft/BotBuilder/issues/634
// https://github.com/Microsoft/BotBuilder/issues/435
}
}
if (intentHandler != null)
{
var intentNames = intents.Select(i => i.IntentName).DefaultIfEmpty(method.Name);
foreach (var intentName in intentNames)
{
var key = string.IsNullOrWhiteSpace(intentName) ? string.Empty : intentName;
yield return new KeyValuePair<string, LuisActionActivityHandler>(intentName, intentHandler);
}
}
else
{
if (intents.Length > 0)
{
var msg = $"Handler '{method.Name}' signature is not valid for the following intent/s: {string.Join(";", intents.Select(i => i.IntentName))}";
throw new InvalidIntentHandlerException(msg, method);
}
}
}
}
}
[Serializable]
internal class LuisActionMissingEntitiesDialog : IDialog<ActionExecutionContext>
{
private readonly ILuisService luisService;
private string intentName;
private ILuisAction luisAction;
private IList<ActionExecutionContext> executionContextChain;
private QueryValueResult overrunData;
public LuisActionMissingEntitiesDialog(ILuisService luisService, IList<ActionExecutionContext> executionContextChain)
{
if (executionContextChain == null || executionContextChain.Count == 0)
{
throw new ArgumentException("Action chain cannot be null or empty.", nameof(executionContextChain));
}
var executionContext = executionContextChain.First();
SetField.NotNull(out this.luisService, nameof(luisService), luisService);
SetField.NotNull(out this.intentName, nameof(this.intentName), executionContext.Intent);
SetField.NotNull(out this.luisAction, nameof(this.luisAction), executionContext.Action);
executionContextChain.RemoveAt(0);
if (executionContextChain.Count > 0)
{
this.executionContextChain = executionContextChain;
}
}
public virtual async Task StartAsync(IDialogContext context)
{
if (this.executionContextChain != null)
{
var childDialog = new LuisActionMissingEntitiesDialog(this.luisService, this.executionContextChain);
// clean executionContextChain - avoid serialization payload
this.executionContextChain = null;
context.Call(childDialog, this.AfterContextualActionFinished);
return;
}
await this.MessageReceivedAsync(context, null);
}
protected virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> item)
{
var nextPromptIdx = 0;
var validationResults = default(ICollection<ValidationResult>);
this.luisAction.IsValid(out validationResults);
if (item != null)
{
var message = await item;
var paramName = validationResults.First().MemberNames.First();
var paramValue = message.Text;
var result = await LuisActionResolver.QueryValueFromLuisAsync(this.luisService, this.luisAction, paramName, paramValue, context.CancellationToken);
if (result.Succeed)
{
nextPromptIdx++;
}
else if (!string.IsNullOrWhiteSpace(result.NewIntent) && result.NewAction != null)
{
var currentActionDefinition = LuisActionResolver.GetActionDefinition(this.luisAction);
var isContextual = false;
if (LuisActionResolver.IsValidContextualAction(result.NewAction, this.luisAction, out isContextual))
{
var executionContextChain = new List<ActionExecutionContext> { new ActionExecutionContext(result.NewIntent, result.NewAction) };
var childDialog = new LuisActionMissingEntitiesDialog(this.luisService, executionContextChain);
context.Call(childDialog, this.AfterContextualActionFinished);
return;
}
else if (isContextual & !LuisActionResolver.IsContextualAction(this.luisAction))
{
var newActionDefinition = LuisActionResolver.GetActionDefinition(result.NewAction);
await context.PostAsync($"Cannot execute action '{newActionDefinition.FriendlyName}' in the context of '{currentActionDefinition.FriendlyName}' - continuing with current action");
}
else if (!this.luisAction.GetType().Equals(result.NewAction.GetType()))
{
var newActionDefinition = LuisActionResolver.GetActionDefinition(result.NewAction);
var valid = LuisActionResolver.UpdateIfValidContextualAction(result.NewAction, this.luisAction, out isContextual);
if (!valid && isContextual)
{
await context.PostAsync($"Cannot switch to action '{newActionDefinition.FriendlyName}' from '{currentActionDefinition.FriendlyName}' due to invalid context - continuing with current action");
}
else if (currentActionDefinition.ConfirmOnSwitchingContext)
{
// serialize overrun info
this.overrunData = result;
PromptDialog.Confirm(
context,
this.AfterOverrunCurrentActionSelected,
$"Do you want to discard the current action '{currentActionDefinition.FriendlyName}' and start executing '{newActionDefinition.FriendlyName}' action?");
return;
}
else
{
this.intentName = result.NewIntent;
this.luisAction = result.NewAction;
this.luisAction.IsValid(out validationResults);
}
}
}
}
if (validationResults.Count > nextPromptIdx)
{
await context.PostAsync(validationResults.ElementAt(nextPromptIdx).ErrorMessage);
context.Wait(this.MessageReceivedAsync);
}
else
{
context.Done(new ActionExecutionContext(this.intentName, this.luisAction));
}
}
private async Task AfterOverrunCurrentActionSelected(IDialogContext context, IAwaitable<bool> result)
{
if (await result == true)
{
// if switching from contextual to other root
if (LuisActionResolver.IsContextualAction(this.luisAction) && !LuisActionResolver.IsContextualAction(this.overrunData.NewAction))
{
context.Done(new ActionExecutionContext(this.overrunData.NewIntent, this.overrunData.NewAction) { ChangeRootSignaling = true });
return;
}
this.intentName = this.overrunData.NewIntent;
this.luisAction = this.overrunData.NewAction;
}
// clean overrunData - avoid serialization payload
this.overrunData = null;
await this.MessageReceivedAsync(context, null);
}
private async Task AfterContextualActionFinished(IDialogContext context, IAwaitable<ActionExecutionContext> executionContext)
{
var executionContextResult = await executionContext;
if (executionContextResult.ChangeRootSignaling)
{
if (LuisActionResolver.IsContextualAction(this.luisAction))
{
context.Done(executionContextResult);
return;
}
else
{
this.intentName = executionContextResult.Intent;
this.luisAction = executionContextResult.Action;
}
}
else
{
var result = await executionContextResult.Action.FulfillAsync();
if (result is string)
{
await context.PostAsync(result.ToString());
}
}
await this.MessageReceivedAsync(context, null);
}
}
}
}