-
Notifications
You must be signed in to change notification settings - Fork 558
Expand file tree
/
Copy pathpersonalizer-quickstart.cs
More file actions
412 lines (358 loc) · 14 KB
/
personalizer-quickstart.cs
File metadata and controls
412 lines (358 loc) · 14 KB
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
// <snippet_1>
using Microsoft.Azure.CognitiveServices.Personalizer;
using Microsoft.Azure.CognitiveServices.Personalizer.Models;
class Program
{
private static readonly string ApiKey = "REPLACE_WITH_YOUR_PERSONALIZER_KEY";
private static readonly string ServiceEndpoint = "REPLACE_WITH_YOUR_ENDPOINT_URL";
static PersonalizerClient InitializePersonalizerClient(string url)
{
PersonalizerClient client = new PersonalizerClient(
new ApiKeyServiceClientCredentials(ApiKey))
{ Endpoint = url };
return client;
}
static Dictionary<string, ActionFeatures> actions = new Dictionary<string, ActionFeatures>
{
{"pasta", new ActionFeatures(
new BrandInfo(company: "pasta_inc"),
new ItemAttributes(
quantity: 1,
category: "Italian",
price: 12),
new DietaryAttributes(
vegan: false,
lowCarb: false,
highProtein: false,
vegetarian: false,
lowFat: true,
lowSodium: true))},
{"bbq", new ActionFeatures(
new BrandInfo(company: "ambisco"),
new ItemAttributes(
quantity: 2,
category: "bbq",
price: 20),
new DietaryAttributes(
vegan: false,
lowCarb: true,
highProtein: true,
vegetarian: false,
lowFat: false,
lowSodium: false))},
{"bao", new ActionFeatures(
new BrandInfo(company: "bao_and_co"),
new ItemAttributes(
quantity: 4,
category: "Chinese",
price: 8),
new DietaryAttributes(
vegan: false,
lowCarb: true,
highProtein: true,
vegetarian: false,
lowFat: true,
lowSodium: false))},
{"hummus", new ActionFeatures(
new BrandInfo(company: "garbanzo_inc"),
new ItemAttributes(
quantity: 1,
category: "Breakfast",
price: 5),
new DietaryAttributes(
vegan: true,
lowCarb: false,
highProtein: true,
vegetarian: true,
lowFat: false,
lowSodium: false))},
{"veg_platter", new ActionFeatures(
new BrandInfo(company: "farm_fresh"),
new ItemAttributes(
quantity: 1,
category: "produce",
price: 7),
new DietaryAttributes(
vegan: true,
lowCarb: true,
highProtein: false,
vegetarian: true,
lowFat: true,
lowSodium: true ))},
};
static IList<RankableAction> GetActions()
{
IList<RankableAction> rankableActions = new List<RankableAction>();
foreach (var action in actions)
{
rankableActions.Add(new RankableAction
{
Id = action.Key,
Features = new List<object>() { action.Value }
});
}
return rankableActions;
}
public class BrandInfo
{
public string Company { get; set; }
public BrandInfo(string company)
{
Company = company;
}
}
public class ItemAttributes
{
public int Quantity { get; set; }
public string Category { get; set; }
public double Price { get; set; }
public ItemAttributes(int quantity, string category, double price)
{
Quantity = quantity;
Category = category;
Price = price;
}
}
public class DietaryAttributes
{
public bool Vegan { get; set; }
public bool LowCarb { get; set; }
public bool HighProtein { get; set; }
public bool Vegetarian { get; set; }
public bool LowFat { get; set; }
public bool LowSodium { get; set; }
public DietaryAttributes(bool vegan, bool lowCarb, bool highProtein, bool vegetarian, bool lowFat, bool lowSodium)
{
Vegan = vegan;
LowCarb = lowCarb;
HighProtein = highProtein;
Vegetarian = vegetarian;
LowFat = lowFat;
LowSodium = lowSodium;
}
}
public class ActionFeatures
{
public BrandInfo BrandInfo { get; set; }
public ItemAttributes ItemAttributes { get; set; }
public DietaryAttributes DietaryAttributes { get; set; }
public ActionFeatures(BrandInfo brandInfo, ItemAttributes itemAttributes, DietaryAttributes dietaryAttributes)
{
BrandInfo = brandInfo;
ItemAttributes = itemAttributes;
DietaryAttributes = dietaryAttributes;
}
}
public static Context GetContext()
{
return new Context(
user: GetRandomUser(),
timeOfDay: GetRandomTimeOfDay(),
location: GetRandomLocation(),
appType: GetRandomAppType());
}
static string[] timesOfDay = new string[] { "morning", "afternoon", "evening" };
static string[] locations = new string[] { "west", "east", "midwest" };
static string[] appTypes = new string[] { "edge", "safari", "edge_mobile", "mobile_app" };
static IList<UserProfile> users = new List<UserProfile>
{
new UserProfile(
name: "Bill",
dietaryPreferences: new Dictionary<string, bool> { { "low_carb", true } },
avgOrderPrice: "0-20"),
new UserProfile(
name: "Satya",
dietaryPreferences: new Dictionary<string, bool> { { "low_sodium", true} },
avgOrderPrice: "201+"),
new UserProfile(
name: "Amy",
dietaryPreferences: new Dictionary<string, bool> { { "vegan", true }, { "vegetarian", true } },
avgOrderPrice: "21-50")
};
static string GetRandomTimeOfDay()
{
var random = new Random();
var timeOfDayIndex = random.Next(timesOfDay.Length);
Console.WriteLine($"TimeOfDay: {timesOfDay[timeOfDayIndex]}");
return timesOfDay[timeOfDayIndex];
}
static string GetRandomLocation()
{
var random = new Random();
var locationIndex = random.Next(locations.Length);
Console.WriteLine($"Location: {locations[locationIndex]}");
return locations[locationIndex];
}
static string GetRandomAppType()
{
var random = new Random();
var appIndex = random.Next(appTypes.Length);
Console.WriteLine($"AppType: {appTypes[appIndex]}");
return appTypes[appIndex];
}
static UserProfile GetRandomUser()
{
var random = new Random();
var userIndex = random.Next(users.Count);
Console.WriteLine($"\nUser: {users[userIndex].Name}");
return users[userIndex];
}
public class UserProfile
{
// Mark name as non serializable so that it is not part of the context features
[NonSerialized()]
public string Name;
public Dictionary<string, bool> DietaryPreferences { get; set; }
public string AvgOrderPrice { get; set; }
public UserProfile(string name, Dictionary<string, bool> dietaryPreferences, string avgOrderPrice)
{
Name = name;
DietaryPreferences = dietaryPreferences;
AvgOrderPrice = avgOrderPrice;
}
}
public class Context
{
public UserProfile User { get; set; }
public string TimeOfDay { get; set; }
public string Location { get; set; }
public string AppType { get; set; }
public Context(UserProfile user, string timeOfDay, string location, string appType)
{
User = user;
TimeOfDay = timeOfDay;
Location = location;
AppType = appType;
}
}
public static float GetRewardScore(Context context, string actionId)
{
float rewardScore = 0.0f;
string userName = context.User.Name;
ActionFeatures actionFeatures = actions[actionId];
if (userName.Equals("Bill"))
{
if (actionFeatures.ItemAttributes.Price < 10 && !context.Location.Equals("midwest"))
{
rewardScore = 1.0f;
Console.WriteLine($"\nBill likes to be economical when he's not in the midwest visiting his friend Warren. He bought {actionId} because it was below a price of $10.");
}
else if (actionFeatures.DietaryAttributes.LowCarb && context.Location.Equals("midwest"))
{
rewardScore = 1.0f;
Console.WriteLine($"\nBill is visiting his friend Warren in the midwest. There he's willing to spend more on food as long as it's low carb, so Bill bought {actionId}.");
}
else if (actionFeatures.ItemAttributes.Price >= 10 && !context.Location.Equals("midwest"))
{
Console.WriteLine($"\nBill didn't buy {actionId} because the price was too high when not visting his friend Warren in the midwest.");
}
else if (!actionFeatures.DietaryAttributes.LowCarb && context.Location.Equals("midwest"))
{
Console.WriteLine($"\nBill didn't buy {actionId} because it's not low-carb, and he's in the midwest visitng his friend Warren.");
}
}
else if (userName.Equals("Satya"))
{
if (actionFeatures.DietaryAttributes.LowSodium)
{
rewardScore = 1.0f;
Console.WriteLine($"\nSatya is health conscious, so he bought {actionId} since it's low in sodium.");
}
else
{
Console.WriteLine($"\nSatya did not buy {actionId} because it's not low sodium.");
}
}
else if (userName.Equals("Amy"))
{
if (actionFeatures.DietaryAttributes.Vegan || actionFeatures.DietaryAttributes.Vegetarian)
{
rewardScore = 1.0f;
Console.WriteLine($"\nAmy likes to eat plant-based foods, so she bought {actionId} because it's vegan or vegetarian friendly.");
}
else
{
Console.WriteLine($"\nAmy did not buy {actionId} because it's not vegan or vegetarian.");
}
}
return rewardScore;
}
// ...
// </snippet_1>
//*********************
// <snippet_2>
static void Main(string[] args)
{
int iteration = 1;
bool runLoop = true;
// Get the actions list to choose from personalizer with their features.
IList<RankableAction> actions = GetActions();
// Initialize Personalizer client.
PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint);
do
{
Console.WriteLine("\nIteration: " + iteration++);
// <rank>
// Get context information.
Context context = GetContext();
// Create current context from user specified data.
IList<object> currentContext = new List<object>() {
context
};
// Generate an ID to associate with the request.
string eventId = Guid.NewGuid().ToString();
// Rank the actions
var request = new RankRequest(actions: actions, contextFeatures: currentContext, eventId: eventId);
RankResponse response = client.Rank(request);
// </rank>
Console.WriteLine($"\nPersonalizer service thinks {context.User.Name} would like to have: {response.RewardActionId}.");
// <reward>
float reward = GetRewardScore(context, response.RewardActionId);
// Send the reward for the action based on user response.
client.Reward(response.EventId, new RewardRequest(reward));
// </reward>
Console.WriteLine("\nPress q to break, any other key to continue:");
runLoop = !(GetKey() == "Q");
} while (runLoop);
}
private static string GetKey()
{
return Console.ReadKey().Key.ToString().Last().ToString().ToUpper();
}
}
// </snippet_2>
// <snippet_multi>
static void Main(string[] args)
{
int iteration = 1;
int runLoop = 0;
// Get the actions list to choose from personalizer with their features.
IList<RankableAction> actions = GetActions();
// Initialize Personalizer client.
PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint);
do
{
Console.WriteLine("\nIteration: " + iteration++);
// <rank>
// Get context information.
Context context = GetContext();
// Create current context from user specified data.
IList<object> currentContext = new List<object>() {
context
};
// Generate an ID to associate with the request.
string eventId = Guid.NewGuid().ToString();
// Rank the actions
var request = new RankRequest(actions: actions, contextFeatures: currentContext, eventId: eventId);
RankResponse response = client.Rank(request);
// </rank>
Console.WriteLine($"\nPersonalizer service thinks {context.User.Name} would like to have: {response.RewardActionId}.");
// <reward>
float reward = GetRewardScore(context, response.RewardActionId);
// Send the reward for the action based on user response.
client.Reward(response.EventId, new RewardRequest(reward));
// </reward>
runLoop = runLoop + 1;
} while (runLoop < 1000);
}
// </snippet_multi>