"""User consent for multi-step plans.
Before a multi-step plan is executed the robot asks the user to confirm it. The reply r is
classified as yes / no / unclear:
1. a normalised match against configurable positive and negative phrase templates (instant, no model
call);
2. otherwise, with ``method: embedding``, the linear decision rule, rho = 1[v^T psi(r) + b > 0],
where psi is a multilingual sentence embedding and (v, b) is the prototype classifier fitted on
the phrase templates;
3. otherwise, with ``method: llm`` (default), a structured yes/no/unclear classification by the
language model, which works for any language the model knows.
"Unclear" replies are treated by the agent as a new instruction.
"""
from __future__ import annotations
import logging
import re
import unicodedata
from typing import Literal
import numpy as np
from .config import ConsentConfig
from .llm import ChatMessage, LLMProvider, extract_json
from .prompts import Prompts, render
log = logging.getLogger(__name__)
Decision = Literal["yes", "no", "unclear"]
_SCHEMA = {
"type": "object",
"properties": {"decision": {"type": "string", "enum": ["yes", "no", "unclear"]}},
"required": ["decision"],
"additionalProperties": False,
}
def normalise(text: str) -> str:
text = unicodedata.normalize("NFKC", text).casefold()
text = re.sub(r"[\s\W_]+", " ", text, flags=re.UNICODE)
return text.strip()
[docs]
class ConsentClassifier:
def __init__(self, cfg: ConsentConfig, provider: LLMProvider | None, prompts: Prompts):
self.cfg = cfg
self.provider = provider
self.prompts = prompts
self._pos = {normalise(p) for p in cfg.positive_phrases}
self._neg = {normalise(p) for p in cfg.negative_phrases}
self._embedder = None
self._v: np.ndarray | None = None
self._b = 0.0
if cfg.method == "embedding":
self._fit_embedding()
def classify(self, text: str) -> Decision:
key = normalise(text)
if key in self._pos:
return "yes"
if key in self._neg:
return "no"
if self._v is not None:
return self._classify_embedding(text)
return self._classify_llm(text)
# ------------------------------------------------------- Eq. (5) variant
def _fit_embedding(self) -> None:
try:
from sentence_transformers import SentenceTransformer
except ImportError as exc:
raise ImportError(
"consent.method 'embedding' needs: pip install 'reli-robot[embeddings]'"
) from exc
self._embedder = SentenceTransformer(self.cfg.embedding_model)
pos = self._embed(self.cfg.positive_phrases).mean(axis=0)
neg = self._embed(self.cfg.negative_phrases).mean(axis=0)
# Prototype linear classifier: the decision boundary is the hyperplane
# bisecting the two class means.
self._v = pos - neg
self._b = -float(self._v @ (pos + neg) / 2.0)
def _embed(self, texts: list[str]) -> np.ndarray:
assert self._embedder is not None
return np.asarray(self._embedder.encode(texts, normalize_embeddings=True))
def _classify_embedding(self, text: str) -> Decision:
score = float(self._v @ self._embed([text])[0] + self._b)
if abs(score) < self.cfg.margin:
return "unclear"
return "yes" if score > 0 else "no"
# ----------------------------------------------------------- LLM variant
def _classify_llm(self, text: str) -> Decision:
if self.provider is None:
return "unclear"
try:
raw = self.provider.complete(
"You classify replies to a confirmation question.",
[ChatMessage("user", render(self.prompts["consent_question"], text=text))],
_SCHEMA,
)
decision = str(extract_json(raw).get("decision", "")).lower()
except Exception: # 'unclear' is the safe outcome
log.exception("Consent classification failed.")
return "unclear"
return decision if decision in ("yes", "no") else "unclear" # type: ignore[return-value]