-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
PersonalizerClient.cs
664 lines (630 loc) · 35.2 KB
/
PersonalizerClient.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Rl.Net;
namespace Azure.AI.Personalizer
{
/// <summary> The Personalizer service client for single and multi slot Rank, Reward and Event Activation. </summary>
///<see href="https://docs.microsoft.com/azure/cognitive-services/personalizer/what-is-personalizer"/>
public class PersonalizerClient
{
private readonly ClientDiagnostics clientDiagnostics;
private readonly HttpPipeline pipeline;
private readonly bool useLocalInference;
private string stringEndpoint;
private AzureKeyCredential azureKeyCredential;
private TokenCredential tokenCredential;
private int liveModelRefreshTimeInMinutes = 15;
private DateTimeOffset tokenExpiry;
private DateTimeOffset liveModelLastRefresh;
private string[] scopes = { "https://cognitiveservices.azure.com/.default" };
private float subsampleRate = 1.0f;
private Lazy<RlNetProcessor> rlNetProcessor;
internal RankRestClient RankRestClient { get; set; }
internal EventsRestClient EventsRestClient { get; set; }
internal MultiSlotRestClient MultiSlotRestClient { get; set; }
internal MultiSlotEventsRestClient MultiSlotEventsRestClient { get; set; }
internal ServiceConfigurationRestClient ServiceConfigurationRestClient { get; set; }
internal PolicyRestClient PolicyRestClient { get; set; }
internal PersonalizerServiceProperties personalizerServiceProperties { get; set; }
internal PersonalizerPolicy personalizerPolicy { get; set; }
/// <summary> Initializes a new instance of Personalizer Client for mocking. </summary>
protected PersonalizerClient()
{
}
/// <summary> Initializes a new instance of PersonalizerClient. </summary>
/// <param name="endpoint"> Supported Cognitive Services endpoint. </param>
/// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
/// <param name="options"> The options for configuring the client. </param>
public PersonalizerClient(Uri endpoint, TokenCredential credential, PersonalizerClientOptions options = null)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (credential == null)
{
throw new ArgumentNullException(nameof(credential));
}
options ??= new PersonalizerClientOptions();
clientDiagnostics = new ClientDiagnostics(options);
pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, scopes));
stringEndpoint = endpoint.AbsoluteUri;
RankRestClient = new RankRestClient(clientDiagnostics, pipeline, stringEndpoint);
EventsRestClient = new EventsRestClient(clientDiagnostics, pipeline, stringEndpoint);
MultiSlotRestClient = new MultiSlotRestClient(clientDiagnostics, pipeline, stringEndpoint);
MultiSlotEventsRestClient = new MultiSlotEventsRestClient(clientDiagnostics, pipeline, stringEndpoint);
ServiceConfigurationRestClient = new ServiceConfigurationRestClient(clientDiagnostics, pipeline, stringEndpoint);
PolicyRestClient = new PolicyRestClient(clientDiagnostics, pipeline, stringEndpoint);
tokenCredential = credential;
this.useLocalInference = options.UseLocalInference;
if (useLocalInference)
{
validateAndAssignSampleRate(options.SubsampleRate);
//lazy load Rankprocessor
rlNetProcessor = new Lazy<RlNetProcessor>(() => GetConfigurationForRankProcessor());
}
}
/// <summary> Initializes a new instance of PersonalizerClient. </summary>
/// <param name="endpoint"> Supported Cognitive Services endpoint. </param>
/// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
public PersonalizerClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, null) { }
/// <summary> Initializes a new instance of PersonalizerClient. </summary>
/// <param name="endpoint"> Supported Cognitive Services endpoint. </param>
/// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
/// <param name="options"> The options for configuring the client. </param>
public PersonalizerClient(Uri endpoint, AzureKeyCredential credential, PersonalizerClientOptions options = null)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (credential == null)
{
throw new ArgumentNullException(nameof(credential));
}
options ??= new PersonalizerClientOptions();
clientDiagnostics = new ClientDiagnostics(options);
pipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, "Ocp-Apim-Subscription-Key"));
stringEndpoint = endpoint.AbsoluteUri;
RankRestClient = new RankRestClient(clientDiagnostics, pipeline, stringEndpoint);
EventsRestClient = new EventsRestClient(clientDiagnostics, pipeline, stringEndpoint);
MultiSlotRestClient = new MultiSlotRestClient(clientDiagnostics, pipeline, stringEndpoint);
MultiSlotEventsRestClient = new MultiSlotEventsRestClient(clientDiagnostics, pipeline, stringEndpoint);
ServiceConfigurationRestClient = new ServiceConfigurationRestClient(clientDiagnostics, pipeline, stringEndpoint);
PolicyRestClient = new PolicyRestClient(clientDiagnostics, pipeline, stringEndpoint);
azureKeyCredential = credential;
this.useLocalInference = options.UseLocalInference;
if (useLocalInference)
{
validateAndAssignSampleRate(options.SubsampleRate);
//lazy load Rankprocessor
rlNetProcessor = new Lazy<RlNetProcessor>(() => GetConfigurationForRankProcessor());
}
}
/// <summary> Initializes a new instance of PersonalizerClient. </summary>
/// <param name="endpoint"> Supported Cognitive Services endpoint. </param>
/// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
public PersonalizerClient(Uri endpoint, AzureKeyCredential credential) : this(endpoint, credential, null) { }
/// <summary> Initializes a new instance of MultiSlotEventsClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="endpoint"> Supported Cognitive Services endpoint. </param>
internal PersonalizerClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint)
{
string stringEndpoint = endpoint.AbsoluteUri;
RankRestClient = new RankRestClient(clientDiagnostics, pipeline, stringEndpoint);
EventsRestClient = new EventsRestClient(clientDiagnostics, pipeline, stringEndpoint);
MultiSlotRestClient = new MultiSlotRestClient(clientDiagnostics, pipeline, stringEndpoint);
MultiSlotEventsRestClient = new MultiSlotEventsRestClient(clientDiagnostics, pipeline, stringEndpoint);
this.clientDiagnostics = clientDiagnostics;
this.pipeline = pipeline;
}
/// <summary> Submit a Personalizer rank request. Receives a context and a list of actions. Returns which of the provided actions should be used by your application, in rewardActionId. </summary>
/// <param name="options"> A Personalizer Rank request. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<PersonalizerRankResult>> RankAsync(PersonalizerRankOptions options, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.Rank");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Rank(options);
}
else
{
return await RankRestClient.RankAsync(options, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Submit a Personalizer rank request. Receives a context and a list of actions. Returns which of the provided actions should be used by your application, in rewardActionId. </summary>
/// <param name="actions">The set of actions the Personalizer service
/// can pick from.
/// The set should not contain more than 50 actions.
/// The order of the actions does not affect the rank result but the
/// order
/// should match the sequence your application would have used to
/// display them.
/// The first item in the array will be used as Baseline item in
/// Offline evaluations.</param>
/// <param name="contextFeatures">Features of the context used for
/// Personalizer as a dictionary of dictionaries. This depends on the application, and
/// typically includes features about the current user, their
/// device, profile information, aggregated data about time and date, etc.
/// Features should not include personally identifiable information (PII),
/// unique UserIDs, or precise timestamps. Need to be JSON serializable.
/// https://docs.microsoft.com/azure/cognitive-services/personalizer/concepts-features.
/// </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<PersonalizerRankResult>> RankAsync(IEnumerable<PersonalizerRankableAction> actions, IEnumerable<object> contextFeatures, CancellationToken cancellationToken = default)
{
PersonalizerRankOptions options = new PersonalizerRankOptions(actions, contextFeatures);
return await RankAsync(options, cancellationToken).ConfigureAwait(false);
}
/// <summary> Submit a Personalizer rank request. Receives a context and a list of actions. Returns which of the provided actions should be used by your application, in rewardActionId. </summary>
/// <param name="options"> A Personalizer Rank request. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<PersonalizerRankResult> Rank(PersonalizerRankOptions options, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.Rank");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Rank(options);
}
else
{
return RankRestClient.Rank(options, cancellationToken);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Submit a Personalizer rank request. Receives a context and a list of actions. Returns which of the provided actions should be used by your application, in rewardActionId. </summary>
/// <param name="actions">The set of actions the Personalizer service
/// can pick from.
/// The set should not contain more than 50 actions.
/// The order of the actions does not affect the rank result but the
/// order
/// should match the sequence your application would have used to
/// display them.
/// The first item in the array will be used as Baseline item in
/// Offline evaluations.</param>
/// <param name="contextFeatures">Features of the context used for
/// Personalizer as a dictionary of dictionaries. This depends on the application, and
/// typically includes features about the current user, their
/// device, profile information, aggregated data about time and date, etc.
/// Features should not include personally identifiable information (PII),
/// unique UserIDs, or precise timestamps. Need to be JSON serializable.
/// https://docs.microsoft.com/azure/cognitive-services/personalizer/concepts-features.
/// </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<PersonalizerRankResult> Rank(IEnumerable<PersonalizerRankableAction> actions, IEnumerable<object> contextFeatures, CancellationToken cancellationToken = default)
{
PersonalizerRankOptions options = new PersonalizerRankOptions(actions, contextFeatures);
return Rank(options, cancellationToken);
}
/// <summary> Submit a Personalizer multi-slot rank request. Receives a context, a list of actions, and a list of slots. Returns which of the provided actions should be used in each slot, in each rewardActionId. </summary>
/// <param name="options"> A Personalizer multi-slot Rank request. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<PersonalizerMultiSlotRankResult>> RankMultiSlotAsync(PersonalizerRankMultiSlotOptions options, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.RankMultiSlot");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Rank(options);
}
else
{
return await MultiSlotRestClient.RankAsync(options, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Submit a Personalizer multi-slot rank request. Receives a context, a list of actions, and a list of slots. Returns which of the provided actions should be used in each slot, in each rewardActionId. </summary>
/// <param name="actions">
/// The set of actions the Personalizer service can pick from.
///
/// The set should not contain more than 50 actions.
///
/// The order of the actions does not affect the rank result but the order
///
/// should match the sequence your application would have used to display them.
///
/// The first item in the array will be used as Baseline item in Offline Evaluations.
/// </param>
/// <param name="slots">
/// The set of slots the Personalizer service should select actions for.
///
/// The set should not contain more than 50 slots.
/// </param>
/// <param name="contextFeatures">Features of the context used for
/// Personalizer as a dictionary of dictionaries. This depends on the application, and
/// typically includes features about the current user, their
/// device, profile information, aggregated data about time and date, etc.
/// Features should not include personally identifiable information (PII),
/// unique UserIDs, or precise timestamps. Need to be JSON serializable.
/// https://docs.microsoft.com/azure/cognitive-services/personalizer/concepts-features.
/// </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<PersonalizerMultiSlotRankResult>> RankMultiSlotAsync(IEnumerable<PersonalizerRankableAction> actions, IEnumerable<PersonalizerSlotOptions> slots, IList<object> contextFeatures, CancellationToken cancellationToken = default)
{
PersonalizerRankMultiSlotOptions options = new PersonalizerRankMultiSlotOptions(actions, slots, contextFeatures);
return await RankMultiSlotAsync(options, cancellationToken).ConfigureAwait(false);
}
/// <summary> Submit a Personalizer multi-slot rank request. Receives a context, a list of actions, and a list of slots. Returns which of the provided actions should be used in each slot, in each rewardActionId. </summary>
/// <param name="options"> A Personalizer multi-slot Rank request. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<PersonalizerMultiSlotRankResult> RankMultiSlot(PersonalizerRankMultiSlotOptions options, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.RankMultiSlot");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Rank(options);
}
else
{
return MultiSlotRestClient.Rank(options, cancellationToken);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Submit a Personalizer multi-slot rank request. Receives a context, a list of actions, and a list of slots. Returns which of the provided actions should be used in each slot, in each rewardActionId. </summary>
/// <param name="actions">
/// The set of actions the Personalizer service can pick from.
///
/// The set should not contain more than 50 actions.
///
/// The order of the actions does not affect the rank result but the order
///
/// should match the sequence your application would have used to display them.
///
/// The first item in the array will be used as Baseline item in Offline Evaluations.
/// </param>
/// <param name="slots">
/// The set of slots the Personalizer service should select actions for.
///
/// The set should not contain more than 50 slots.
/// </param>
/// <param name="contextFeatures">Features of the context used for
/// Personalizer as a dictionary of dictionaries. This depends on the application, and
/// typically includes features about the current user, their
/// device, profile information, aggregated data about time and date, etc.
/// Features should not include personally identifiable information (PII),
/// unique UserIDs, or precise timestamps. Need to be JSON serializable.
/// https://docs.microsoft.com/azure/cognitive-services/personalizer/concepts-features.
/// </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<PersonalizerMultiSlotRankResult> RankMultiSlot(IEnumerable<PersonalizerRankableAction> actions, IEnumerable<PersonalizerSlotOptions> slots, IList<object> contextFeatures, CancellationToken cancellationToken = default)
{
PersonalizerRankMultiSlotOptions options = new PersonalizerRankMultiSlotOptions(actions, slots, contextFeatures);
return RankMultiSlot(options, cancellationToken);
}
/// <summary> Report reward between 0 and 1 that resulted from using the action specified in rewardActionId, for the specified event. </summary>
/// <param name="eventId"> The event id this reward applies to. </param>
/// <param name="reward"> The reward should be a floating point number, typically between 0 and 1. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response> RewardAsync(string eventId, float reward, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.Reward");
scope.Start();
try
{
PersonalizerRewardOptions rewardOptions = new PersonalizerRewardOptions(reward);
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Reward(eventId, reward);
}
else
{
return await EventsRestClient.RewardAsync(eventId, rewardOptions, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Report reward between 0 and 1 that resulted from using the action specified in rewardActionId, for the specified event. </summary>
/// <param name="eventId"> The event id this reward applies to. </param>
/// <param name="reward"> The reward should be a floating point number, typically between 0 and 1. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response Reward(string eventId, float reward, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.Reward");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Reward(eventId, reward);
}
else
{
PersonalizerRewardOptions rewardOptions = new PersonalizerRewardOptions(reward);
return EventsRestClient.Reward(eventId, rewardOptions, cancellationToken);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Report reward that resulted from using the action specified in rewardActionId for the slot. </summary>
/// <param name="eventId"> The event id this reward applies to. </param>
/// <param name="options"> List of slot id and reward values. The reward should be a floating point number, typically between 0 and 1. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response> RewardMultiSlotAsync(string eventId, PersonalizerRewardMultiSlotOptions options, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.RewardMultiSlot");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.RewardMultiSlot(eventId, options.Reward);
}
else
{
return await MultiSlotEventsRestClient.RewardAsync(eventId, options, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Report reward that resulted from using the action specified in rewardActionId for the slot. </summary>
/// <param name="eventId"> The event id this reward applies to. </param>
/// <param name="slotId"> Slot id for which we are sending the reward. </param>
/// <param name="reward"> Reward to be assigned to slotId. Value should be between -1 and 1 inclusive. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response> RewardMultiSlotAsync(string eventId, string slotId, float reward, CancellationToken cancellationToken = default)
{
PersonalizerRewardMultiSlotOptions options = new PersonalizerRewardMultiSlotOptions(new List<PersonalizerSlotReward> { new PersonalizerSlotReward(slotId, reward) });
return await RewardMultiSlotAsync(eventId, options, cancellationToken).ConfigureAwait(false);
}
/// <summary> Report reward that resulted from using the action specified in rewardActionId for the slot. </summary>
/// <param name="eventId"> The event id this reward applies to. </param>
/// <param name="options"> List of slot id and reward values. The reward should be a floating point number, typically between 0 and 1. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response RewardMultiSlot(string eventId, PersonalizerRewardMultiSlotOptions options, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.RewardMultiSlot");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.RewardMultiSlot(eventId, options.Reward);
}
else
{
return MultiSlotEventsRestClient.Reward(eventId, options, cancellationToken);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Report reward that resulted from using the action specified in rewardActionId for the slot. </summary>
/// <param name="eventId"> The event id this reward applies to. </param>
/// <param name="slotId"> Slot id for which we are sending the reward. </param>
/// <param name="reward"> Reward to be assigned to slotId. Value should be between -1 and 1 inclusive. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response RewardMultiSlot(string eventId, string slotId, float reward, CancellationToken cancellationToken = default)
{
PersonalizerRewardMultiSlotOptions options = new PersonalizerRewardMultiSlotOptions(new List<PersonalizerSlotReward> { new PersonalizerSlotReward(slotId, reward) });
return RewardMultiSlot(eventId, options, cancellationToken);
}
/// <summary> Report that the specified event was actually used (e.g. by being displayed to the user) and a reward should be expected for it. </summary>
/// <param name="eventId"> The event ID to be activated. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response> ActivateAsync(string eventId, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.Activate");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Activate(eventId);
}
else
{
return await EventsRestClient.ActivateAsync(eventId, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Report that the specified event was actually used (e.g. by being displayed to the user) and a reward should be expected for it. </summary>
/// <param name="eventId"> The event ID to be activated. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response Activate(string eventId, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.Activate");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Activate(eventId);
}
else
{
return EventsRestClient.Activate(eventId, cancellationToken);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Report that the specified event was actually used or displayed to the user and a rewards should be expected for it. </summary>
/// <param name="eventId"> The event ID this activation applies to. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response> ActivateMultiSlotAsync(string eventId, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.ActivateMultiSlot");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Activate(eventId);
}
else
{
return await MultiSlotEventsRestClient.ActivateAsync(eventId, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Report that the specified event was actually used or displayed to the user and a rewards should be expected for it. </summary>
/// <param name="eventId"> The event ID this activation applies to. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response ActivateMultiSlot(string eventId, CancellationToken cancellationToken = default)
{
using var scope = clientDiagnostics.CreateScope("PersonalizerClient.ActivateMultiSlot");
scope.Start();
try
{
if (useLocalInference)
{
validateAndUpdateLiveModelConfig();
return rlNetProcessor.Value.Activate(eventId);
}
else
{
return MultiSlotEventsRestClient.Activate(eventId, cancellationToken);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the rank processor initiated with live model to use </summary>
internal virtual RlNetProcessor GetConfigurationForRankProcessor(CancellationToken cancellationToken = default)
{
Configuration config = new Configuration();
// set up the model
if (azureKeyCredential != null)
{
config["http.api.key"] = azureKeyCredential.Key;
}
else if (tokenCredential != null)
{
var tokenRequestContext = new TokenRequestContext(scopes);
AccessToken token = tokenCredential.GetToken(tokenRequestContext, cancellationToken);
config["http.api.key"] = "Bearer " + token.Token;
config["http.api.header.key.name"] = "Authorization";
tokenExpiry = token.ExpiresOn;
}
else
{
throw new ApplicationException("PersonalizerClient is neither initalized with Token Credential nor with AzureKey Credential");
}
personalizerServiceProperties = ServiceConfigurationRestClient.Get(cancellationToken);
personalizerPolicy = PolicyRestClient.Get(cancellationToken);
//interactions & observations
config["interaction.http.api.host"] = stringEndpoint + "personalizer/v1.1-preview.3/logs/interactions";
config["observation.http.api.host"] = stringEndpoint + "personalizer/v1.1-preview.3/logs/observations";
config["interaction.sender.implementation"] = "INTERACTION_HTTP_API_SENDER";
config["observation.sender.implementation"] = "OBSERVATION_HTTP_API_SENDER";
config["interaction.subsample.rate"] = Convert.ToString(this.subsampleRate, CultureInfo.InvariantCulture);
config["observation.subsample.rate"] = Convert.ToString(this.subsampleRate, CultureInfo.InvariantCulture);
//model
config["model.blob.uri"] = stringEndpoint + "personalizer/v1.1-preview.3/model";
config["model.source"] = "HTTP_MODEL_DATA";
config["model.vw.initial_command_line"] = personalizerPolicy.Arguments;
config["protocol.version"] = "2";
config["initial_exploration.epsilon"] = Convert.ToString(personalizerServiceProperties.ExplorationPercentage, CultureInfo.InvariantCulture);
config["rank.learning.mode"] = Convert.ToString(personalizerServiceProperties.LearningMode, CultureInfo.InvariantCulture);
LiveModel liveModel = new LiveModel(config);
liveModel.Init();
LiveModelBase liveModelAdapter = new LiveModelAdapter(liveModel);
liveModelLastRefresh = DateTimeOffset.UtcNow;
return new RlNetProcessor(liveModelAdapter);
}
/// <summary> Update the config details periodically based on liveModelRefreshTimeInMinutes or when bearer token is expired </summary>
private void validateAndUpdateLiveModelConfig()
{
if ((tokenCredential != null &&
DateTimeOffset.Compare(tokenExpiry, DateTimeOffset.MinValue) != 0 &&
DateTimeOffset.Compare(tokenExpiry, DateTimeOffset.UtcNow) <= 0) ||
(DateTimeOffset.Compare(liveModelLastRefresh, DateTimeOffset.MinValue) != 0 &&
DateTimeOffset.Compare(liveModelLastRefresh.AddMinutes(liveModelRefreshTimeInMinutes), DateTimeOffset.UtcNow) < 0))
{
rlNetProcessor = new Lazy<RlNetProcessor>(() => GetConfigurationForRankProcessor());
}
}
/// <summary> validate SubsampleRate input from user and throw exception if not in range </summary>
private void validateAndAssignSampleRate(float subsampleRate)
{
if (0 >= subsampleRate || subsampleRate > 1)
{
throw new ArgumentOutOfRangeException(nameof(subsampleRate), "Percentage should be between (0,1]");
}
this.subsampleRate = subsampleRate;
}
}
}