Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
|---|---|---|
| `ovos-switchboard-echo-pipeline-plugin` | the utterance repeats 4+ words in a row the assistant said in the last 60 s | decline |
| `ovos-switchboard-exact-pipeline-plugin` | the whole utterance matches exactly one skill's phrase (after a leading "Hey Mycroft") | dispatch |
| `ovos-switchboard-classifier-pipeline-plugin` | a character n-gram classifier with a "not for me" class | dispatch at confidence 0.5+; decline or pass for "not for me"; pass otherwise |
| `ovos-switchboard-classifier-pipeline-plugin` | a character n-gram classifier with a "not for me" class | dispatch at confidence 0.5+; decline or pass for "not for me"; pass otherwise, or when every phrase of the picked intent needs a slot the utterance doesn't fill |
| `ovos-switchboard-llm-pipeline-plugin` | an LLM picks one of 12 shortlisted skills, then a gate checks the speech was addressed to the assistant | dispatch; decline when it's not for the assistant or the LLM is unreachable; pass questions on to common_qa |
| `ovos-switchboard-prefix-pipeline-plugin` (optional) | the utterance starts with a skill's phrase and keeps going ("make me laugh hey dad …") | dispatch |
| `ovos-switchboard-decider-pipeline-plugin` (experimental) | a small local model picks a shortlisted skill, for hosts without an LLM | dispatch at probability 0.7+; otherwise decline or pass |
Expand Down
15 changes: 13 additions & 2 deletions ovos_switchboard/core/labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
compiles,
literal_words,
named_template_regex,
requires_slot,
well_formed,
)


Expand Down Expand Up @@ -78,6 +80,7 @@ class LabelSelector:
def __init__(self, device, schema):
from sklearn.feature_extraction.text import TfidfVectorizer
self.by_canon, self.adapt, self.templates, ex_text = {}, {}, {}, {}
self.slot_required = set() # template labels whose every sample needs a slot
for skill_id, defs in device.definitions.items():
for d in defs if isinstance(defs, list) else []:
label = f"{skill_id}:{d['intent_name']}"
Expand All @@ -88,13 +91,21 @@ def __init__(self, device, schema):
if d["method"] == "adapt":
self.adapt[label] = AdaptRule(d["definition"])
else:
self.templates[label] = [self._template(line) for line in d["definition"].get("samples") or []
if compiles(line)]
samples = d["definition"].get("samples") or []
self.templates[label] = [self._template(line) for line in samples if compiles(line)]
if d["lang"].lower() == device.lang:
self._note_slot_required(label, samples)
for e in device.examples:
ex_text.setdefault(e["label"], []).append(SLOT_TOKEN.sub(" ", e["example"]).lower())
self.ex_text = {label: " ".join(v[:EXAMPLES_PER_LABEL]) for label, v in ex_text.items()}
self.vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4)).fit(list(self.ex_text.values()) or ["x"])

def _note_slot_required(self, label, samples):
"""Judged on the samples the skill accepts (well_formed, typed slots included), not the compiling subset."""
accepted = [line for line in samples if well_formed(line)]
if accepted and all(requires_slot(line) for line in accepted):
self.slot_required.add(label)

@staticmethod
def _template(line):
body = named_template_regex(line)
Expand Down
17 changes: 16 additions & 1 deletion ovos_switchboard/core/stages.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ def resolve(self, intent, utterance, loose_slots=True):
label, data, how = self.labels.select(intent, utterance)
return label, data, how, slots

def slot_required(self, label):
"""True for a template label whose every sample needs a slot."""
return label in self.labels.slot_required

def keyword_data(self, label, utterance):
"""Keyword tools carry no parameters; the vocab the skill reads (message.data["Location"]) comes from
evaluating its rule on the utterance."""
Expand Down Expand Up @@ -149,7 +153,18 @@ def decide(self, utterance, context):
return passed(self.name, "unmapped intent", details=details)
if conf < self.options.threshold:
return passed(self.name, "low confidence", details=details)
return resolved(self.name, top, utterance, self.resolver, **details)
verdict = resolved(self.name, top, utterance, self.resolver, **details)
if self._slot_unfilled(verdict):
# No `intent` on this PASS: a classifier verdict with an intent counts as routed (Router.route).
return passed(self.name, "required slot unfilled", details={**verdict.details, "unfilled": verdict.label})
return verdict

def _slot_unfilled(self, verdict):
"""A dispatch the skill could not act on: no template matched, and every sample needs a slot ("what is the
boiling point of mercury" would reach Home Assistant's sensor intent, which asks "which device?"). Later
stages may answer it."""
return (verdict.outcome is Outcome.DISPATCH and not verdict.match_data
and self.resolver.slot_required(verdict.label))

def _pass_onward(self, context):
gap, policy = context.get("gap_s"), self.options.route_decline_class
Expand Down
7 changes: 7 additions & 0 deletions ovos_switchboard/core/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
LITERAL_EXPANSION_LIMIT = 50 # expansions examined when counting a template's literal words
SLOT = re.compile(r"\{+([a-z_]+)\}+")
SLOT_TOKEN = re.compile(r"\{+[a-z_]+\}+")
ANY_SLOT = re.compile(r"\{+[^{}]+\}+") # also typed ({number:n}) and other names the matcher accepts
# A template space: whitespace, or nothing where an omitted [optional] group leaves a word edge. Never zero
# characters inside a word, so "play {query}" doesn't match "playing by".
WORD_GAP = r"(?:\s+|\b)"
Expand Down Expand Up @@ -61,6 +62,12 @@ def clean(s):
return re.sub(r"\s+", " ", s).strip()


def requires_slot(line):
"""True when every expansion of `line` keeps a {slot}: "[about {topic}]" and "(in {location}|)" make it
optional."""
return all(ANY_SLOT.search(e) for e in expand(line))


def expansions(line, limit=MAX_PER_LINE):
"""Cleaned, non-empty expansions of a template line, at most `limit`."""
return [c for c in (clean(e) for e in itertools.islice(expand(line), limit)) if c]
Expand Down
78 changes: 76 additions & 2 deletions test/test_stages.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pytest
from ovos_bus_client.message import Message

from conftest import DATA, DIALOG_LINES, HA, WEATHER, StubLLM, register_all
from conftest import DATA, DATETIME, DIALOG_LINES, HA, WEATHER, StubLLM, register_all
from ovos_switchboard import data
from ovos_switchboard.adapters.bus_registry import IntentRegistry
from ovos_switchboard.core.classifier import Classifier
Expand All @@ -12,7 +13,7 @@
from ovos_switchboard.core.schema import Schema
from ovos_switchboard.core.shortlist import Shortlist
from ovos_switchboard.core.slots import SlotExtractor
from ovos_switchboard.core.stages import ClassifierStage, EchoStage, ExactStage, LabelResolver, LLMStage
from ovos_switchboard.core.stages import ClassifierStage, EchoStage, ExactStage, LabelResolver, LLMStage, PrefixStage
from ovos_switchboard.core.tools import build_tools
from ovos_switchboard.core.verdict import Outcome, Verdict

Expand Down Expand Up @@ -153,3 +154,76 @@ def rank(self, _utterance):
def test_unmapped_top_class_passes_with_its_own_reason(parts):
stage = ClassifierStage(RankedClassifier([("__unmapped__:skill-x.someone:do_thing", 0.97)]), parts.resolver)
assert stage.decide("do the thing", COLD).reason == "unmapped intent"


def picked(parts, intent, utterance):
"""The classifier stage's verdict when the model ranks `intent` first."""
return ClassifierStage(RankedClassifier([(intent, 0.97)]), parts.resolver).decide(utterance, COLD)


def test_slot_required_label_with_nothing_filled_passes(parts):
"""#37: every turn.on sample needs {entity}; a knowledge question gave the skill nothing to act on."""
v = picked(parts, "device.on", "what is the boiling point of mercury in kelvin")
assert (v.outcome, v.reason) == (Outcome.PASS, "required slot unfilled")
# no intent, so the router routes onward; the decision log keeps the label
assert (v.intent, v.label, v.details["unfilled"]) == (None, None, f"{HA}:turn.on")


def test_gated_pass_keeps_the_classifier_details(parts):
"""The router copies these into the decision record for a classifier PASS."""
v = picked(parts, "device.on", "what is the boiling point of mercury in kelvin")
assert (v.details["confidence"], v.details["label_how"]) == (0.97, "only label")


def test_required_slot_gate_is_classifier_only(parts, monkeypatch):
"""Exact and prefix matches dispatch as before even for a label the gate would hold."""
monkeypatch.setattr(parts.resolver, "slot_required", lambda label: True)
layer = ExactLayer(parts.device, parts.schema)
v = ExactStage(layer, parts.resolver).decide("what time is it")
assert (v.outcome, v.match_data) == (Outcome.DISPATCH, {})
layer.enable_prefix(3)
v = PrefixStage(layer, parts.resolver).decide("tell me the time oh and also")
assert (v.outcome, v.label) == (Outcome.DISPATCH, f"{DATETIME}:what_time_is_it")


def slot_required_after(*registrations):
"""LabelSelector.slot_required for (skill_id, intent_name, lang, samples) registrations, on an en-us device."""
from ovos_utils.fakebus import FakeBus
bus = FakeBus()
reg = IntentRegistry(bus)
for skill_id, name, lang, samples in registrations:
bus.emit(Message("ovos.intent.register.template",
{"skill_id": skill_id, "intent_name": name, "lang": lang, "samples": samples}))
return LabelSelector(Device.from_definitions(reg.definitions(), "en-us"), Schema.load()).slot_required


def test_a_typed_sample_that_can_omit_its_slot_keeps_the_label_ungated():
assert f"{HA}:turn.on" not in slot_required_after(
(HA, "turn.on", "en-us", ["turn on [the {entity:device}]", "turn on the {entity}"]))


def test_typed_samples_count_as_needing_their_slot():
assert f"{HA}:turn.on" in slot_required_after((HA, "turn.on", "en-us", ["turn on the {entity:device}"]))


def test_another_languages_samples_do_not_gate_the_device_language():
assert f"{DATETIME}:what_time_is_it" not in slot_required_after(
(DATETIME, "what_time_is_it", "en-us", ["what time is it", "what time is it in {location}"]),
(DATETIME, "what_time_is_it", "de-de", ["wie spät ist es in {ort}"]))


def test_slot_required_label_with_the_slot_filled_dispatches(parts):
v = picked(parts, "device.on", "hey could you turn on the desk lamp")
assert (v.outcome, v.label, v.match_data) == (Outcome.DISPATCH, f"{HA}:turn.on", {"entity": "desk lamp"})


def test_label_with_a_slot_free_sample_dispatches_without_data(parts):
"""what_time_is_it has "what time is it": an empty slot is a valid reading of it."""
v = picked(parts, "time.current", "whats the time right now")
assert (v.outcome, v.match_data) == (Outcome.DISPATCH, {})


def test_adapt_label_dispatches_without_data(parts):
"""Keyword intents are not templates: the gate does not apply to them."""
v = picked(parts, "weather.current", "is it going to be cold tonight")
assert (v.outcome, v.label) == (Outcome.DISPATCH, f"{WEATHER}:HandleCurrentWeather")
16 changes: 15 additions & 1 deletion test/test_templates.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import pytest

from ovos_switchboard.core.templates import template_regex
from ovos_switchboard.core.templates import requires_slot, template_regex


@pytest.mark.parametrize("line, required", [
("turn on (the|my|) {entity}", True),
("set (a|the) timer for {duration}", True),
("tell me a joke [about {topic}]", False), # optional group: "tell me a joke" has no slot
("what time is it (in {location}|)", False), # empty alternative
("what time is it", False),
("remind me in {number:n} minutes", True), # typed slot
("set [a] timer [for {duration:time}]", False), # typed, but optional
("turn on {Entity}", True), # the matcher lowercases slot names
])
def test_requires_slot(line, required):
assert requires_slot(line) is required


@pytest.mark.parametrize("line, utterance", [
Expand Down
Loading