Turns
A turn handles one line of conversation and can run a command. Call
Agent::turn with the line and a TurnHandler supplied by your firmware.
What it is good for
Use turns to control devices from serial text or from text produced by a speech recognizer. The agent can ask which device the user means and let them say “it” in a follow-up. The command and its context are handled on the chip.
Who decides what
The agent handles the order of events in a turn and keeps conversation memory.
Your handler decides what the input means and how to act on it. When the
closest stored example has positive similarity, the agent passes its payload
as suggested. A search hit provides a hint only. parse validates the
original input, including every argument, before returning a command.
The handler
parseextracts aCommandwith an action and aTargetSelector.Explicitcarries a device name, alias, or group.Previousrefers to the target of the last successful command, as in “dim it”.resolve_targetslooks up an explicit selector in your device catalog. Each device has a stableTargetId.TargetMatch::Resolvednames the devices that act together,Ambiguousoffers alternatives for the user to choose from, andMissingindicates that the selector matched no device.matches_targetchecks whether a clarification reply identifies a device in the choices offered. Exactly one match is needed to continue.dispatchruns the action once on the resolved targets. It checks that every target ID still belongs to the catalog and returns a result or error.
Outcomes
Agent::turn returns a TurnOutcome that your firmware can use to respond.
| Outcome | Meaning |
|---|---|
Executed | The handler ran the action successfully and returned its result. |
Failed | The handler returned an error while running the action. |
Clarify | Ask the user to choose one of the returned targets. |
NeedTarget | Ask for a complete command with a more specific target. |
Unrecognized | The input did not parse as a command, and no question is pending. |
Conversation memory
Call Agent::builder(model, &knowledge).context(n).build() to keep up to n
choices for a pending question and up to n targets from the last successful
command. The default is zero, including when you use Agent::new. With memory
set to zero, explicit commands still work.
A successful dispatch replaces the remembered targets or clears them if the
whole list exceeds n. A failed dispatch preserves the previous targets.
“It” resolves directly when one target is remembered. If a group is remembered,
the agent asks the user to choose. With no remembered targets, it requests a
more specific command.
Each agent owns its conversation state. It can be cloned when its payload is
Clone, and each clone keeps an independent conversation. Agent never
implements Copy.
Declare the vocabulary instead
You do not need to write the handler by hand. targets! declares the devices
and the phrases that name them, and #[derive(TurnCommands)] declares the
commands on your action enum. The turn macros reference
covers every rule. The home assistant firmware declares both.
Example with the home assistant
The home-assistant firmware controls two simulated lamps. Its knowledge
store holds examples for turning a lamp on and setting its brightness. For
“Dim the lamp”, the firmware constructs BeginDim directly.
/// Knowledge store examples for turning a lamp on and setting its brightness.
pub const EXAMPLES: [(&str, Action); 2] = [
("Turn on the lamp", Action::TurnOn),
(
"Dim the lamp to 30 percent",
Action::SetBrightness {
level: Percent::new(30),
},
),
];
/// What the user can ask a lamp to do, with the arguments read from the original input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, TurnCommands)]
#[commands(previous = "it")]
pub enum Action {
/// Switch the lamp on.
#[command("turn on {target}", "turn {target} on")]
TurnOn,
/// Set the brightness.
#[command("dim {target} to {level} percent", "dim {target} to {level}%")]
SetBrightness {
/// The new brightness.
level: Percent,
},
/// Ask which brightness the user wants. The firmware builds it from a shorter command.
BeginDim,
}
/// A brightness in percent, from 0 to 100.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Percent(u8);
impl Percent {
/// Creates a brightness at compile time.
///
/// # Panics
///
/// Panics if `value` is above 100.
pub const fn new(value: u8) -> Self {
assert!(value <= 100, "a percentage is at most 100");
Self(value)
}
}
impl FromStr for Percent {
type Err = ();
/// Accepts decimal digits only, from 0 through 100.
fn from_str(text: &str) -> Result<Self, ()> {
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(());
}
text.parse::<u8>()
.ok()
.filter(|value| *value <= 100)
.map(Self)
.ok_or(())
}
}
The firmware embeds the examples and gives the agent room for two targets.
let mut knowledge = Knowledge::with_capacity(Embedder::new(POTION), EXAMPLES.len());
knowledge.extend(EXAMPLES);
let mut agent = Agent::builder(POTION, &knowledge)
.context(CONTEXT_TARGETS)
.build()
.expect("the examples are embedded with POTION");
The catalog lists the lamps. “Lamp” is ambiguous and “living room lights” is a group containing both lamps.
/// The lamps, the phrases that name them, and the replies that pick one out of a question.
static LAMPS: TargetCatalog = targets! {
device Desk = 1, "desk lamp" {
replies ["desk", "desk one"];
}
device Floor = 2, "floor lamp" {
replies ["floor", "floor one"];
}
choose "lamp" from [Desk, Floor];
group ["living room", "living room lights"] = [Desk, Floor];
};
The handler forwards parsing and lookups to the declarations. It also keeps one firmware-owned question, described below.
impl TurnHandler<Action> for Home {
type Success = Done;
type Error = HomeError;
fn parse<'a>(
&self,
input: &'a str,
_suggested: Option<&Action>,
) -> Option<Command<'a, Action>> {
parse_command(input).or_else(|| {
let lamp = self.awaiting_brightness?;
Some(Command {
action: Action::SetBrightness {
level: parse_level(input)?,
},
target: TargetSelector::Explicit(LAMPS.name(lamp)?),
})
})
}
fn resolve_targets(&self, selector: &str) -> TargetMatch {
LAMPS.resolve_targets(selector)
}
fn matches_target(&self, target: TargetId, reply: &str) -> bool {
LAMPS.matches_target(target, reply)
}
fn dispatch(&mut self, action: Action, targets: &[TargetId]) -> Result<Done, HomeError> {
if targets.is_empty() {
return Err(HomeError::NoTarget);
}
if let Some(unknown) = targets.iter().find(|id| self.lamp(**id).is_none()) {
return Err(HomeError::UnknownTarget(*unknown));
}
if action == Action::BeginDim {
let &[lamp] = targets else {
return Err(HomeError::NameOneLamp);
};
self.awaiting_brightness = Some(lamp);
} else {
for lamp in self
.lamps
.iter_mut()
.filter(|lamp| targets.contains(&lamp.id))
{
match action {
Action::SetBrightness { level } => lamp.brightness = level.0,
Action::TurnOn | Action::BeginDim => lamp.on = true,
}
}
self.awaiting_brightness = None;
}
Ok(Done {
action,
targets: targets.to_vec(),
})
}
}
From the repository root, flash the example with the command for your board.
just run_s3 home-assistant
# ESP32-S31
just run_s31 home-assistant
Try these commands in the serial monitor. The agent asks which lamp, and “it” refers to the last lamp that a command acted on.
> Dim the lamp to 37%
Which lamp, the desk lamp or the floor lamp?
> The desk one
The desk lamp is at 37 percent.
> Turn it on
The desk lamp is on.
> Turn on the living room lights
The living room lights are on.
> Dim it to 12%
Which lamp, the desk lamp or the floor lamp?
> Floor
The floor lamp is at 12 percent.
A question that the firmware owns
The agent asks which target a command means. It cannot know that a command is
missing a value, so your firmware asks for that. “Dim the lamp” is a short
command that the firmware turns into the unannotated BeginDim action. After
the agent resolves the lamp, dispatching BeginDim records the lamp and returns
a prompt. It changes no hardware.
/// Reads a complete command, or the short "dim <lamp>" that starts the brightness question.
fn parse_command(input: &str) -> Option<Command<'_, Action>> {
Action::parse_command(input).or_else(|| begin_dim(input))
}
/// Recognizes "dim <lamp>" when the lamp is a known selector or the word "it".
fn begin_dim(input: &str) -> Option<Command<'_, Action>> {
let rest = strip_prefix_ignore_case(trim_sentence(input), "dim ")?.trim();
let target = if rest.eq_ignore_ascii_case("it") {
TargetSelector::Previous
} else if LAMPS.contains_selector(rest) {
TargetSelector::Explicit(rest)
} else {
return None;
};
Some(Command {
action: Action::BeginDim,
target,
})
}
/// Tells whether the line opens with a command verb, whether or not it is a valid command.
fn starts_like_command(input: &str) -> bool {
["dim ", "turn "]
.iter()
.any(|verb| strip_prefix_ignore_case(input, verb).is_some())
}
/// Reads a bare brightness such as "37 percent" or "37%".
fn parse_level(input: &str) -> Option<Percent> {
let input = trim_sentence(input);
strip_suffix_ignore_case(input, " percent")
.or_else(|| strip_suffix_ignore_case(input, "%"))?
.trim()
.parse()
.ok()
}
The conversation looks like this. An invalid value repeats the question.
> Dim the lamp
Which lamp, the desk lamp or the floor lamp?
> The desk one
To what brightness?
> 150 percent
To what brightness?
> 37 percent
The desk lamp is at 37 percent.
The firmware keeps this state next to its devices, one value for each
conversation, and the question is independent of the agent’s memory limit. A
new command abandons it, even a command that needs a clarification, names an
unknown lamp, or is malformed such as “Dim the floor lamp to 150%”, so a later “37 percent” cannot revive the old question.
If the serial line is too long, the firmware asks for a shorter command. A
command verb in the retained prefix still cancels the brightness question.
Classifying a new command and clearing the question happens in the firmware’s
respond before it calls Agent::turn, because parse borrows the handler
immutably.
> Dim the lamp to 37%
Which lamp, the desk lamp or the floor lamp?
> Dim desk lamp
To what brightness?
> Turn on the floor lamp
The floor lamp is on.
> 37 percent
Sorry, I did not understand. Try "Turn on the lamp".
A group has no single brightness question, so “Dim the living room lights” replies that you must name one lamp. A complete command still works on a group.
The same walkthrough runs on your computer with just test in the
home assistant integration test.