Call tools · Voice commands
Turn a spoken command into one function call
“I want to hear purple haze” has to become play_music(query="purple haze"), and “what time is it in central time zone” has to become get_date_time(place="central time zone"). That is two decisions: which function, and what goes into it. Nenya can make both in one request. This cookbook measures that on real commands, shows where it goes wrong, and then does it the way that works best: the function by classification, the arguments by extraction, and a check on the arguments before anything runs.
- The move
- Map a free-form command to one of your functions with its arguments, or to “nothing fits”.
- The model’s role
- It reads the command. Your code runs the function.
- Why it fits
- Commands are short, there are a handful of functions, and the arguments are words of the command itself. That is a classification and an extraction, the two things the model does best.
- How it goes
- Command in → the intent, as a classification → the function of that intent → its parameters, as a JSON extraction → drop any day or time the user did not say → call your function.
- Payoff
- Measured: on 250 real commands the right function in 79.6% with two requests, against 70.0% when one request picks among all eleven tools. The words the annotators marked as arguments are in the arguments 79% of the time. A third of the calls that take a day or a time came back with one the user had not said. After the check, none did.
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. MASSIVE’s annotators gave every command an intent and marked the words that are arguments: i want to hear [song_name : purple haze]. Those marks are what the calls are checked against. MASSIVE was kept out of the model’s training on purpose.
The commands cover twelve intents. Ten of them have a function below. Two, small talk and questions about facts, have none: for those the right call is no_matching_tool.
Set up#
pip install openai. The API is free and needs no key.
import json
import math
import re
from pathlib import Path
from openai import OpenAI
client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")The tools#
Ten functions and a way out. tool is the helper of the API page. Every parameter has a description, and the descriptions of look-alike tools say when to use which.
def tool(name, description, properties, required):
return {"type": "function", "function": {"name": name, "description": description, "parameters": {
"type": "object", "properties": properties, "required": required}}}
TOOLS = [
tool("add_calendar_event", "Create something new on the user's calendar: an event, a meeting, or a reminder "
"(\"remind me to ...\", \"schedule ...\", \"add ... to my calendar\").",
{"title": {"type": "string", "description": "What the event or the reminder is"},
"date": {"type": "string", "description": "The day, as the user said it"},
"time": {"type": "string", "description": "The time, as the user said it"},
"place": {"type": "string", "description": "Where it is"}}, ["title"]),
tool("get_calendar", "Look up what is already on the user's calendar: the schedule of a day, or when a meeting "
"or a reminder is.",
{"date": {"type": "string", "description": "The day asked about, as the user said it"},
"event": {"type": "string", "description": "The event asked about"}}, []),
tool("get_date_time", "Tell what time or what date it is now, here or in another place. Only for the clock and "
"today's date.",
{"place": {"type": "string", "description": "The place or time zone asked about"}}, []),
tool("check_email", "Look at the emails the user has received: new mail, or mail from someone.",
{"sender": {"type": "string", "description": "Whose emails to look for"}}, []),
tool("send_email", "Write an email or a reply and send it.",
{"to": {"type": "string", "description": "Who the email goes to, as the user said it"},
"message": {"type": "string", "description": "What the email should say"}}, ["to"]),
tool("get_weather", "The weather now or the forecast: temperature, rain, what to wear outside.",
{"place": {"type": "string", "description": "The place asked about"},
"date": {"type": "string", "description": "The day asked about, as the user said it"}}, []),
tool("get_news", "News and headlines from papers, channels and news sites.",
{"topic": {"type": "string", "description": "What the news should be about"},
"source": {"type": "string", "description": "The paper, channel or site to take it from"}}, []),
tool("play_music", "Play a song, an artist, an album, a genre or a playlist.",
{"query": {"type": "string", "description": "What to play, as the user said it"}}, []),
tool("post_to_social_media", "Post, tweet or publish a message or a complaint on a social network such as "
"twitter or facebook.",
{"network": {"type": "string", "description": "The network, such as twitter or facebook"},
"text": {"type": "string", "description": "What to post"}}, ["text"]),
tool("find_recipe", "Find how to cook or prepare a dish.",
{"dish": {"type": "string", "description": "The dish or the ingredient"}}, ["dish"]),
tool("no_matching_tool", "Call this for everything else: small talk, a question about a fact, a person or a "
"place, or a request that none of the other tools can do.",
{"reason": {"type": "string", "description": "One sentence on why no tool fits"}}, ["reason"]),
]
def command_to_call(command):
"""(tool name, arguments) for one spoken command. `tool_choice="required"` makes the model call a tool."""
reply = client.chat.completions.create(model="nenya", messages=[{"role": "user", "content": command}],
tools=TOOLS, tool_choice="required")
call = reply.choices[0].message.tool_calls[0]
return call.function.name, json.loads(call.function.arguments)DATA = json.loads((Path(__file__).parent / "data" / "tools-voice-commands.json").read_text())
for t in TOOLS:
print(f"{t['function']['name']}({', '.join(t['function']['parameters']['properties'])})")add_calendar_event(title, date, time, place)
get_calendar(date, event)
get_date_time(place)
check_email(sender)
send_email(to, message)
get_weather(place, date)
get_news(topic, source)
play_music(query)
post_to_social_media(network, text)
find_recipe(dish)
no_matching_tool(reason)The request#
command_to_call sends the command and all eleven tools, with tool_choice="required", so a call always comes back:
command = DATA["examples"][0]
name, arguments = command_to_call(command["text"])
print(f"command: {command['text']}")
print(f"call: {name}({json.dumps(arguments)})")
print(f"annotators: {command['annotated']}"){
"model": "nenya",
"messages": [
{
"role": "user",
"content": "what is the minimum temperature of london"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "add_calendar_event",
"description": "Create something new on the user's calendar: an event, a meeting, or a reminder (\"remind me to ...\", \"schedule ...\", \"add ... to my calendar\").",
"parameters": {
"type": "object",
"properties": {
"title": {
"type": "string",
"description": "What the event or the reminder is"
},
"date": {
"type": "string",
"description": "The day, as the user said it"
},
"time": {
"type": "string",
"description": "The time, as the user said it"
},
"place": {
"type": "string",
"description": "Where it is"
}
},
"required": [
"title"
]
}
}
},
{
"type": "function",
"function": {
"name": "get_calendar",
"description": "Look up what is already on the user's calendar: the schedule of a day, or when a meeting or a reminder is.",
"parameters": {
"type": "object",
"properties": {
"date": {
"type": "string",
"description": "The day asked about, as the user said it"
},
"event": {
"type": "string",
"description": "The event asked about"
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "get_date_time",
"description": "Tell what time or what date it is now, here or in another place. Only for the clock and today's date.",
"parameters": {
"type": "object",
"properties": {
"place": {
"type": "string",
"description": "The place or time zone asked about"
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "check_email",
"description": "Look at the emails the user has received: new mail, or mail from someone.",
"parameters": {
"type": "object",
"properties": {
"sender": {
"type": "string",
"description": "Whose emails to look for"
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "send_email",
"description": "Write an email or a reply and send it.",
"parameters": {
"type": "object",
"properties": {
"to": {
"type": "string",
"description": "Who the email goes to, as the user said it"
},
"message": {
"type": "string",
"description": "What the email should say"
}
},
"required": [
"to"
]
}
}
},
{
"type": "function",
"function": {
"name": "get_weather",
"description": "The weather now or the forecast: temperature, rain, what to wear outside.",
"parameters": {
"type": "object",
"properties": {
"place": {
"type": "string",
"description": "The place asked about"
},
"date": {
"type": "string",
"description": "The day asked about, as the user said it"
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "get_news",
"description": "News and headlines from papers, channels and news sites.",
"parameters": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "What the news should be about"
},
"source": {
"type": "string",
"description": "The paper, channel or site to take it from"
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "play_music",
"description": "Play a song, an artist, an album, a genre or a playlist.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "What to play, as the user said it"
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "post_to_social_media",
"description": "Post, tweet or publish a message or a complaint on a social network such as twitter or facebook.",
"parameters": {
"type": "object",
"properties": {
"network": {
"type": "string",
"description": "The network, such as twitter or facebook"
},
"text": {
"type": "string",
"description": "What to post"
}
},
"required": [
"text"
]
}
}
},
{
"type": "function",
"function": {
"name": "find_recipe",
"description": "Find how to cook or prepare a dish.",
"parameters": {
"type": "object",
"properties": {
"dish": {
"type": "string",
"description": "The dish or the ingredient"
}
},
"required": [
"dish"
]
}
}
},
{
"type": "function",
"function": {
"name": "no_matching_tool",
"description": "Call this for everything else: small talk, a question about a fact, a person or a place, or a request that none of the other tools can do.",
"parameters": {
"type": "object",
"properties": {
"reason": {
"type": "string",
"description": "One sentence on why no tool fits"
}
},
"required": [
"reason"
]
}
}
}
],
"tool_choice": "required"
}The response#
command: what is the minimum temperature of london
call: get_weather({"place": "london"})
annotators: what is the minimum [weather_descriptor : temperature] of [place_name : london]{
"model": "nenya-1",
"choices": [
{
"message": {
"content": "",
"role": "assistant",
"tool_calls": [
{
"id": "chatcmpl-tool-81332dd82aca55b1",
"function": {
"arguments": "{\"place\": \"london\"}",
"name": "get_weather"
},
"type": "function"
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"completion_tokens": 10,
"prompt_tokens": 1159,
"total_tokens": 1169
}
}arguments is a JSON string. The function name and the place are right: the annotators marked “london” as the place.
Six commands#
for command in DATA["examples"]:
name, arguments = command_to_call(command["text"])
print(f"{command['text']:<50} -> {name}({json.dumps(arguments)})")what is the minimum temperature of london -> get_weather({"place": "london"})
i need a recipe of veg pulav -> find_recipe({"dish": "veg pulav"})
send tech news -> get_news({"topic": "tech"})
i want to hear purple haze -> play_music({"query": "purple haze"})
did i email tom on the subject of gun control -> check_email({"sender": "tom"})
what time is it in central time zone -> get_date_time({"place": "central time zone"})All six are the function of the command’s intent, with the marked words as arguments.
Where one request goes wrong#
Those six were picked because they come out right. Sixty commands taken without looking at the answers tell the rest:
sample = DATA["sample"] # 60 commands, taken without looking at the answers
calls = [command_to_call(command["text"]) for command in sample]
right = sum(name == command["tool"] for (name, _), command in zip(calls, sample))
print(f"the right tool for {right} of {len(sample)} commands")
for t in TOOLS:
mine = [name for (name, _), command in zip(calls, sample) if command["tool"] == t["function"]["name"]]
print(f"{t['function']['name']:<22} {mine.count(t['function']['name']):2d} of {len(mine):2d}")the right tool for 38 of 60 commands
add_calendar_event 0 of 4
get_calendar 2 of 3
get_date_time 4 of 4
check_email 3 of 4
send_email 4 of 6
get_weather 9 of 10
get_news 3 of 3
play_music 4 of 4
post_to_social_media 2 of 4
find_recipe 6 of 7
no_matching_tool 1 of 11Two rows carry the misses. A reminder (“remind me to call mom in half an hour”) is sent to the clock or to the calendar look-up, not to add_calendar_event. And a question about a fact (“how old is mariah carey”) gets a tool that has a date or news in it, not no_matching_tool. With eleven tools that resemble each other, picking is the weak step. This is the same finding as on the API page: a tool call used as a classifier scored 70% where the classification recipe scored 81%.
Route, then extract#
So let each recipe do what it is good at. classify and extract are the two functions of the API page, unchanged. The first names the intent. The second fills the parameters of that intent’s function, as fields that may be null:
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, confidence
def extract(kind, document, fields, max_tokens=800):
"""{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
f"Fields:\n{lines}\n\n"
"Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
"additionalProperties": False}
reply = client.chat.completions.create(
model="nenya",
messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
temperature=0, # one right answer: do not sample
max_tokens=max_tokens,
response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
)
choice = reply.choices[0]
if choice.finish_reason != "stop": # "length": the JSON was cut off and will not parse
raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
return json.loads(choice.message.content)
QUESTION = "Which intent does this voice-assistant command express?"
TOOL_FOR = DATA["tool_for"] # which tool answers which intent: {"check weather": "get_weather", ...}
INTENTS = sorted(TOOL_FOR)
BY_NAME = {t["function"]["name"]: t for t in TOOLS}
def route_then_extract(command):
"""(tool name, arguments). The intent as a classification, then the arguments as a JSON extraction whose
fields are the tool's parameters. A parameter the command does not give comes back null and is left out."""
intent, confidence = classify(QUESTION, command, INTENTS, heading="Command")
name = TOOL_FOR[intent]
if name == "no_matching_tool":
return name, {"reason": f"the command is a {intent}"}
parameters = BY_NAME[name]["function"]["parameters"]["properties"]
fields = [{"name": key, "type": spec["type"], "description": spec["description"]} for key, spec in parameters.items()]
record = extract("voice command", command, fields, max_tokens=200)
return name, {key: value for key, value in record.items() if value is not None}
for command in DATA["examples"] + DATA["nothing_fits"]:
name, arguments = route_then_extract(command["text"])
print(f"{command['text']:<50} -> {name}({json.dumps(arguments)})")what is the minimum temperature of london -> get_weather({"place": "london"})
i need a recipe of veg pulav -> find_recipe({"dish": "veg pulav"})
send tech news -> get_news({"topic": "tech news"})
i want to hear purple haze -> play_music({"query": "purple haze"})
did i email tom on the subject of gun control -> check_email({"sender": "tom"})
what time is it in central time zone -> get_date_time({"place": "central time zone"})
where was president madison born -> no_matching_tool({"reason": "the command is a factual question"})
does pink have a new baby -> no_matching_tool({"reason": "the command is a chit-chat or odd request"})The same six, and two commands that have no function: both are turned away.
Keep what the user said#
The arguments of a voice command are words the user said. The model does not always stop there: asked for a day, it sometimes writes a calendar date it worked out from nothing.
def said(value, command):
"""Is this value made of the user's own words? Every word of it has to be in the command."""
words = re.findall(r"[a-z0-9']+", str(value).lower())
return bool(words) and all(word in command.lower() for word in words)
def keep_what_was_said(arguments, command, copied=("date", "time")):
"""The call without the days and times the user did not say."""
return {key: value for key, value in arguments.items() if key not in copied or said(value, command)}
for command in DATA["made_up"]:
name, arguments = route_then_extract(command["text"])
print(f"command: {command['text']}")
print(f"the model's call: {name}({json.dumps(arguments)})")
print(f"after the check: {name}({json.dumps(keep_what_was_said(arguments, command['text']))})")command: do i have anything planned for the twenty first
the model's call: get_calendar({"date": "2021-03-25", "event": "the twenty first"})
after the check: get_calendar({"event": "the twenty first"})
command: remind me my mom's birthday a week before
the model's call: add_calendar_event({"title": "Mom's birthday", "date": "2020-08-08"})
after the check: add_calendar_event({"title": "Mom's birthday"})Nobody said 2021 or 2020. keep_what_was_said drops a day or a time unless every word of it is in the command. What is left is what the user said, and your own code can turn “the twenty first” into a date, with today’s date in hand.
Measure it#
The same sixty commands, routed and extracted:
routed = [route_then_extract(command["text"]) for command in sample]
right = sum(name == command["tool"] for (name, _), command in zip(routed, sample))
print(f"the right tool for {right} of {len(sample)} commands")
for t in TOOLS:
mine = [name for (name, _), command in zip(routed, sample) if command["tool"] == t["function"]["name"]]
print(f"{t['function']['name']:<22} {mine.count(t['function']['name']):2d} of {len(mine):2d}")the right tool for 48 of 60 commands
add_calendar_event 3 of 4
get_calendar 1 of 3
get_date_time 3 of 4
check_email 3 of 4
send_email 6 of 6
get_weather 9 of 10
get_news 3 of 3
play_music 4 of 4
post_to_social_media 2 of 4
find_recipe 7 of 7
no_matching_tool 7 of 11On the whole test set#
All 250 commands, one request at a time:
| How the call is made | The right function | Marked words in the arguments | Calls with a day or a time the user did not say |
|---|---|---|---|
| One request, all eleven tools, first tool descriptions | 64.0% (160) | 88 of 120 | not counted |
| One request, descriptions rewritten to say when to use which | 70.0% (175) | 79 of 120 | 16 of 40 |
| The intent by classification, then a tool call forced to that tool | 79.6% (199) | 100 of 140 | 23 of 50 |
| The intent by classification, then the arguments by extraction (this recipe) | 79.6% (199) | 111 of 140 | 17 of 50 |
The same, with keep_what_was_said | 79.6% (199) | 111 of 140 | 0 of 50 |
The last column counts, among the calls to the three tools that take a day or a time, the ones where the day or the time is not made of the command’s own words. The check costs nothing: no marked word was lost to it.
Reading the rows:
- Descriptions matter, and they are not enough. Rewriting them was worth six points. We rewrote them after reading the misses of the first run, on these same 250 commands, so six points is the most to expect.
- Routing by classification is worth ten points more.
add_calendar_eventwent from 6 of 27 to 23 of 27, and the commands with no function from 17 of 41 turned away to 31 of 41. - Extraction fills arguments better than a forced tool call: 111 against 100 of the 140 marked words.
- What stays wrong is the classification’s own misses: “check calendar” is right in 10 of 20, mostly taken for a question about the time (the routing cookbook has the details).
Make it yours#
- One request is fine for a few tools that do not resemble each other. With one or two tools the model picks and fills correctly nine times in ten.
- With a menu of similar tools, route first. Use your intents as labels, then call the one tool, or extract its parameters.
- Never run a call unchecked. Check that required arguments are there, and drop copied values the user did not say. Work dates out in your own code: in our tests the model turned 1 of 13 relative dates (“tomorrow”, “next Thursday”) into the right day.
- Give “nothing fits” a place to go: an intent with no function, or a
no_matching_tooltool. - Leave
temperatureunset with tools. The server decodes a tool request at temperature 0.
Run it#
pip install openai
curl -O https://contrastivelabs.com/cookbook/tools-voice-commands.py
curl --create-dirs -o data/tools-voice-commands.json \
https://contrastivelabs.com/cookbook/data/tools-voice-commands.json
python tools-voice-commands.pyThe file is this page’s code in one piece: tools-voice-commands.py. The commands, with MASSIVE’s marks, are in data/tools-voice-commands.json.