Skip to content

Commit 54c62bb

Browse files
committed
finish rewrite node qs
1 parent b58d53b commit 54c62bb

File tree

1 file changed

+27
-220
lines changed

1 file changed

+27
-220
lines changed

articles/cognitive-services/personalizer/includes/quickstart-sdk-nodejs.md

Lines changed: 27 additions & 220 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,6 @@ ms.custom: cog-serv-seo-aug-2020
1010
ms.date: 02/02/2023
1111
---
1212

13-
You'll need to install the Personalizer client library forN ode.js to:
14-
* Authenticate the quickstart example client with a Personalizer resource in Azure.
15-
* Send context and action features to the Reward API, which will return the best action from the Personalizer model
16-
* Send a reward score to the Rank API and train the Personalizer model.
17-
1813
[Reference documentation](/javascript/api/@azure/cognitiveservices-personalizer) |[Library source code](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/cognitiveservices/cognitiveservices-personalizer) | [Package (npm)](https://www.npmjs.com/package/@azure/cognitiveservices-personalizer) | [Quickstart code sample](https://github.com/Azure-Samples/cognitive-services-quickstart-code/tree/master/javascript/Personalizer)
1914

2015
## Prerequisites
@@ -25,7 +20,7 @@ You'll need to install the Personalizer client library forN ode.js to:
2520
* You'll need the key and endpoint from the resource you create to connect your application to the Personalizer API. You'll paste your key and endpoint into the code below later in the quickstart.
2621
* You can use the free pricing tier (`F0`) to try the service, and upgrade later to a paid tier for production.
2722

28-
## Setting Up
23+
## Model configuration
2924

3025
[!INCLUDE [Change model frequency](change-model-frequency.md)]
3126

@@ -45,28 +40,9 @@ Run the `npm init -y` command to create a `package.json` file.
4540
npm init -y
4641
```
4742

48-
Create a new Node.js application in your preferred editor or IDE named `sample.js` and create variables for your resource's endpoint and subscription key.
49-
50-
[!INCLUDE [Personalizer find resource info](find-azure-resource-info.md)]
51-
52-
> [!IMPORTANT]
53-
> Remember to remove the key from your code when you're done, and never post it publicly. For production, use a secure way of storing and accessing your credentials like [Azure Key Vault](../../../key-vault/general/overview.md). For more information about security see the Cognitive Services [security](../../cognitive-services-security.md) article.
54-
55-
```javascript
56-
const uuidv1 = require('uuid/v1');
57-
const Personalizer = require('@azure/cognitiveservices-personalizer');
58-
const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
59-
const readline = require('readline-sync');
60-
61-
// The key specific to your personalization service instance; e.g. "0123456789abcdef0123456789ABCDEF"
62-
const serviceKey = "<REPLACE-WITH-YOUR-PERSONALIZER-KEY>";
63-
64-
// The endpoint specific to your personalization service instance;
65-
// e.g. https://<your-resource-name>.cognitiveservices.azure.com
66-
const baseUri = "https://<REPLACE-WITH-YOUR-PERSONALIZER-ENDPOINT>.cognitiveservices.azure.com";
67-
```
43+
Create a new Node.js script in your preferred editor or IDE named `personalizer-quickstart.js` and create variables for your resource's endpoint and subscription key. TBD
6844

69-
### Install the Node.js library for Personalizer
45+
### Install the client library
7046

7147
Install the Personalizer client library for Node.js with the following command:
7248

@@ -81,220 +57,51 @@ npm install @azure/ms-rest-azure-js @azure/ms-rest-js readline-sync uuid --save
8157
```
8258

8359

84-
Personalizer is meant to run on applications that receive and interpret real-time data. For the purpose of this quickstart, you'll use sample code to generate imaginary customer actions on a grocery website. The following code block defines three key methods: **getActionsList**, **getContextFeaturesList** and **getReward**.
85-
86-
87-
88-
## Authenticate the client
89-
90-
Instantiate the `PersonalizerClient` with your `serviceKey` and `baseUri` that you created earlier.
91-
92-
```javascript
93-
const credentials = new CognitiveServicesCredentials(serviceKey);
94-
95-
// Initialize Personalization client.
96-
const personalizerClient = new Personalizer.PersonalizerClient(credentials, baseUri);
97-
```
98-
99-
## Get content choices represented as actions
100-
101-
Actions represent the content choices from which you want Personalizer to select the best content item. Add the following methods to the Program class to represent the set of actions and their features.
102-
103-
```javascript
104-
function getContextFeaturesList() {
105-
const timeOfDayFeatures = ['morning', 'afternoon', 'evening', 'night'];
106-
const tasteFeatures = ['salty', 'sweet'];
107-
108-
let answer = readline.question("\nWhat time of day is it (enter number)? 1. morning 2. afternoon 3. evening 4. night\n");
109-
let selection = parseInt(answer);
110-
const timeOfDay = selection >= 1 && selection <= 4 ? timeOfDayFeatures[selection - 1] : timeOfDayFeatures[0];
111-
112-
answer = readline.question("\nWhat type of food would you prefer (enter number)? 1. salty 2. sweet\n");
113-
selection = parseInt(answer);
114-
const taste = selection >= 1 && selection <= 2 ? tasteFeatures[selection - 1] : tasteFeatures[0];
115-
116-
console.log("Selected features:\n");
117-
console.log("Time of day: " + timeOfDay + "\n");
118-
console.log("Taste: " + taste + "\n");
119-
120-
return [
121-
{
122-
"time": timeOfDay
123-
},
124-
{
125-
"taste": taste
126-
}
127-
];
128-
}
129-
```
130-
131-
```javascript
132-
function getActionsList() {
133-
return [
134-
{
135-
"id": "pasta",
136-
"features": [
137-
{
138-
"taste": "salty",
139-
"spiceLevel": "medium"
140-
},
141-
{
142-
"nutritionLevel": 5,
143-
"cuisine": "italian"
144-
}
145-
]
146-
},
147-
{
148-
"id": "ice cream",
149-
"features": [
150-
{
151-
"taste": "sweet",
152-
"spiceLevel": "none"
153-
},
154-
{
155-
"nutritionalLevel": 2
156-
}
157-
]
158-
},
159-
{
160-
"id": "juice",
161-
"features": [
162-
{
163-
"taste": "sweet",
164-
"spiceLevel": "none"
165-
},
166-
{
167-
"nutritionLevel": 5
168-
},
169-
{
170-
"drink": true
171-
}
172-
]
173-
},
174-
{
175-
"id": "salad",
176-
"features": [
177-
{
178-
"taste": "salty",
179-
"spiceLevel": "low"
180-
},
181-
{
182-
"nutritionLevel": 8
183-
}
184-
]
185-
}
186-
];
187-
}
188-
```
189-
190-
## Create the learning loop
191-
192-
The Personalizer learning loop is a cycle of [Rank](#request-the-best-action) and [Reward](#send-a-reward) calls. In this quickstart, each Rank call, to personalize the content, is followed by a Reward call to tell Personalizer how well the service performed.
60+
## Code block 1: Generate sample data
19361

194-
The following code loops through a cycle of asking the user their preferences at the command line, sending that information to Personalizer to select the best action, presenting the selection to the customer to choose from among the list, and then sending a reward to Personalizer signaling how well the service did in its selection.
195-
196-
```javascript
197-
let runLoop = true;
198-
199-
do {
200-
201-
let rankRequest = {}
202-
203-
// Generate an ID to associate with the request.
204-
rankRequest.eventId = uuidv1();
205-
206-
// Get context information from the user.
207-
rankRequest.contextFeatures = getContextFeaturesList();
208-
209-
// Get the actions list to choose from personalization with their features.
210-
rankRequest.actions = getActionsList();
211-
212-
// Exclude an action for personalization ranking. This action will be held at its current position.
213-
rankRequest.excludedActions = getExcludedActionsList();
214-
215-
rankRequest.deferActivation = false;
216-
217-
// Rank the actions
218-
const rankResponse = await personalizerClient.rank(rankRequest);
219-
220-
console.log("\nPersonalization service thinks you would like to have:\n")
221-
console.log(rankResponse.rewardActionId);
222-
223-
// Display top choice to user, user agrees or disagrees with top choice
224-
const reward = getReward();
225-
226-
console.log("\nPersonalization service ranked the actions with the probabilities as below:\n");
227-
for (let i = 0; i < rankResponse.ranking.length; i++) {
228-
console.log(JSON.stringify(rankResponse.ranking[i]) + "\n");
229-
}
230-
231-
// Send the reward for the action based on user response.
232-
233-
const rewardRequest = {
234-
value: reward
235-
}
236-
237-
await personalizerClient.events.reward(rankRequest.eventId, rewardRequest);
238-
239-
runLoop = continueLoop();
240-
241-
} while (runLoop);
242-
```
243-
244-
Take a closer look at the rank and reward calls in the following sections.
245-
246-
Add the following methods, which [get the content choices](#get-content-choices-represented-as-actions), before running the code file:
247-
248-
* getActionsList
249-
* getContextFeaturesList
62+
Personalizer is meant to run on applications that receive and interpret real-time data. For the purpose of this quickstart, you'll use sample code to generate imaginary customer actions on a grocery website. The following code block defines three key methods: **getActionsList**, **getContextFeaturesList** and **getReward**.
25063

251-
## Request the best action
64+
- **getActionsList** returns a list of the choices that the grocery website needs to rank. In this example, the actions are meal products. Each action choice has details (features) that may affect user behavior later on. Actions are used as input for the Rank API
25265

253-
To make a Rank request, you'll need to provide: a list of 'RankActions' (_actions_), a list of context features (_context_), an optional list of actions (_excludeActions_) to remove from consideration by Personalizer, and a unique event ID to receive the response.
66+
- **getContextFeaturesList** returns a simulated customer visit. It selects randomized details (context features) like which customer is present and what time of day the visit is taking place. In general, a context represents the current state of your application, system, environment, or user. The context object is used as input for the Rank API.
25467

255-
This quickstart has simple context features of time of day and user food preference. In production systems, determining and [evaluating](../how-to-feature-evaluation.md) [actions and features](../concepts-features.md) can be a non-trivial matter.
68+
The context features in this quickstart are simplistic. However, in a real production system, designing your [features](../concepts-features.md) and [evaluating their effectiveness](../how-to-feature-evaluation.md) is very important. Refer to the linked documentation for guidance.
25669

257-
```javascript
258-
let rankRequest = {}
70+
- **getReward** prompts the user to score the service's recommendation as a success or failure. It returns a score between zero and one that represents the success of a customer interaction. In a real scenario, Personalizer will learn user preferences from realtime customer interactions.
25971

260-
// Generate an ID to associate with the request.
261-
rankRequest.eventId = uuidv1();
72+
In a real production system, the [reward score](../concept-rewards.md) should be designed to align with your business objectives and KPIs. Determining how to calculate the reward metric may require some experimentation.
26273

263-
// Get context information from the user.
264-
rankRequest.contextFeatures = getContextFeaturesList();
74+
1. Find your key and endpoint.
26575

266-
// Get the actions list to choose from personalization with their features.
267-
rankRequest.actions = getActionsList();
76+
[!INCLUDE [Personalizer find resource info](find-azure-resource-info.md)]
26877

269-
// Exclude an action for personalization ranking. This action will be held at its current position.
270-
rankRequest.excludedActions = getExcludedActionsList();
78+
1. Open _personalizer-quickstart.js_ in a text editor or IDE and paste in the code below.
27179

272-
rankRequest.deferActivation = false;
80+
1. 1. Paste your key and endpoint into the code where indicated. Your endpoint has the form `https://<your_resource_name>.cognitiveservices.azure.com/`.
27381

274-
// Rank the actions
275-
const rankResponse = await personalizerClient.rank(rankRequest);
276-
```
82+
> [!IMPORTANT]
83+
> Remember to remove the key from your code when you're done, and never post it publicly. For production, use a secure way of storing and accessing your credentials like [Azure Key Vault](../../../key-vault/general/overview.md). For more information about security see the Cognitive Services [security](../../cognitive-services-security.md) article.
27784
278-
## Send a reward
85+
:::code language="js" source="~/cognitive-services-quickstart-code/javascript/Personalizer/quickstart-sdk/personalizer-quickstart.js" id="snippet_1":::
27986

280-
To get the reward score to send in the Reward request, the program gets the user's selection from the command line, assigns a numeric value to the selection, then sends the unique event ID and the reward score as the numeric value to the Reward API.
87+
## Code block 2: Iterate the learning loop
28188

282-
This quickstart assigns a simple number as a reward score, either a zero or a 1. In production systems, determining when and what to send to the [Reward](../concept-rewards.md) call can be a non-trivial matter, depending on your specific needs.
89+
The next block of code defines the **main** method and closes out the script. It runs a learning loop iteration, in which it asks the user their preferences at the command line and sends that information to Personalizer to select the best action. It presents the selected action to the user, who makes a choice using the command line. Then it sends a reward score to the Personalizer service to signal how well the service did in its selection.
28390

284-
```javascript
285-
const rewardRequest = {
286-
value: reward
287-
}
91+
The Personalizer learning loop is a cycle of **Rank** and **Reward** calls. In this quickstart, each Rank call, to personalize the content, is followed by a Reward call to tell Personalizer how well the service performed.
28892

289-
await personalizerClient.events.reward(rankRequest.eventId, rewardRequest);
290-
```
93+
:::code language="js" source="~/cognitive-services-quickstart-code/javascript/Personalizer/quickstart-sdk/personalizer-quickstart.js" id="snippet_2":::
29194

29295
## Run the program
29396

294-
Run the application with the Node.js from your application directory.
97+
Run the application with the Node.js command from your application directory.
29598

29699
```console
297-
node sample.js
100+
node personalizer-quickstart.js
298101
```
299102

103+
Iterate through a few learning loops. After about 10 minutes, the service will start to show improvements in its recommendations.
104+
300105
![The quickstart program asks a couple of questions to gather user preferences, known as features, then provides the top action.](../media/csharp-quickstart-commandline-feedback-loop/quickstart-program-feedback-loop-example.png)
106+
107+
The source code for this quickstart is available on [GitHub](https://github.com/Azure-Samples/cognitive-services-quickstart-code/blob/master/javascript/Personalizer/quickstart-sdk/personalizer-quickstart.js).

0 commit comments

Comments
 (0)