-
Notifications
You must be signed in to change notification settings - Fork 479
/
LuisRecognizer.cs
748 lines (678 loc) · 50.3 KB
/
LuisRecognizer.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Configuration;
using Microsoft.Bot.Schema;
using Microsoft.Rest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Bot.Builder.AI.Luis
{
/// <inheritdoc />
/// <summary>
/// A LUIS based implementation of <see cref="ITelemetryRecognizer"/>.
/// </summary>
public class LuisRecognizer : ITelemetryRecognizer
{
/// <summary>
/// The declarative type for this recognizer.
/// </summary>
[JsonProperty("$kind")]
public const string DeclarativeType = "Microsoft.LuisRecognizer";
/// <summary>
/// The value type for a LUIS trace activity.
/// </summary>
public const string LuisTraceType = "https://www.luis.ai/schemas/trace";
/// <summary>
/// The context label for a LUIS trace activity.
/// </summary>
public const string LuisTraceLabel = "Luis Trace";
private readonly string _cacheKey;
private readonly LuisRecognizerOptions _luisRecognizerOptions;
/// <summary>
/// Initializes a new instance of the <see cref="LuisRecognizer"/> class.
/// </summary>
/// <param name="recognizerOptions"> The LUIS recognizer version options.</param>
/// <param name="clientHandler">(Optional) Custom handler for LUIS API calls to allow mocking.</param>
public LuisRecognizer(LuisRecognizerOptions recognizerOptions, HttpClientHandler clientHandler = null)
{
_luisRecognizerOptions = recognizerOptions;
TelemetryClient = recognizerOptions.TelemetryClient;
LogPersonalInformation = recognizerOptions.LogPersonalInformation;
var delegatingHandler = new LuisDelegatingHandler();
var httpClientHandler = clientHandler ?? CreateRootHandler();
#pragma warning disable CA2000 // Dispose objects before losing scope (suppressing this warning, for now! we will address this once we implement HttpClientFactory in a future release)
var currentHandler = CreateHttpHandlerPipeline(httpClientHandler, delegatingHandler);
#pragma warning restore CA2000 // Dispose objects before losing scope
HttpClient = new HttpClient(currentHandler, false)
{
Timeout = TimeSpan.FromMilliseconds(recognizerOptions.Timeout),
};
#pragma warning disable 618 // Reference to obsolete property, this is here only for backward compat and should be removed when DefaultHttpClient is removed.
DefaultHttpClient = HttpClient;
#pragma warning restore 618
_cacheKey = _luisRecognizerOptions.Application.Endpoint + _luisRecognizerOptions.Application.ApplicationId;
}
/// <summary>
/// Initializes a new instance of the <see cref="LuisRecognizer"/> class.
/// </summary>
/// <param name="application">The LUIS application to use to recognize text.</param>
/// <param name="predictionOptions">(Optional) The LUIS prediction options to use.</param>
/// <param name="includeApiResults">(Optional) TRUE to include raw LUIS API response.</param>
/// <param name="clientHandler">(Optional) Custom handler for LUIS API calls to allow mocking.</param>
[Obsolete("Constructor is deprecated, please use LuisRecognizer(LuisRecognizerOptions recognizer).")]
public LuisRecognizer(LuisApplication application, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
#pragma warning disable CS0618 // Type or member is obsolete
: this(application, telemetryClient: null, logPersonalInformation: false, predictionOptions: predictionOptions, includeApiResults: includeApiResults, clientHandler: clientHandler)
#pragma warning restore CS0618 // Type or member is obsolete
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LuisRecognizer"/> class.
/// </summary>
/// <param name="application">The LUIS application to use to recognize text.</param>
/// <param name="predictionOptions">(Optional) The LUIS prediction options to use.</param>
/// <param name="includeApiResults">(Optional) TRUE to include raw LUIS API response.</param>
/// <param name="clientHandler">(Optional) Custom handler for LUIS API calls to allow mocking.</param>
/// <param name="telemetryClient">The IBotTelemetryClient used to log the LuisResult event.</param>
/// <param name="logPersonalInformation">TRUE to include personally indentifiable information.</param>
[Obsolete("Constructor is deprecated, please use LuisRecognizer(LuisRecognizerOptions recognizer).")]
public LuisRecognizer(LuisApplication application, IBotTelemetryClient telemetryClient, bool logPersonalInformation, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
: this(BuildLuisRecognizerOptionsV2(application, predictionOptions, includeApiResults), clientHandler)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LuisRecognizer"/> class.
/// </summary>
/// <param name="service">The LUIS service from configuration.</param>
/// <param name="predictionOptions">(Optional) The LUIS prediction options to use.</param>
/// <param name="includeApiResults">(Optional) TRUE to include raw LUIS API response.</param>
/// <param name="clientHandler">(Optional) Custom handler for LUIS API calls to allow mocking.</param>
[Obsolete("Constructor is deprecated, please use LuisRecognizer(LuisRecognizerOptions recognizer).")]
public LuisRecognizer(LuisService service, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
: this(new LuisApplication(service), predictionOptions, includeApiResults, clientHandler)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LuisRecognizer"/> class.
/// </summary>
/// <param name="applicationEndpoint">The LUIS endpoint as shown in https://luis.ai .</param>
/// <param name="predictionOptions">(Optional) The LUIS prediction options to use.</param>
/// <param name="includeApiResults">(Optional) TRUE to include raw LUIS API response.</param>
/// <param name="clientHandler">(Optional) Custom handler for LUIS API calls to allow mocking.</param>
[Obsolete("Constructor is deprecated, please use LuisRecognizer(LuisRecognizerOptions recognizer).")]
public LuisRecognizer(string applicationEndpoint, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
: this(new LuisApplication(applicationEndpoint), predictionOptions, includeApiResults, clientHandler)
{
}
/// <summary>
/// Gets the default <see cref="System.Net.Http.HttpClient"/> to use when calling the LUIS API.
/// </summary>
/// <value>
/// The default HTTP client to use.
/// </value>
[Obsolete("This property is deprecated and will be removed in future versions of the SDK.")]
public static HttpClient DefaultHttpClient { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to log personal information that came from the user to telemetry.
/// </summary>
/// <value>If true, personal information is logged to Telemetry; otherwise the properties will be filtered.</value>
public bool LogPersonalInformation { get; set; }
/// <summary>
/// Gets the currently configured <see cref="IBotTelemetryClient"/> that logs the LuisResult event.
/// </summary>
/// <value>The <see cref="IBotTelemetryClient"/> being used to log events.</value>
[JsonIgnore]
public IBotTelemetryClient TelemetryClient { get; }
/// <summary>
/// Gets the HttpClient used when calling the LUIS API.
/// </summary>
/// <value>
/// A <see cref="HttpClient"/>.
/// </value>
/// <remarks>
/// This property is internal only and intended to support unit tests.
/// </remarks>
[JsonIgnore]
internal HttpClient HttpClient { get; }
/// <summary>
/// Returns the name of the top scoring intent from a set of LUIS results.
/// </summary>
/// <param name="results">Result set to be searched.</param>
/// <param name="defaultIntent">(Optional) Intent name to return should a top intent be found. Defaults to a value of "None".</param>
/// <param name="minScore">(Optional) Minimum score needed for an intent to be considered as a top intent. If all intents in the set are below this threshold then the `defaultIntent` will be returned. Defaults to a value of `0.0`.</param>
/// <returns>The top scoring intent name.</returns>
public static string TopIntent(RecognizerResult results, string defaultIntent = "None", double minScore = 0.0)
{
if (results == null)
{
throw new ArgumentNullException(nameof(results));
}
string topIntent = null;
var topScore = -1.0;
if (results.Intents.Count > 0)
{
foreach (var intent in results.Intents)
{
var score = (double)intent.Value.Score;
if (score > topScore && score >= minScore)
{
topIntent = intent.Key;
topScore = score;
}
}
}
return !string.IsNullOrEmpty(topIntent) ? topIntent : defaultIntent;
}
/// <inheritdoc />
public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken)
=> await RecognizeInternalAsync(turnContext, null, null, null, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Runs an utterance through a recognizer and returns a generic recognizer result.
/// </summary>
/// <param name="dialogContext">dialogcontext.</param>
/// <param name="activity">activity.</param>
/// <param name="cancellationToken">cancellationtoken.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, CancellationToken cancellationToken)
=> await RecognizeInternalAsync(dialogContext, activity, null, null, null, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Runs an utterance through a recognizer and returns a generic recognizer result.
/// </summary>
/// <param name="turnContext">Turn context.</param>
/// <param name="predictionOptions">A <see cref="LuisPredictionOptions"/> instance to be used by the call.
/// This parameter gets merged with the default <see cref="LuisPredictionOptions"/> passed in the constructor. This will call Luis V2 endpoint if passed.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Analysis of utterance.</returns>
[Obsolete("Method is deprecated, please use RecognizeAsync(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, CancellationToken cancellationToken).")]
public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, LuisPredictionOptions predictionOptions, CancellationToken cancellationToken)
{
var overrideV2 = MergeDefaultOptionsWithProvidedOptionsV2(predictionOptions);
return await RecognizeInternalAsync(turnContext, overrideV2, null, null, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, CancellationToken cancellationToken)
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(turnContext, null, null, null, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Runs an utterance through a recognizer and returns a strongly-typed recognizer result.
/// </summary>
/// <typeparam name="T">type of result.</typeparam>
/// <param name="dialogContext">dialogContext.</param>
/// <param name="activity">activity.</param>
/// <param name="cancellationToken">cancellationToken.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
public virtual async Task<T> RecognizeAsync<T>(DialogContext dialogContext, Activity activity, CancellationToken cancellationToken)
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(dialogContext, activity, null, null, null, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Runs an utterance through a recognizer and returns a strongly-typed recognizer result.
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="turnContext">Turn context.</param>
/// <param name="predictionOptions">A <see cref="LuisPredictionOptions"/> instance to be used by the call.
/// This parameter gets merged with the default <see cref="LuisPredictionOptions"/> passed in the constructor. This will call Luis V2 endpoint if passed.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Analysis of utterance.</returns>
[Obsolete("Method is deprecated, please use RecognizeAsync<T>(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, CancellationToken cancellationToken).")]
public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, LuisPredictionOptions predictionOptions, CancellationToken cancellationToken)
where T : IRecognizerConvert, new()
{
var result = new T();
var overrideV2 = MergeDefaultOptionsWithProvidedOptionsV2(predictionOptions);
result.Convert(await RecognizeInternalAsync(turnContext, overrideV2, null, null, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
=> await RecognizeInternalAsync(turnContext, null, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <param name="dialogContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="activity">activity to recognize.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
=> await RecognizeInternalAsync(dialogContext, activity, null, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="predictionOptions">A <see cref="LuisPredictionOptions"/> instance to be used by the call.
/// This parameter gets merged with the default <see cref="LuisPredictionOptions"/> passed in the constructor. This will call Luis V2 endpoint if passed.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
[Obsolete("Method is deprecated, please use RecognizeAsync(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken)).")]
public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, LuisPredictionOptions predictionOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
{
var overrideV2 = MergeDefaultOptionsWithProvidedOptionsV2(predictionOptions);
return await RecognizeInternalAsync(turnContext, overrideV2, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(turnContext, null, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="dialogContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="activity">activity to recognize.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<T> RecognizeAsync<T>(DialogContext dialogContext, Activity activity, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(dialogContext, activity, null, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="predictionOptions">A <see cref="LuisPredictionOptions"/> instance to be used by the call.
/// This parameter gets merged with the default <see cref="LuisPredictionOptions"/> passed in the constructor. This will use Luis V2 endpoint if passed.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
[Obsolete("Method is deprecated, please use RecognizeAsync(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken)).")]
public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, LuisPredictionOptions predictionOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
where T : IRecognizerConvert, new()
{
var result = new T();
var overrideV2 = MergeDefaultOptionsWithProvidedOptionsV2(predictionOptions);
result.Convert(await RecognizeInternalAsync(turnContext, overrideV2, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Runs an utterance through a recognizer and returns a generic recognizer result.
/// </summary>
/// <param name="turnContext">Turn context.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Analysis of utterance.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, CancellationToken cancellationToken)
{
return await RecognizeInternalAsync(turnContext, recognizerOptions, null, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Runs an utterance through a recognizer and returns a generic recognizer result.
/// </summary>
/// <param name="dialogContext">dialog context.</param>
/// <param name="activity">activity to recognize.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Analysis of utterance.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, LuisRecognizerOptions recognizerOptions, CancellationToken cancellationToken)
{
return await RecognizeInternalAsync(dialogContext, activity, recognizerOptions, null, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Runs an utterance through a recognizer and returns a strongly-typed recognizer result.
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="turnContext">Turn context.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Analysis of utterance.</returns>
public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, CancellationToken cancellationToken)
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(turnContext, recognizerOptions, null, null, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Runs an utterance through a recognizer and returns a strongly-typed recognizer result.
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="dialogContext">dialog context.</param>
/// <param name="activity">activity to recognize.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Analysis of utterance.</returns>
public virtual async Task<T> RecognizeAsync<T>(DialogContext dialogContext, Activity activity, LuisRecognizerOptions recognizerOptions, CancellationToken cancellationToken)
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(dialogContext, activity, recognizerOptions, null, null, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
{
return await RecognizeInternalAsync(turnContext, recognizerOptions, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <param name="dialogContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="activity">activity to recognize.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, LuisRecognizerOptions recognizerOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
{
return await RecognizeInternalAsync(dialogContext, activity, recognizerOptions, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, LuisRecognizerOptions recognizerOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(turnContext, recognizerOptions, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <typeparam name="T">The recognition result type.</typeparam>
/// <param name="dialogContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="activity">activity to recognize.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<T> RecognizeAsync<T>(DialogContext dialogContext, Activity activity, LuisRecognizerOptions recognizerOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
where T : IRecognizerConvert, new()
{
var result = new T();
result.Convert(await RecognizeInternalAsync(dialogContext, activity, recognizerOptions, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false));
return result;
}
/// <summary>
/// Return results of the analysis (Suggested actions and intents).
/// </summary>
/// <remarks>No telemetry is provided when using this method.</remarks>
/// <param name="utterance">utterance to recognize.</param>
/// <param name="recognizerOptions">A <see cref="LuisRecognizerOptions"/> instance to be used by the call.
/// This parameter overrides the default <see cref="LuisRecognizerOptions"/> passed in the constructor.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The LUIS results of the analysis of the current message text in the current turn's context activity.</returns>
public virtual async Task<RecognizerResult> RecognizeAsync(string utterance, LuisRecognizerOptions recognizerOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
recognizerOptions ??= _luisRecognizerOptions;
return await RecognizeInternalAsync(utterance, recognizerOptions, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Invoked prior to a LuisResult being logged.
/// </summary>
/// <param name="recognizerResult">The Luis Results for the call.</param>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns><see cref="Task"/>.</returns>
protected virtual async Task OnRecognizerResultAsync(RecognizerResult recognizerResult, ITurnContext turnContext, Dictionary<string, string> telemetryProperties = null, Dictionary<string, double> telemetryMetrics = null, CancellationToken cancellationToken = default(CancellationToken))
{
var properties = await FillLuisEventPropertiesAsync(recognizerResult, turnContext, telemetryProperties, cancellationToken).ConfigureAwait(false);
// Track the event
_luisRecognizerOptions.TelemetryClient.TrackEvent(LuisTelemetryConstants.LuisResult, properties, telemetryMetrics);
}
/// <summary>
/// Fills the event properties for LuisResult event for telemetry.
/// These properties are logged when the recognizer is called.
/// </summary>
/// <param name="recognizerResult">Last activity sent from user.</param>
/// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// additionalProperties
/// <returns>A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event.</returns>
#pragma warning disable CA1801 // Review unused parameters (we can't remove cancellationToken without breaking binary compat).
protected Task<Dictionary<string, string>> FillLuisEventPropertiesAsync(RecognizerResult recognizerResult, ITurnContext turnContext, Dictionary<string, string> telemetryProperties = null, CancellationToken cancellationToken = default(CancellationToken))
#pragma warning restore CA1801 // Review unused parameters
{
var topTwoIntents = (recognizerResult.Intents.Count > 0) ? recognizerResult.Intents.OrderByDescending(x => x.Value.Score).Take(2).ToArray() : null;
// Add the intent score and conversation id properties
var properties = new Dictionary<string, string>()
{
{ LuisTelemetryConstants.ApplicationIdProperty, _luisRecognizerOptions.Application.ApplicationId },
{ LuisTelemetryConstants.IntentProperty, topTwoIntents?[0].Key ?? string.Empty },
{ LuisTelemetryConstants.IntentScoreProperty, topTwoIntents?[0].Value.Score?.ToString("N2", CultureInfo.InvariantCulture) ?? "0.00" },
{ LuisTelemetryConstants.Intent2Property, (topTwoIntents?.Length > 1) ? topTwoIntents?[1].Key ?? string.Empty : string.Empty },
{ LuisTelemetryConstants.IntentScore2Property, (topTwoIntents?.Length > 1) ? topTwoIntents?[1].Value.Score?.ToString("N2", CultureInfo.InvariantCulture) ?? "0.00" : "0.00" },
{ LuisTelemetryConstants.FromIdProperty, turnContext.Activity.From.Id },
};
if (recognizerResult.Properties.TryGetValue("sentiment", out var sentiment) && sentiment is JObject)
{
if (((JObject)sentiment).TryGetValue("label", out var label))
{
properties.Add(LuisTelemetryConstants.SentimentLabelProperty, label.Value<string>());
}
if (((JObject)sentiment).TryGetValue("score", out var score))
{
properties.Add(LuisTelemetryConstants.SentimentScoreProperty, score.Value<string>());
}
}
var entities = recognizerResult.Entities?.ToString();
properties.Add(LuisTelemetryConstants.EntitiesProperty, entities);
// Use the LogPersonalInformation flag to toggle logging PII data, text is a common example
if (LogPersonalInformation && !string.IsNullOrEmpty(turnContext.Activity.Text))
{
properties.Add(LuisTelemetryConstants.QuestionProperty, turnContext.Activity.Text);
}
// Additional Properties can override "stock" properties.
if (telemetryProperties != null)
{
return Task.FromResult(telemetryProperties.Concat(properties)
.GroupBy(kv => kv.Key)
.ToDictionary(g => g.Key, g => g.First().Value));
}
return Task.FromResult(properties);
}
/// <summary>
/// Returns a LuisRecognizerOptions object with the correspondig version.
/// If no V2 LuisPredictionoption passed it sets the recognizer to use Luis V3 endpoint.
/// This exists to maintain backwards compatibility with existing constructors.
/// </summary>
/// <param name="application">LuisAplication object to initialize LuisReognizerOptions.</param>
/// <param name="options">If passed a LuisRecognizerOptionsV2 will be returned initialized with this object.</param>
/// <param name="includeAPIResults">Boolean value to initialize IncludeAPIResults .</param>
/// <returns>LuisRecognizerOptions object.</returns>
private static LuisRecognizerOptions BuildLuisRecognizerOptionsV2(LuisApplication application, LuisPredictionOptions options, bool includeAPIResults)
{
if (options == null)
{
return new LuisRecognizerOptionsV3(application)
{
IncludeAPIResults = includeAPIResults,
};
}
var luisVersionOptions = new LuisRecognizerOptionsV2(application)
{
PredictionOptions = options,
#pragma warning disable CS0618 // Type or member is obsolete
TelemetryClient = options.TelemetryClient,
Timeout = options.Timeout,
LogPersonalInformation = options.LogPersonalInformation,
#pragma warning restore CS0618 // Type or member is obsolete
IncludeAPIResults = includeAPIResults
};
return luisVersionOptions;
}
/// <summary>
/// Returns a RecognizerResult object.
/// </summary>
/// <param name="turnContext">Dialog turn Context.</param>
/// <param name="predictionOptions">LuisRecognizerOptions implementation to override current properties.</param>
/// <param name="telemetryProperties"> Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>RecognizerResult object.</returns>
private async Task<RecognizerResult> RecognizeInternalAsync(ITurnContext turnContext, LuisRecognizerOptions predictionOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics, CancellationToken cancellationToken)
{
var recognizer = predictionOptions ?? _luisRecognizerOptions;
var cached = turnContext.TurnState.Get<RecognizerResult>(_cacheKey);
if (cached == null)
{
var result = await recognizer.RecognizeInternalAsync(turnContext, HttpClient, cancellationToken).ConfigureAwait(false);
await OnRecognizerResultAsync(result, turnContext, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);
turnContext.TurnState.Set(_cacheKey, result);
_luisRecognizerOptions.TelemetryClient.TrackEvent("Luis result cached", telemetryProperties, telemetryMetrics);
return result;
}
_luisRecognizerOptions.TelemetryClient.TrackEvent("Read from cached Luis result", telemetryProperties, telemetryMetrics);
return cached;
}
/// <summary>
/// Returns a RecognizerResult object.
/// </summary>
/// <param name="dialogContext">Dialog turn Context.</param>
/// <param name="activity">activity to recognize.</param>
/// <param name="predictionOptions">LuisRecognizerOptions implementation to override current properties.</param>
/// <param name="telemetryProperties"> Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>RecognizerResult object.</returns>
private async Task<RecognizerResult> RecognizeInternalAsync(DialogContext dialogContext, Activity activity, LuisRecognizerOptions predictionOptions, Dictionary<string, string> telemetryProperties, Dictionary<string, double> telemetryMetrics, CancellationToken cancellationToken)
{
var recognizer = predictionOptions ?? _luisRecognizerOptions;
var turnContext = dialogContext.Context;
var cached = turnContext.TurnState.Get<RecognizerResult>(_cacheKey);
if (cached == null)
{
var result = await recognizer.RecognizeInternalAsync(dialogContext, activity, HttpClient, cancellationToken).ConfigureAwait(false);
await OnRecognizerResultAsync(result, dialogContext.Context, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);
turnContext.TurnState.Set(_cacheKey, result);
_luisRecognizerOptions.TelemetryClient.TrackEvent("Luis result cached", telemetryProperties, telemetryMetrics);
return result;
}
_luisRecognizerOptions.TelemetryClient.TrackEvent("Read from cached Luis result", telemetryProperties, telemetryMetrics);
return cached;
}
/// <summary>
/// Returns a RecognizerResult object.
/// </summary>
/// <param name="utterance">utterance to recognize.</param>
/// <param name="predictionOptions">LuisRecognizerOptions implementation to override current properties.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>RecognizerResult object.</returns>
private async Task<RecognizerResult> RecognizeInternalAsync(string utterance, LuisRecognizerOptions predictionOptions, CancellationToken cancellationToken)
{
var recognizer = predictionOptions ?? _luisRecognizerOptions;
var result = await recognizer.RecognizeInternalAsync(utterance, HttpClient, cancellationToken).ConfigureAwait(false);
return result;
}
/// <summary>
/// Returns a LuisRecognizerOptionsV2.
/// This exists to maintain backwards compatibility with existing constructors.
/// </summary>
/// <param name="overridenOptions">LuisPredictionOptions object to initialize or merge with existing LuisReognizerOptions.</param>
/// <returns>LuisRecognizerOptions object.</returns>
private LuisRecognizerOptions MergeDefaultOptionsWithProvidedOptionsV2(LuisPredictionOptions overridenOptions)
{
var instanceLuisRecognizer = _luisRecognizerOptions as LuisRecognizerOptionsV2;
var defaultOptions = instanceLuisRecognizer != null ? instanceLuisRecognizer.PredictionOptions : new LuisPredictionOptions();
var overrideV2 = new LuisPredictionOptions()
{
BingSpellCheckSubscriptionKey = overridenOptions.BingSpellCheckSubscriptionKey ?? defaultOptions.BingSpellCheckSubscriptionKey,
IncludeAllIntents = overridenOptions.IncludeAllIntents ?? defaultOptions.IncludeAllIntents,
IncludeInstanceData = overridenOptions.IncludeInstanceData ?? defaultOptions.IncludeInstanceData,
Log = overridenOptions.Log ?? defaultOptions.Log,
SpellCheck = overridenOptions.SpellCheck ?? defaultOptions.SpellCheck,
Staging = overridenOptions.Staging ?? defaultOptions.Staging,
TimezoneOffset = overridenOptions.TimezoneOffset ?? defaultOptions.TimezoneOffset,
};
return BuildLuisRecognizerOptionsV2(_luisRecognizerOptions.Application, overrideV2, _luisRecognizerOptions.IncludeAPIResults);
}
private DelegatingHandler CreateHttpHandlerPipeline(HttpClientHandler httpClientHandler, params DelegatingHandler[] handlers)
{
// Now, the RetryAfterDelegatingHandler should be the absolute outermost handler
// because it's extremely lightweight and non-interfering
DelegatingHandler currentHandler =
#pragma warning disable CA2000 // Dispose objects before losing scope (suppressing this warning, for now! we will address this once we implement HttpClientFactory in a future release)
new RetryDelegatingHandler(new RetryAfterDelegatingHandler { InnerHandler = httpClientHandler });
#pragma warning restore CA2000 // Dispose objects before losing scope
if (handlers != null)
{
for (var i = handlers.Length - 1; i >= 0; --i)
{
var handler = handlers[i];
// Non-delegating handlers are ignored since we always
// have RetryDelegatingHandler as the outer-most handler
while (handler.InnerHandler is DelegatingHandler)
{
handler = handler.InnerHandler as DelegatingHandler;
}
handler.InnerHandler = currentHandler;
currentHandler = handlers[i];
}
}
return currentHandler;
}
private HttpClientHandler CreateRootHandler() => new HttpClientHandler();
}
}