In dialog trees for voice assistants, you often need to introduce some randomness. If the smart speaker doesn’t always repeat the same phrases, the dialog sounds more natural. Many other use cases exist as well, e.g., you might want to ask the user a random question in a quiz.
Random Block in Voiceflow
However, while this works fine in the Voiceflow testing environment, it currently has issues when using the skill live on Amazon Alexa. Additionally, you might sometimes want to have more control over the process – e.g., pre-set the random choices, store them in a database for advanced logging or tease the next item when the skill ends.
Custom Code for Advanced Random Choices
Once all random numbers between zero and the self-defined max number have been selected once, all choices are re-added.
This method pre-decides the upcoming choices; with this method, you could look at what will be the next choice and integrate this into your dialog design.
Variables in the Skill
To enable this advanced random functionality, set up two variables in your Voiceflow model:
- num_available: a global variable, which is an array containing all the remaining random numbers from 0..max. Global variables are stored and retained over multiple sessions and are unique to each user.
- num_now: a flow variable, which is then defined by Voiceflow and can be set by the custom script to contain the chosen number in this session.
Speech Flow Design
Copy and paste the following code into the new block:
The maximum number (
num_max) is the variable that contains the available choices, ranging from
0 .. < num_max. If you need this to be more flexible, you could of course also create this variable in Voiceflow and set it through a “Set” block.
In Voiceflow, every variable defined in the model is initialized with
0. If the
num_available variable contains this value, this means that the skill was run the first time. The code in the if statement then generates an array with the desired numbers.
To provide the ability to preview the net choice, it’s better to shuffle the numbers right away and always take one item from the array later; instead of taking a random number each time a new one is needed. The function
shuffleArray() is based on the StackOverflow answer by Laurens Holst.
Testing in the Alexa Developer Console
For quick testing, the connected “Speak”-blocks just announce the selected number (stored in the flow variable
num_now). You could of course easily adapt this with an “if condition”-block to switch to different paths in your dialog model.
Next, upload the skill to the Alexa developer console. Repeatedly start the skill to see the generated random numbers. After all numbers have been run through once, all options are available again, in a newly randomized order.