Classify · Voice commands
Route a spoken command to the skill that handles it
“I would like to hear jazz music.” “Have I received new emails in the last ten minutes?” A voice assistant has a fraction of a second to decide which skill a sentence is for, and it has to notice the sentences it has no skill for. Nenya names the intent, quickly, and its confidence tells you when to say “sorry, I cannot do that yet”.
- The move
- Turn a transcribed command into one of your intents, or into “none”.
- The model’s role
- It is the router in front of your skills.
- Why it fits
- Commands are short and there are many ways to say each one. A small model answers in about a seventh of a second.
- How it goes
- Transcript in → the question, the command and your intents in one message → one intent and a confidence → run the skill, or decline.
- Payoff
- Measured: 78.4% right on 250 real commands with twelve intents on offer, and 93.0% on the 57% of commands it was at least 90% sure of. With eight skills and “none” allowed, 85% of the commands that had no skill were caught. About 135 tokens a command.
On this page
The data#
250 commands from MASSIVE 1.1, a public set of things people say to a voice assistant (Amazon; FitzGerald et al. 2022; CC BY 4.0), English test split. Each has the intent its annotators gave it. MASSIVE was kept out of the model’s training on purpose, so these are commands it has no training data for.
Twelve intents:
Which intent does this voice-assistant command express?
- add calendar event or reminder
- ask date or time
- check calendar
- check email
- check weather
- chit-chat or odd request
- factual question
- find recipe
- get news
- play music
- post on social media
- send emailSet up#
pip install openai. The API is free and needs no key.
import json
import math
import time
from pathlib import Path
from openai import OpenAI
client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")The recipe#
The classify function of the API page, unchanged: one user message in the layout the model was trained on, the reply held to your labels, and a confidence from the reply’s token probabilities.
def classify(question, text, labels, heading="Text", descriptions=None, allow_none=False):
"""(label, confidence)"""
options = "\n".join(f"- {label}: {descriptions[label]}" if descriptions else f"- {label}" for label in labels)
prompt = f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\nAnswer with the label only."
if allow_none:
prompt += ' If none of the options fits, answer "none".'
reply = client.chat.completions.create(
model="nenya",
messages=[{"role": "user", "content": prompt}],
temperature=0, # one right answer: do not sample
max_tokens=24,
logprobs=True, # for the confidence
extra_body={"structured_outputs": {"choice": labels + (["none"] if allow_none else [])}},
)
choice = reply.choices[0]
tokens = [t for t in choice.logprobs.content if not t.token.startswith("<|")]
confidence = math.exp(sum(t.logprob for t in tokens))
return choice.message.content, confidenceDATA = json.loads((Path(__file__).parent / "data" / "classify-voice-commands.json").read_text())
QUESTION = DATA["question"]
INTENTS = DATA["labels"] # the twelve things people ask this assistant for
print(QUESTION)
for name in INTENTS:
print(f"- {name}")The request#
command = DATA["examples"][0]
label, confidence = classify(QUESTION, command["text"], INTENTS, heading="Command")
print(f"command: {command['text']}")
print(f"model: {label} ({confidence:.0%} sure)")
print(f"annotator: {command['label']}")The body the function sends:
{
"model": "nenya",
"messages": [
{
"role": "user",
"content": "Which intent does this voice-assistant command express?\n\nCommand:\ni would like to hear jazz music\n\nOptions:\n- add calendar event or reminder\n- ask date or time\n- check calendar\n- check email\n- check weather\n- chit-chat or odd request\n- factual question\n- find recipe\n- get news\n- play music\n- post on social media\n- send email\n\nAnswer with the label only."
}
],
"temperature": 0,
"max_tokens": 24,
"logprobs": true,
"structured_outputs": {
"choice": [
"add calendar event or reminder",
"ask date or time",
"check calendar",
"check email",
"check weather",
"chit-chat or odd request",
"factual question",
"find recipe",
"get news",
"play music",
"post on social media",
"send email"
]
}
}The response#
command: i would like to hear jazz music
model: play music (100% sure)
annotator: play music{
"model": "nenya-1",
"choices": [
{
"message": {
"content": "play music",
"role": "assistant"
},
"finish_reason": "stop",
"logprobs": {
"content": [
{
"token": "play",
"logprob": -0.0025
},
{
"token": " music",
"logprob": 0.0
}
]
}
}
],
"usage": {
"completion_tokens": 3,
"prompt_tokens": 135,
"total_tokens": 138
}
}Six commands#
for command in DATA["examples"]:
label, confidence = classify(QUESTION, command["text"], INTENTS, heading="Command")
print(f"{label:<18} {confidence:4.0%} {command['text']}")play music 100% i would like to hear jazz music
find recipe 94% what do i need to make lamb pathia
ask date or time 98% what is the current time
check weather 100% how is the weather
factual question 99% what is the capital of mexico
check email 100% have i received new emails in the last ten minutesAll six are the intent the annotators gave.
A command the assistant cannot do#
A real assistant has a fixed set of skills, and people ask for other things. Say this one can do eight of the twelve. Offer the eight, allow “none” (allow_none=True adds one sentence to the prompt and “none” to the choices), and decline when the answer is “none” or the confidence is low:
SKILLS = DATA["skills"] # say the assistant can do eight of the twelve things
for command in DATA["unknown"]:
label, confidence = classify(QUESTION, command["text"], SKILLS, heading="Command", allow_none=True)
if label == "none" or confidence < 0.8:
action = "say: sorry, I cannot do that yet"
else:
action = f"run the skill: {label}"
print(f"{command['text']:<54} {label:<17} {confidence:4.0%} {action}")i would like to hear jazz music play music 100% run the skill: play music
what is the current time ask date or time 100% run the skill: ask date or time
tweet a disgusted face about mcdonalds none 97% say: sorry, I cannot do that yet
find the recipe for sambar in cookingforu application none 95% say: sorry, I cannot do that yetThe first two have a skill and run it. The last two, a tweet and a recipe, have none, and the model says so.
“None” alone is not enough, which is why the code also looks at the confidence. On all 250 commands, with these eight skills on offer:
| Commands that have a skill (169): the right skill | 84.6% |
|---|---|
| Commands that have a skill: wrongly “none” | 6 of 169 |
| Commands with no skill (81): answered “none” | 64% |
| Commands with no skill: “none”, or a confidence under 0.8 | 85% |
| Commands with no skill: “none”, or a confidence under 0.9 | 96% |
The price of the threshold is the commands it turns away although a skill exists: at 0.8 the assistant runs 127 of the 169, and 121 of those 127 are the right skill.
Measure it#
Sixty commands taken from the test set without looking at the answers, with all twelve intents on offer, timed:
sample = DATA["sample"] # 60 commands, taken without looking at the answers
start = time.perf_counter()
answers = [classify(QUESTION, command["text"], INTENTS, heading="Command") for command in sample]
seconds = time.perf_counter() - start
right = sum(label == command["label"] for (label, _), command in zip(answers, sample))
sure = [(label, command) for (label, confidence), command in zip(answers, sample) if confidence >= 0.9]
sure_right = sum(label == command["label"] for label, command in sure)
print(f"{right} of {len(sample)} right ({right / len(sample):.0%})")
print(f"at least 90% sure of {len(sure)}; {sure_right} of those right ({sure_right / len(sure):.0%})")
print(f"{seconds / len(sample):.2f} s a command, one at a time")49 of 60 right (82%)
at least 90% sure of 34; 33 of those right (97%)
0.14 s a command, one at a timeThe time is from a machine in the same region as the server, with one request at a time. Add your own network.
On the whole test set#
All 250 commands, asked exactly as above, one request at a time:
| Right | |
|---|---|
| Intent names only (this recipe) | 78.4% (196 of 250) |
| A few words after each intent (“check calendar: ask what is on the calendar, or when an event is”) | 81.6% (204 of 250) |
| Act only when the confidence is at least | Commands you keep | Right among them |
|---|---|---|
| 0.80 | 70.4% | 90.3% |
| 0.90 | 57.2% | 93.0% |
| 0.95 | 46.0% | 94.8% |
Where it goes wrong: “check calendar” was right in 10 of 20, and 7 of the misses came back as “ask date or time” (“when is my brunch with jennifer”, “what is my schedule for the day”). Describing the two intents moved “check calendar” to 14 of 20. Intents that people word the same way need a description, or one skill behind both.
Make it yours#
- Offer few intents at a time. In our tests on these commands the model was right 91% of the time with 5 intents on offer, 86% with 10, 81% with 20 and 62% with all 60 that MASSIVE has. If you have many skills, route in two steps: first to a group (music, calendar, home), then to the intent inside the group.
- Allow “none” and keep the threshold. Each catches commands the other misses.
- Keep the wording of the prompt. It is the layout the model was trained on.
- This is routing only. To get the arguments as well (which song, what time), see Turn a spoken command into one function call.
Run it#
pip install openai
curl -O https://contrastivelabs.com/cookbook/classify-voice-commands.py
curl --create-dirs -o data/classify-voice-commands.json \
https://contrastivelabs.com/cookbook/data/classify-voice-commands.json
python classify-voice-commands.pyThe file is this page’s code in one piece: classify-voice-commands.py. The commands are in data/classify-voice-commands.json, each with its id in MASSIVE.