Source code for reli.planner

"""Language-to-action decision and parsing.

One model call maps the user's utterance c (any language) together with the robot's context (pose,
destinations, recently seen objects, optional camera frame) to a turn ``{language, intent, reply,
actions}``:

* ``language`` updates the session language state l (skipped when the user fixed the language);
* ``intent`` is the high-level interpretation r in R_int;
* ``actions`` are the k steps a_1..a_k, constrained to the action catalogue by schema-guided
  decoding and validated afterwards.

Invalid output is sent back to the model once with the validator's exact error messages
(self-repair) before the user is asked to rephrase.
"""

from __future__ import annotations

import logging
import time
from collections.abc import Sequence
from dataclasses import dataclass, field

from .actions import INTENTS, Catalog
from .config import ReLIConfig
from .llm import ChatMessage, LLMProvider, extract_json
from .prompts import Prompts, render
from .types import Action, Pose2D

log = logging.getLogger(__name__)


[docs] @dataclass class PlanningContext: pose: Pose2D language: str # current session language (BCP-47) fixed_language: str | None = None # set by the user: skip detection scene: Sequence[str] = () image_jpeg: bytes | None = None has_navigation: bool = True
[docs] @dataclass class Plan: language: str intent: str reply: str actions: list[Action] = field(default_factory=list) errors: list[str] = field(default_factory=list) raw: str = "" latency_s: float = 0.0 repaired: bool = False @property def usable(self) -> bool: if self.errors: return False return self.intent != "execute" or bool(self.actions)
[docs] class Planner: def __init__(self, cfg: ReLIConfig, provider: LLMProvider, prompts: Prompts, catalog: Catalog): self.cfg = cfg self.provider = provider self.prompts = prompts self.catalog = catalog self._schema = catalog.turn_schema() # ----------------------------------------------------------- prompting def system_prompt(self, ctx: PlanningContext) -> str: lim = self.cfg.robot.limits fixed = ctx.fixed_language language_rule = render( self.prompts["language_fixed_rule" if fixed else "language_auto_rule"], language=fixed or ctx.language, ) state = ( f"Position x={ctx.pose.x:.2f} m, y={ctx.pose.y:.2f} m in the map frame; heading " f"{ctx.pose.yaw_deg:.0f} deg (0 = +x axis, counter-clockwise positive). " f"Navigation stack: {'available' if ctx.has_navigation else 'not available'}. " f"Camera: {'available' if 'DESCRIBE_SCENE' in self.catalog else 'not available'}." ) limits = ( f"linear {lim.linear_speed_min}-{lim.linear_speed_max} m/s " f"(default {lim.linear_speed_default}), rotation up to " f"{lim.angular_speed_max_deg} deg/s (default {lim.angular_speed_default_deg})" ) dests = [] for key, d in self.cfg.destinations.items(): aliases = f" [{', '.join(d.aliases)}]" if d.aliases else "" dests.append(f"- {key}: {d.name or key}{aliases} at ({d.x:.2f}, {d.y:.2f})") system = render( self.prompts["system"], robot_name=self.cfg.robot.name, robot_description=self.cfg.robot.description.strip(), language_rule=language_rule, limits=limits, state=state, destinations="\n".join(dests) or "(none configured)", scene="\n".join(ctx.scene) or "(nothing seen yet)", catalog=self.catalog.describe(), ) return system + "\n\n" + self.prompts["json_only"].strip() # -------------------------------------------------------------- public
[docs] def plan(self, text: str, ctx: PlanningContext, history: Sequence[ChatMessage] = ()) -> Plan: """Interpret ``text``. Raises ``LLMError`` if the provider is unreachable.""" t0 = time.monotonic() system = self.system_prompt(ctx) user = ChatMessage("user", text, [ctx.image_jpeg] if ctx.image_jpeg else []) messages = [*history, user] raw = self.provider.complete(system, messages, self._schema) plan = self._parse(raw, ctx) attempts = 0 while plan.errors and attempts < self.cfg.planning.max_repair_attempts: attempts += 1 log.info("Repairing model output (attempt %d): %s", attempts, plan.errors) repair = render(self.prompts["repair"], errors="\n".join(f"- {e}" for e in plan.errors)) raw2 = self.provider.complete( system, [*messages, ChatMessage("assistant", raw), ChatMessage("user", repair)], self._schema, ) plan2 = self._parse(raw2, ctx) if len(plan2.errors) <= len(plan.errors): plan2.repaired = True plan, raw = plan2, raw2 if not plan2.errors: break plan.latency_s = time.monotonic() - t0 return plan
# ------------------------------------------------------------- parsing def _parse(self, raw: str, ctx: PlanningContext) -> Plan: try: data = extract_json(raw) except ValueError as exc: return Plan(ctx.language, "execute", "", errors=[f"invalid JSON: {exc}"], raw=raw) errors: list[str] = [] language = str(data.get("language") or "").strip()[:35] or ctx.language if ctx.fixed_language: language = ctx.fixed_language intent = str(data.get("intent") or "").strip().lower() reply = str(data.get("reply") or "").strip() actions, action_errors = self.catalog.validate(data.get("actions")) errors.extend(action_errors) if actions and intent != "execute": # Acting on a valid step list is more useful than discarding it. log.info("Model returned actions with intent '%s'; treating as execute.", intent) intent = "execute" if intent not in INTENTS: errors.append(f"'intent' must be one of {list(INTENTS)}, got {intent!r}") elif intent == "execute" and not actions and not action_errors: errors.append("intent 'execute' needs at least one action") elif intent != "execute" and not reply: errors.append(f"intent '{intent}' needs a non-empty 'reply'") return Plan(language, intent, reply, actions, errors, raw)