"""Typed, validated configuration.
Every option ReLI reads is declared here.
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
from typing import Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
log = logging.getLogger(__name__)
class _Section(BaseModel):
model_config = ConfigDict(extra="forbid", validate_assignment=True)
# --------------------------------------------------------------------- robot
class MotionLimits(_Section):
linear_speed_default: float = Field(0.2, gt=0, description="m/s")
linear_speed_min: float = Field(0.05, gt=0, description="m/s")
linear_speed_max: float = Field(1.0, gt=0, description="m/s")
angular_speed_default_deg: float = Field(30.0, gt=0, description="deg/s")
angular_speed_max_deg: float = Field(90.0, gt=0, description="deg/s")
linear_accel: float = Field(0.5, gt=0, description="m/s^2")
angular_accel_deg: float = Field(120.0, gt=0, description="deg/s^2")
@model_validator(mode="after")
def _ordered(self) -> MotionLimits:
if not self.linear_speed_min <= self.linear_speed_default <= self.linear_speed_max:
raise ValueError("require linear_speed_min <= linear_speed_default <= linear_speed_max")
if self.angular_speed_default_deg > self.angular_speed_max_deg:
raise ValueError("require angular_speed_default_deg <= angular_speed_max_deg")
return self
class ControlSettings(_Section):
rate_hz: float = Field(20.0, gt=0)
goal_tolerance_m: float = Field(0.2, gt=0, description="navigation success radius")
timeout_factor: float = Field(
2.0, ge=1.0, description="timeout = factor * nominal duration + 2 s"
)
navigation_timeout_s: float = Field(300.0, gt=0)
heading_gain: float = Field(2.0, gt=0, description="P gain on heading error (1/s)")
min_angular_speed_deg: float = Field(5.0, gt=0, description="creep speed near the target")
class Pose2DConfig(_Section):
x: float = 0.0
y: float = 0.0
yaw_deg: float = 0.0
class SimObject(_Section):
label: str
x: float
y: float
z: float = 0.0
radius: float = Field(0.25, gt=0)
class SimSettings(_Section):
realtime_factor: float = Field(
1.0, ge=0, description="1 = real time, >1 faster, 0 = as fast as possible"
)
start_pose: Pose2DConfig = Pose2DConfig()
objects: list[SimObject] = Field(
default_factory=list, description="objects visible to the simulated perception"
)
fov_deg: float = Field(70.0, gt=0, le=360)
max_range_m: float = Field(8.0, gt=0)
class RosTopics(_Section):
cmd_vel: str = "/cmd_vel"
odom: str = "/odom"
pose: str | None = Field(
"/amcl_pose",
description="geometry_msgs/PoseWithCovarianceStamped in the map frame; null = use odom",
)
color: str | None = "/camera/color/image_raw/compressed"
depth: str | None = "/camera/aligned_depth_to_color/image_raw"
camera_info: str | None = "/camera/color/camera_info"
input: str = "/reli/input"
response: str = "/reli/response"
tts: str = "/reli/tts"
image: str = "/reli/image/compressed"
emergency_stop: str = "/reli/emergency_stop"
class RosbridgeSettings(_Section):
host: str = "localhost"
port: int = 9090
ros_version: Literal[1, 2] = 1
topics: RosTopics = RosTopics()
cmd_vel_stamped: bool = False
base_frame: str = "base_link"
map_frame: str = "map"
navigation_action: str | None = Field(
None, description="default: /move_base (ROS 1) or /navigate_to_pose (ROS 2)"
)
depth_throttle_ms: int = Field(300, ge=0)
connect_timeout_s: float = Field(10.0, gt=0)
class RobotConfig(_Section):
name: str = Field("ReLI robot", description="name the robot uses for itself")
description: str = Field(
"", description="free-text identity shown to the language model (design, links, ...)"
)
backend: Literal["sim", "rosbridge"] = Field("sim", description="robot connection")
limits: MotionLimits = MotionLimits()
control: ControlSettings = ControlSettings()
sim: SimSettings = SimSettings()
rosbridge: RosbridgeSettings = RosbridgeSettings()
# ------------------------------------------------------------------ language
class LanguageConfig(_Section):
fixed: str | None = Field(
None, description="BCP-47 tag; when set, language detection is skipped"
)
default: str = Field("en", description="language before the first utterance")
# ----------------------------------------------------------------------- llm
class LLMConfig(_Section):
provider: Literal["openai", "openai_compatible", "anthropic", "gemini"] = Field(
"openai", description="chat model provider"
)
model: str = Field("gpt-5.4-mini", description="model name at the provider")
base_url: str | None = Field(None, description="server URL for openai_compatible")
api_key_env: str | None = Field(
None, description="env var holding the key; null = provider default (OPENAI_API_KEY, ...)"
)
max_output_tokens: int = Field(1024, gt=0)
temperature: float | None = Field(
0.0, description="dropped automatically for models that do not accept it"
)
timeout_s: float = Field(60.0, gt=0)
retries: int = Field(2, ge=0)
structured_output: Literal["auto", "schema", "json", "prompt"] = "auto"
history_turns: int = Field(6, ge=0, description="previous exchanges kept as dialogue context")
attach_image: bool = Field(
False, description="send the current camera frame to a vision-language model"
)
request_options: dict = Field(
default_factory=dict, description="extra provider-specific request body fields"
)
def api_key(self) -> str | None:
env = self.api_key_env or {
"openai": "OPENAI_API_KEY",
"anthropic": "ANTHROPIC_API_KEY",
"gemini": "GEMINI_API_KEY",
}.get(self.provider)
return os.getenv(env) if env else None
class PlanningConfig(_Section):
max_repair_attempts: int = Field(1, ge=0, description="self-repair rounds for invalid output")
# ------------------------------------------------------------------- consent
class ConsentConfig(_Section):
policy: Literal["never", "multi_step", "motion", "always"] = "multi_step"
timeout_s: float = Field(120.0, gt=0, description="a plan awaiting consent expires after this")
method: Literal["llm", "embedding"] = "llm"
embedding_model: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
margin: float = Field(0.05, ge=0, description="|v^T psi(r) + b| below this is 'unclear'")
positive_phrases: list[str] = Field(
default_factory=lambda: [
"yes",
"y",
"ok",
"okay",
"sure",
"go ahead",
"do it",
"proceed",
"confirm",
"ja",
"oui",
"sí",
"si",
"sim",
"da",
"tak",
"evet",
"hai",
"是",
"好",
"はい",
"ndiyo",
"ee",
"bẹẹni",
"haan",
"हाँ",
"نعم",
]
)
negative_phrases: list[str] = Field(
default_factory=lambda: [
"no",
"n",
"nope",
"cancel",
"abort",
"don't",
"do not",
"stop",
"nein",
"non",
"não",
"nie",
"hayır",
"iie",
"不",
"不要",
"いいえ",
"hapana",
"rara",
"nahin",
"नहीं",
"لا",
"mba",
]
)
# -------------------------------------------------------------------- safety
class Workspace(_Section):
x_min: float
x_max: float
y_min: float
y_max: float
@model_validator(mode="after")
def _ordered(self) -> Workspace:
if self.x_min >= self.x_max or self.y_min >= self.y_max:
raise ValueError("workspace requires x_min < x_max and y_min < y_max")
return self
class SafetyConfig(_Section):
enabled: bool = Field(True, description="per-step limits and plan rollout")
on_violation: Literal["reject", "clamp"] = "reject"
allowed_actions: list[str] | None = Field(None, description="null = whole catalogue")
max_distance_m: float = Field(10.0, gt=0)
max_turn_deg: float = Field(720.0, gt=0)
max_wait_s: float = Field(300.0, gt=0)
max_plan_steps: int = Field(40, gt=0)
min_clearance_m: float = Field(0.3, ge=0)
workspace: Workspace | None = None
rollout_step_m: float = Field(0.1, gt=0)
stop_phrases: list[str] = Field(
default_factory=lambda: [
"stop",
"halt",
"emergency stop",
"stopp",
"arrête",
"arrete",
"para",
"pare",
"fermati",
"alto",
"stój",
"dur",
"停",
"停下",
"停止",
"止まれ",
"ストップ",
"simama",
"kwụsị",
"توقف",
"रुको",
],
description="exact (normalised) utterances that stop the robot without a model call",
)
# ---------------------------------------------------------------- perception
class VerifierConfig(_Section):
model: str | None = Field(
None, description="dual encoder, e.g. google/siglip2-base-patch16-224; null = off"
)
temperature: float | None = Field(
None, gt=0, description="T in Eq. 6; null = model's learned logit scale"
)
energy_threshold: float | None = Field(
None, description="reject regions with energy above this (Eq. 6); calibrate per model"
)
crop_margin: float = Field(0.1, ge=0)
class DegradationConfig(_Section):
beta: float = Field(1.0, ge=0, description="sensitivity in Eq. 7")
reference_luma: float = Field(0.35, gt=0, le=1, description="mean luma below this = dark")
reference_sharpness: float = Field(100.0, gt=0, description="Laplacian variance below = blur")
class DepthConfig(_Section):
min_m: float = Field(0.2, ge=0)
max_m: float = Field(10.0, gt=0)
window_px: int = Field(7, ge=1, description="half-size of the centroid neighbourhood (Eq. 8)")
monocular_model: str | None = Field(
"depth-anything/Depth-Anything-V2-Metric-Indoor-Small-hf",
description="metric depth model used when the camera has no depth; null = off",
)
class TrackingConfig(_Section):
gate_m: float = Field(0.6, gt=0)
ttl_s: float = Field(300.0, gt=0)
process_noise: float = Field(0.01, ge=0, description="m^2/s")
noise_base_m: float = Field(0.03, gt=0)
noise_per_m2: float = Field(0.01, ge=0, description="depth noise grows with range^2")
class SearchConfig(_Section):
enabled: bool = True
step_deg: float = Field(60.0, gt=0, le=180)
max_deg: float = Field(360.0, gt=0, le=720)
class PerceptionConfig(_Section):
enabled: bool = True
detector: Literal["sam3", "grounding_dino", "owlv2", "yolo_world", "sim"] = "sam3"
model: str | None = Field(None, description="checkpoint id; null = detector default")
device: str = "auto"
score_threshold: float = Field(0.4, ge=0, le=1)
mask_threshold: float = Field(0.5, ge=0, le=1)
max_detections: int = Field(20, gt=0)
mask_quality_threshold: float = Field(0.4, ge=0, le=1, description="tau_q")
vocabulary: list[str] = Field(
default_factory=lambda: [
"person",
"chair",
"table",
"desk",
"door",
"monitor",
"laptop",
"cup",
"bottle",
"sofa",
"bookshelf",
"trash bin",
"plant",
"backpack",
],
description="labels for scene descriptions and verifier distractors",
)
verifier: VerifierConfig = VerifierConfig()
degradation: DegradationConfig = DegradationConfig()
depth: DepthConfig = DepthConfig()
tracking: TrackingConfig = TrackingConfig()
search: SearchConfig = SearchConfig()
approach_distance_m: float = Field(0.6, gt=0, description="stand-off when going to objects")
# -------------------------------------------------------------------- camera
class Intrinsics(_Section):
fx: float = Field(gt=0)
fy: float = Field(gt=0)
cx: float
cy: float
class Extrinsics(_Section):
"""Camera body pose in the robot base frame (REP 103: x forward, y left, z up)."""
x: float = 0.0
y: float = 0.0
z: float = 0.0
roll_deg: float = 0.0
pitch_deg: float = 0.0
yaw_deg: float = 0.0
class RealSenseSettings(_Section):
width: int = 640
height: int = 480
fps: int = 30
class CameraConfig(_Section):
source: Literal["none", "webcam", "realsense", "robot"] = "none"
webcam_index: int = 0
intrinsics: Intrinsics | None = Field(None, description="null = from driver or hfov_deg")
hfov_deg: float = Field(69.0, gt=0, lt=180)
extrinsics: Extrinsics = Extrinsics()
realsense: RealSenseSettings = RealSenseSettings()
# -------------------------------------------------------------- destinations
class Destination(_Section):
name: str | None = None
aliases: list[str] = Field(default_factory=list)
x: float
y: float
yaw_deg: float | None = None
# --------------------------------------------------------------------- misc
class SpeechConfig(_Section):
backend: Literal["browser", "faster_whisper", "openai"] = "browser"
model: str = "large-v3-turbo"
device: str = "auto"
compute_type: str = "default"
class WebConfig(_Section):
host: str = "127.0.0.1"
port: int = 8080
video_fps: float = Field(10.0, gt=0)
jpeg_quality: int = Field(80, ge=10, le=100)
overlay_detections: bool = True
detection_refresh_hz: float = Field(1.0, gt=0)
class LoggingConfig(_Section):
level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
dir: str = Field("runs", description="interaction logs, relative to the working directory")
cache_translations: bool = True
[docs]
class ReLIConfig(_Section):
robot: RobotConfig = RobotConfig()
language: LanguageConfig = LanguageConfig()
llm: LLMConfig = LLMConfig()
planning: PlanningConfig = PlanningConfig()
consent: ConsentConfig = ConsentConfig()
safety: SafetyConfig = SafetyConfig()
perception: PerceptionConfig = PerceptionConfig()
camera: CameraConfig = CameraConfig()
destinations: dict[str, Destination] = Field(
default_factory=dict,
description="named places in the map frame: key -> {name, aliases, x, y, yaw_deg}",
)
speech: SpeechConfig = SpeechConfig()
web: WebConfig = WebConfig()
logging: LoggingConfig = LoggingConfig()
prompts_file: str | None = Field(None, description="override the packaged prompt templates")
# Directory that relative paths in this file resolve against.
base_dir: Path = Field(default_factory=Path.cwd, exclude=True)
[docs]
@classmethod
def load(cls, path: str | Path) -> ReLIConfig:
"""Load a YAML file, or a bundled example by name (``sim``, ``romr_ros1``, ...).
``extends: other.yaml`` in a file merges it over a base file.
"""
path = find_file(path, "configs", ".yaml").resolve()
data = _read_yaml(path, seen=())
try:
cfg = cls.model_validate({**data, "base_dir": path.parent})
except ValidationError as exc:
raise ValueError(f"Invalid configuration in {path}:\n{exc}") from exc
log.info("Loaded configuration from %s", path)
return cfg
def resolve(self, relative: str | Path) -> Path:
p = Path(relative).expanduser()
return p if p.is_absolute() else (self.base_dir / p)
@model_validator(mode="after")
def _check_destinations(self) -> ReLIConfig:
ws = self.safety.workspace
for key, dest in self.destinations.items():
if ws and not (ws.x_min <= dest.x <= ws.x_max and ws.y_min <= dest.y <= ws.y_max):
raise ValueError(f"destination '{key}' lies outside safety.workspace")
return self
def bundled(kind: str) -> dict[str, Path]:
"""Example files shipped with the package: ``bundled("configs")`` -> {name: path}."""
from importlib import resources
root = Path(str(resources.files("reli").joinpath(kind)))
return {
p.name.split(".")[0]: p
for p in sorted(root.glob("*"))
if p.is_file() and not p.name.startswith(("_", "."))
}
def find_file(name: str | Path, kind: str, suffixes: str | tuple[str, ...]) -> Path:
"""An existing path, else a bundled example with that name (``sim`` or ``sim.yaml``)."""
path = Path(name).expanduser()
if path.is_file():
return path
examples = bundled(kind)
stem = path.name
for suffix in (suffixes,) if isinstance(suffixes, str) else suffixes:
stem = stem.removesuffix(suffix)
if path.parent == Path(".") and stem in examples:
return examples[stem]
raise FileNotFoundError(
f"{name}: no such file, and no bundled {kind[:-1]} of that name "
f"(bundled: {', '.join(examples)})"
)
def _read_yaml(path: Path, seen: tuple[Path, ...]) -> dict:
if path in seen:
raise ValueError(f"circular 'extends' chain: {' -> '.join(map(str, (*seen, path)))}")
with open(path, encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
if not isinstance(data, dict):
raise ValueError(f"{path}: top level must be a mapping")
base = data.pop("extends", None)
if base is None:
return data
base_path = path.parent / base
if not base_path.is_file(): # a bundled example by name, e.g. "extends: sim"
base_path = find_file(base, "configs", ".yaml")
return _merge(_read_yaml(base_path.resolve(), (*seen, path)), data)
def _merge(base: dict, override: dict) -> dict:
"""Recursive dict merge; lists and scalars in ``override`` replace those in ``base``."""
out = dict(base)
for key, value in override.items():
if isinstance(value, dict) and isinstance(out.get(key), dict):
out[key] = _merge(out[key], value)
else:
out[key] = value
return out
def setup_logging(cfg: ReLIConfig) -> None:
logging.basicConfig(
level=getattr(logging, cfg.logging.level),
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)