/// <summary> /// Initializes the personalization client. /// </summary> /// <param name="url">Azure endpoint</param> /// <param name="serviceKey">subscription key</param> /// <returns>Personalization client instance</returns> private static PersonalizationClient InitializePersonalizationClient(Uri url, string serviceKey) { PersonalizationClient client = new PersonalizationClient(url, new ApiKeyServiceClientCredentials(serviceKey), new DelegatingHandler[] { }); return(client); }
public PersonalizationClientTests() { _uid = "9a2ccdefb89a46ef"; _sid = "a49589bb29e6c18a"; var projectId = new Guid("462517ce-9dbf-44f0-a57b-22b9d50747fd"); var apiKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJ1c3JfMHZRWm12OHFYcUpmSWhzZmRUVW1FViIsInBpZCI6IjQ2MjUxN2NlLTlkYmYtNDRmMC1hNTdiLTIyYjlkNTA3NDdmZCIsImp0aSI6Ing5TjVURGJqd1BCdUZ5bXIiLCJhdWQiOiJlbmdhZ2UtYXBpLmtlbnRpY29jbG91ZC5jb20ifQ.IvaiOpLYs-UW54l2sagxkDH6VwynZX8G4D4Yx-wYTjw"; _client = new PersonalizationClient(apiKey, projectId); }
public HomeController() { // Disable personalization when PersonalizationToken is not set var personalizationToken = ConfigurationManager.AppSettings["PersonalizationToken"]; if (!string.IsNullOrWhiteSpace(personalizationToken)) { personalizationClient = new PersonalizationClient(personalizationToken); } }
public HomeController() { // Disable personalization when PersonalizationToken is not set var personalizationToken = ConfigurationManager.AppSettings["PersonalizationToken"]; if (!string.IsNullOrWhiteSpace(personalizationToken) && AppSettingProvider.ProjectId.HasValue) { personalizationClient = new PersonalizationClient(personalizationToken, AppSettingProvider.ProjectId.Value); } }
private async Task RewardAsync(ITurnContext turnContext, string eventId, double reward, CancellationToken cancellationToken) { await turnContext.SendActivityAsync( "===== DEBUG MESSAGE CALL REWARD =====\n" + "Calling Reward:\n" + $"eventId = {eventId}, reward = {reward}\n", cancellationToken : cancellationToken); var client = new PersonalizationClient( new ApiKeyServiceClientCredentials(_rlFeaturesManager.SubscriptionKey), new DelegatingHandler[] { }) { BaseUri = _rlFeaturesManager.RLFeatures.HostName }; await client.RewardAsync(eventId, new RewardRequest(reward), cancellationToken); }
private async Task <RankResponse> ChooseRankAsync(ITurnContext turnContext, string eventId, CancellationToken cancellationToken) { var client = new PersonalizationClient( new ApiKeyServiceClientCredentials(_rlFeaturesManager.SubscriptionKey), new DelegatingHandler[] { }) { BaseUri = _rlFeaturesManager.RLFeatures.HostName }; IList <object> contextFeature = new List <object> { new { weather = _rlFeaturesManager.RLFeatures.Weather.ToString() }, new { dayofweek = _rlFeaturesManager.RLFeatures.DayOfWeek.ToString() }, }; Random rand = new Random(DateTime.UtcNow.Millisecond); IList <RankableAction> actions = new List <RankableAction>(); var coffees = Enum.GetValues(typeof(Coffees)); var beansOrigin = Enum.GetValues(typeof(CoffeeBeansOrigin)); var organic = Enum.GetValues(typeof(Organic)); var roast = Enum.GetValues(typeof(CoffeeRoast)); var teas = Enum.GetValues(typeof(Teas)); foreach (var coffee in coffees) { actions.Add(new RankableAction { Id = coffee.ToString(), Features = new List <object>() { new { BeansOrigin = beansOrigin.GetValue(rand.Next(0, beansOrigin.Length)).ToString() }, new { Organic = organic.GetValue(rand.Next(0, organic.Length)).ToString() }, new { Roast = roast.GetValue(rand.Next(0, roast.Length)).ToString() }, }, }); } foreach (var tea in teas) { actions.Add(new RankableAction { Id = tea.ToString(), Features = new List <object>() { new { Organic = organic.GetValue(rand.Next(0, organic.Length)).ToString() }, }, }); } var request = new RankRequest(actions, contextFeature, null, eventId); await turnContext.SendActivityAsync( "===== DEBUG MESSAGE CALL TO RANK =====\n" + "This is what is getting sent to Rank:\n" + $"{JsonConvert.SerializeObject(request, Formatting.Indented)}\n", cancellationToken : cancellationToken); var response = await client.RankAsync(request, cancellationToken); await turnContext.SendActivityAsync( $"===== DEBUG MESSAGE RETURN FROM RANK =====\n" + "This is what Rank returned:\n" + $"{JsonConvert.SerializeObject(response, Formatting.Indented)}\n", cancellationToken : cancellationToken); return(response); }
private static void Main(string[] args) { int iteration = 1; bool runLoop = true; // Initialize Personalization client. PersonalizationClient client = InitializePersonalizationClient(new Uri(ServiceEndpoint)); // Initialize the RSS Feed actions provider IActionProvider actionProvider = new RSSFeedActionProvider(new RSSParser { // Number of items to fetch while crawling the RSS feed ItemLimit = 2 }); // Initialize the Cognitive Services TextAnalyticsClient for featurizing the crawled action articles ITextAnalyticsClient textAnalyticsClient = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(cognitiveTextAnalyticsSubscriptionKey)) { // Cognitive Service Endpoint Endpoint = cognitiveTextAnalyticsEndpoint.Split("/text/analytics")[0] }; // Initialize the Cognitive Text Analytics actions featurizer IActionFeaturizer actionFeaturizer = new CognitiveTextAnalyticsFeaturizer(new CognitiveTextAnalyzer(textAnalyticsClient)); var newsActions = new List <RankableAction>(); foreach (var newsTopic in newsRSSFeeds) { Console.WriteLine($"Fetching Actions for: {newsTopic.Key} from {newsTopic.Value}"); IList <CrawlAction> crawlActions = actionProvider.GetActionsAsync(newsTopic.Value).Result.ToList(); Console.WriteLine($"Fetched {crawlActions.Count} actions"); actionFeaturizer.FeaturizeActionsAsync(crawlActions).Wait(10000); Console.WriteLine($"Featurized actions for {newsTopic.Key}"); // Generate a rankable action for each crawlAction and add the news topic as additional feature newsActions.AddRange(crawlActions.Select(a => { a.Features.Add(new { topic = newsTopic.Key }); return((RankableAction)a); }).ToList()); } do { Console.WriteLine("Iteration: " + iteration++); // Get context information from the user. string username = GetUserName(); string timeOfDay = GetUsersTimeOfDay(); string location = GetLocation(); // Create current context from user specified data. IList <object> currentContext = new List <object>() { new { username }, new { timeOfDay }, new { location } }; // Id to associate with the request string eventId = Guid.NewGuid().ToString(); // Rank the actions var request = new RankRequest(newsActions, currentContext, null, eventId); RankResponse response = client.Rank(request); var recommendedAction = newsActions.Where(a => a.Id.Equals(response.RewardActionId)).FirstOrDefault(); Console.WriteLine("Personalization service thinks you would like to read: "); Console.WriteLine("Id: " + recommendedAction.Id); Console.WriteLine("Features : " + JsonConvert.SerializeObject(recommendedAction.Features, Formatting.Indented)); Console.WriteLine("Do you like this article ?(y/n)"); float reward = 0.0f; string answer = GetKey(); if (answer == "Y") { reward = 1; Console.WriteLine("Great!"); } else if (answer == "N") { reward = 0; Console.WriteLine("You didn't like the recommended news article."); } else { Console.WriteLine("Entered choice is invalid. Service assumes that you didn't like the recommended news article."); } Console.WriteLine("Personalization service ranked the actions with the probabilities as below:"); Console.WriteLine("{0, 10} {1, 0}", "Probability", "Id"); var rankedResponses = response.Ranking.OrderByDescending(r => r.Probability); foreach (var rankedResponse in rankedResponses) { Console.WriteLine("{0, 10} {1, 0}", rankedResponse.Probability, rankedResponse.Id); } // Send the reward for the action based on user response. client.Reward(response.EventId, new RewardRequest(reward)); Console.WriteLine("Press q to break, any other key to continue:"); runLoop = !(GetKey() == "Q"); } while (runLoop); }