"""Action catalogue.
The catalogue defines what the robot can do. It provides (i) the JSON schema used for decoding, (ii)
the catalogue text shown to the model, and (iii) the validator applied to every model output.
``expand`` is the rule-based parser P: the k high-level steps chosen by the model become n >= k
executable primitives, e.g. a POLYGON becomes alternating MOVE/TURN steps.
"""
from __future__ import annotations
import math
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, Literal
from .types import Action
ParamKind = Literal["number", "integer", "string", "enum"]
Capability = Literal["camera", "destinations"]
@dataclass(frozen=True)
class Param:
name: str
kind: ParamKind
description: str
required: bool = False
default: Any = None
choices: tuple[str, ...] = ()
minimum: float | None = None # physical validity, not a safety limit
maximum: float | None = None
exclusive_minimum: bool = False
# The default is what an unstated value means ("move 1 m" = forward), not an
# open choice, so reference plans keep it even when it is not stated.
implied: bool = False
@dataclass(frozen=True)
class ActionSpec:
name: str
description: str
params: tuple[Param, ...] = ()
moves: bool = False # commands base motion
requires: frozenset[str] = field(default_factory=frozenset)
def _speed(desc: str = "linear speed in m/s; omit for the default") -> Param:
return Param("speed", "number", desc, minimum=0.0, exclusive_minimum=True)
def _turn_dir(default: str = "left") -> Param:
return Param(
"direction", "enum", "turning direction", default=default, choices=("left", "right")
)
_BASE_SPECS: tuple[ActionSpec, ...] = (
# ----------------------------------------------------------- primitives
ActionSpec(
"MOVE",
"Drive straight forward or backward.",
(
Param("distance", "number", "distance in metres", required=True, minimum=0.0),
Param(
"direction",
"enum",
"driving direction",
default="forward",
choices=("forward", "backward"),
implied=True,
),
_speed(),
),
moves=True,
),
ActionSpec(
"TURN",
"Rotate in place. 'rotate clockwise' means right.",
(
Param("angle", "number", "angle in degrees", required=True, minimum=0.0),
_turn_dir(),
Param(
"angular_speed",
"number",
"rotation speed in deg/s; omit for the default",
minimum=0.0,
exclusive_minimum=True,
),
),
moves=True,
),
ActionSpec(
"ARC",
"Drive along a circular arc; angle 360 is a full circle.",
(
Param(
"radius",
"number",
"radius in metres",
required=True,
minimum=0.0,
exclusive_minimum=True,
),
Param(
"angle",
"number",
"swept angle in degrees",
default=360.0,
minimum=0.0,
exclusive_minimum=True,
implied=True,
),
_turn_dir(),
_speed(),
),
moves=True,
),
# ---------------------------------------------- composite patterns (P)
ActionSpec(
"POLYGON",
"Trace a regular polygon (triangle=3, square=4, ...), ending at the start.",
(
Param("sides", "integer", "number of sides", required=True, minimum=3, maximum=24),
Param(
"side_length",
"number",
"side length in metres",
required=True,
minimum=0.0,
exclusive_minimum=True,
),
_turn_dir(),
_speed(),
),
moves=True,
),
ActionSpec(
"RECTANGLE",
"Trace a rectangle: drive 'length', turn, drive 'width', ... back to start.",
(
Param(
"length",
"number",
"first side in metres",
required=True,
minimum=0.0,
exclusive_minimum=True,
),
Param(
"width",
"number",
"second side in metres",
required=True,
minimum=0.0,
exclusive_minimum=True,
),
_turn_dir(),
_speed(),
),
moves=True,
),
# ------------------------------------------------------------ navigation
ActionSpec(
"GO_TO_COORDINATES",
"Navigate to map coordinates (metres) with the navigation stack.",
(
Param("x", "number", "map x in metres", required=True),
Param("y", "number", "map y in metres", required=True),
Param("yaw", "number", "final heading in degrees, counter-clockwise from +x"),
_speed(),
),
moves=True,
),
ActionSpec(
"GO_TO_DESTINATION",
"Navigate to a named place from the destination list.",
(Param("destination", "enum", "destination key", required=True), _speed()),
moves=True,
requires=frozenset({"destinations"}),
),
ActionSpec(
"GO_TO_OBJECT",
"Find a visible object and stop in front of it.",
(
Param("object", "string", "short English noun phrase, e.g. 'red chair'", required=True),
Param(
"approach_distance",
"number",
"stand-off distance in metres; omit for default",
minimum=0.0,
exclusive_minimum=True,
),
_speed(),
),
moves=True,
requires=frozenset({"camera"}),
),
ActionSpec(
"FACE_OBJECT",
"Find an object and turn to face it.",
(Param("object", "string", "short English noun phrase", required=True),),
moves=True,
requires=frozenset({"camera"}),
),
ActionSpec(
"CIRCLE_OBJECT",
"Drive a full circle around an object at a clearance.",
(
Param("object", "string", "short English noun phrase", required=True),
Param(
"clearance",
"number",
"gap to the object surface in metres",
default=0.5,
minimum=0.0,
exclusive_minimum=True,
),
_turn_dir(),
_speed(),
),
moves=True,
requires=frozenset({"camera"}),
),
# ---------------------------------------------------------------- queries
ActionSpec(
"DESCRIBE_SCENE", "Describe what the robot currently sees.", requires=frozenset({"camera"})
),
ActionSpec("REPORT_POSE", "Report the robot's current coordinates and heading."),
ActionSpec(
"LOCATE_OBJECTS",
"Report where objects are; give 'object' to look for one thing.",
(Param("object", "string", "short English noun phrase; omit to list everything"),),
requires=frozenset({"camera"}),
),
ActionSpec("SEND_IMAGE", "Send the current camera image.", requires=frozenset({"camera"})),
# ---------------------------------------------------------------- control
ActionSpec(
"WAIT",
"Pause for a duration.",
(Param("duration", "number", "seconds", required=True, minimum=0.0),),
),
ActionSpec("STOP", "Stop all motion immediately and cancel the current plan."),
)
INTENTS = ("converse", "execute", "clarify", "refuse")
[docs]
class Catalog:
"""The actions available in a given deployment (capabilities + destinations)."""
def __init__(
self,
capabilities: Iterable[str] = (),
destinations: Sequence[str] = (),
allowed: Iterable[str] | None = None,
):
caps = set(capabilities)
if destinations:
caps.add("destinations")
allowed_set = set(allowed) if allowed is not None else None
self.destinations = tuple(destinations)
self.specs: dict[str, ActionSpec] = {}
for spec in _BASE_SPECS:
if not spec.requires <= caps:
continue
if allowed_set is not None and spec.name not in allowed_set and spec.name != "STOP":
continue
self.specs[spec.name] = spec
def __contains__(self, name: str) -> bool:
return name in self.specs
def _choices(self, p: Param) -> tuple[str, ...]:
return self.destinations if p.name == "destination" else p.choices
# ------------------------------------------------------------ schema
[docs]
def turn_schema(self) -> dict:
"""Strict JSON schema for one dialogue turn (OpenAI strict-mode compatible)."""
variants = []
for spec in self.specs.values():
props: dict[str, Any] = {"action": {"type": "string", "enum": [spec.name]}}
for p in spec.params:
props[p.name] = self._param_schema(p)
variants.append(
{
"type": "object",
"properties": props,
"required": list(props),
"additionalProperties": False,
}
)
return {
"type": "object",
"properties": {
"language": {
"type": "string",
"description": "BCP-47 tag of the language the user wrote in",
},
"intent": {"type": "string", "enum": list(INTENTS)},
"reply": {
"type": "string",
"description": "message to the user, in the user's language",
},
"actions": {"type": "array", "items": {"anyOf": variants}},
},
"required": ["language", "intent", "reply", "actions"],
"additionalProperties": False,
}
def _param_schema(self, p: Param) -> dict:
base: dict[str, Any]
if p.kind == "enum":
base = {"type": "string", "enum": list(self._choices(p))}
else:
base = {"type": p.kind}
desc = p.description + ("" if p.default is None else f" (default {p.default})")
if p.required:
return {**base, "description": desc}
if p.kind == "enum":
return {"anyOf": [base, {"type": "null"}], "description": desc}
return {"type": [p.kind, "null"], "description": desc}
[docs]
def describe(self) -> str:
"""Human-readable catalogue for the system prompt."""
lines = []
for spec in self.specs.values():
parts = []
for p in spec.params:
kind = " | ".join(self._choices(p)) if p.kind == "enum" else p.kind
tag = "required" if p.required else "optional"
parts.append(f"{p.name} <{kind}, {tag}>: {p.description}")
params = ("; ".join(parts)) if parts else "no parameters"
lines.append(f"- {spec.name}: {spec.description} [{params}]")
return "\n".join(lines)
# -------------------------------------------------------- validation
[docs]
def validate(
self, raw_actions: Any, fill_defaults: bool = True
) -> tuple[list[Action], list[str]]:
"""Validate model output. Returns (actions, errors); invalid items are dropped.
With ``fill_defaults=False`` only the parameters that were given are kept
(used for reference plans, whose unstated parameters are not compared).
"""
if raw_actions is None:
return [], []
if not isinstance(raw_actions, list):
return [], ["'actions' must be an array"]
actions: list[Action] = []
errors: list[str] = []
for i, item in enumerate(raw_actions, 1):
if not isinstance(item, Mapping):
errors.append(f"actions[{i}] is not an object")
continue
name = str(item.get("action", "")).strip().upper().replace(" ", "_")
if name not in self.specs:
errors.append(
f"actions[{i}]: unknown action '{item.get('action')}'; "
f"valid: {', '.join(self.specs)}"
)
continue
spec = self.specs[name]
unknown = set(item) - {"action"} - {p.name for p in spec.params}
if unknown:
errors.append(f"actions[{i}] ({name}): unknown parameter(s) {sorted(unknown)}")
continue
params: dict[str, Any] = {}
ok = True
for p in spec.params:
value = item.get(p.name)
if value is None or (isinstance(value, str) and not value.strip()):
if p.required:
errors.append(f"actions[{i}] ({name}): missing required '{p.name}'")
ok = False
elif p.default is not None and (fill_defaults or p.implied):
params[p.name] = p.default
continue
try:
params[p.name] = self._coerce(p, value)
except ValueError as exc:
errors.append(f"actions[{i}] ({name}): '{p.name}' {exc}")
ok = False
if ok:
actions.append(Action(name, params))
return actions, errors
def _coerce(self, p: Param, value: Any) -> Any:
if p.kind in ("number", "integer"):
if isinstance(value, bool):
raise ValueError("must be a number, got a boolean")
if isinstance(value, str):
value = value.strip().replace(",", ".")
try:
number = float(value)
except (TypeError, ValueError):
raise ValueError(f"must be a number, got {value!r}") from None
if not math.isfinite(number):
raise ValueError("must be finite")
if p.kind == "integer":
if not number.is_integer():
raise ValueError(f"must be an integer, got {value!r}")
number = int(number)
if p.minimum is not None and (
number < p.minimum or (p.exclusive_minimum and number == p.minimum)
):
op = ">" if p.exclusive_minimum else ">="
raise ValueError(f"must be {op} {p.minimum}, got {number}")
if p.maximum is not None and number > p.maximum:
raise ValueError(f"must be <= {p.maximum}, got {number}")
return number
text = str(value).strip()
if p.kind == "enum":
choices = self._choices(p)
for c in choices:
if text.casefold() == c.casefold():
return c
raise ValueError(f"must be one of {list(choices)}, got {text!r}")
return text
# ------------------------------------------------------------- expansion P
[docs]
def expand(actions: Sequence[Action]) -> list[Action]:
"""Rule-based parser P (paper Eq. 4): k model steps -> n >= k primitives."""
out: list[Action] = []
for a in actions:
if a.name == "POLYGON":
sides = int(a.params["sides"])
turn = 360.0 / sides
for _ in range(sides):
out.append(_move(a.params["side_length"], a.get("speed")))
out.append(_turn(turn, a.get("direction", "left")))
elif a.name == "RECTANGLE":
for side in (a.params["length"], a.params["width"]) * 2:
out.append(_move(side, a.get("speed")))
out.append(_turn(90.0, a.get("direction", "left")))
else:
out.append(a)
return out
def _move(distance: float, speed: float | None) -> Action:
return Action("MOVE", {"distance": float(distance), "direction": "forward", "speed": speed})
def _turn(angle: float, direction: str) -> Action:
return Action("TURN", {"angle": float(angle), "direction": direction, "angular_speed": None})
_MOTION = frozenset(spec.name for spec in _BASE_SPECS if spec.moves)
[docs]
def is_motion(actions: Iterable[Action]) -> bool:
"""True if any step commands base motion."""
return any(a.name in _MOTION for a in actions)